Esempio n. 1
0
def taobao_callback(request):
    top_appkey = request.GET['top_appkey']
    top_sign = request.GET["top_sign"]
    top_parameters = request.GET['top_parameters']
    top_session = request.GET['top_session']  #get 1
    top_secret = TAOBAO_SECRET

    # validate the signature
    m = md5.new()
    m.update(top_appkey)
    m.update(top_parameters)
    m.update(top_session)
    m.update(top_secret)
    base64str = base64.b64encode(m.digest())
    if cmp(base64str, top_sign) == 0:
        dec_parameters = base64.decodestring(unquote(top_parameters))
        array_parameters = dec_parameters.split('&')
        refresh_token = array_parameters[3].split('=')[1]  #get2

        sign_str = "appkey" + TAOBAO_KEY + "refresh_token" + refresh_token + "sessionkey" + top_session + TAOBAO_SECRET
        hash = md5.new()
        hash.update(sign_str)
        sign = hash.hexdigest().upper()
        access_token_url = 'http://container.open.taobao.com/container/refresh?appkey=%s&refresh_token=%s&sessionkey=%s&sign=%s' \
                           % (TAOBAO_KEY, refresh_token, top_session, sign)
        info = JSONDecoder().decode(
            urllib2.urlopen(access_token_url, "").read())

        uid = request.session.get('uid', default=None)
        if uid is not None:
            p = Profile.objects.get(pk=uid)
            params = {
                'method': 'taobao.user.get',
                'session': info['top_session'],
                'fields': 'nick',
                'partner_id': 'top-apitools',
                'format': 'json'
            }

            op = OpenTaobao(TAOBAO_KEY, TAOBAO_SECRET)
            user_info = JSONDecoder().decode(op.get_result(params))
            en_info = JSONEncoder().encode(info)
            d = DataSource.objects.create(
                source_name="taobao",
                auth_info=en_info,
                account_name=user_info['user_get_response']['user']['nick'],
                owner=p)

            sync_source(d)
            return redirect('/datasources')
        else:
            return redirect('/login')
    else:
        red_url = "http://container.open.taobao.com/container?appkey=%s&encode=utf-8" % (
            TAOBAO_KEY)
        return redirect(red_url)
Esempio n. 2
0
def taobao_callback(request):
    top_appkey = request.GET['top_appkey']
    top_sign = request.GET["top_sign"]
    top_parameters = request.GET['top_parameters']
    top_session = request.GET['top_session'] #get 1
    top_secret = TAOBAO_SECRET
    
    # validate the signature
    m = md5.new()
    m.update(top_appkey)
    m.update(top_parameters)
    m.update(top_session)
    m.update(top_secret)
    base64str = base64.b64encode(m.digest())
    if cmp(base64str, top_sign)==0:    
        dec_parameters = base64.decodestring(unquote(top_parameters))
        array_parameters = dec_parameters.split('&')
        refresh_token = array_parameters[3].split('=')[1] #get2
        
        
        sign_str = "appkey"+TAOBAO_KEY+"refresh_token"+refresh_token+"sessionkey"+top_session+TAOBAO_SECRET
        hash = md5.new()
        hash.update(sign_str)
        sign = hash.hexdigest().upper()
        access_token_url = 'http://container.open.taobao.com/container/refresh?appkey=%s&refresh_token=%s&sessionkey=%s&sign=%s' \
                           % (TAOBAO_KEY, refresh_token, top_session, sign)
        info = JSONDecoder().decode(urllib2.urlopen(access_token_url, "").read())
        
     
        uid = request.session.get('uid', default = None)
        if uid is not None:
            p = Profile.objects.get(pk = uid)
            params = {
                        'method':'taobao.user.get',
                        'session':info['top_session'],
                        'fields':'nick',
                        'partner_id':'top-apitools',
                        'format':'json'
                    }

            op = OpenTaobao(TAOBAO_KEY,TAOBAO_SECRET)
            user_info = JSONDecoder().decode(op.get_result(params))
            en_info = JSONEncoder().encode(info)
            d = DataSource.objects.create(source_name="taobao", auth_info=en_info, account_name=user_info['user_get_response']['user']['nick'], owner=p)
            
            sync_source(d)
            return redirect('/datasources')
        else:
            return redirect('/login')
    else:
        red_url = "http://container.open.taobao.com/container?appkey=%s&encode=utf-8" % (TAOBAO_KEY)
        return redirect(red_url)
Esempio n. 3
0
def sync_taobao(did, page, new_latest):
    d = DataSource.objects.get(pk=did)

    # here refresh the sessionkey

    info = JSONDecoder().decode(d.auth_info)
    sign_str = "appkey" + TAOBAO_KEY + "refresh_token" + info[
        'refresh_token'] + "sessionkey" + info['top_session'] + TAOBAO_SECRET
    hash = md5.new()
    hash.update(sign_str)
    sign = hash.hexdigest().upper()
    access_token_url = 'http://container.open.taobao.com/container/refresh?appkey=%s&refresh_token=%s&sessionkey=%s&sign=%s' \
                       % (TAOBAO_KEY, info['refresh_token'], info['top_session'], sign)
    new_info = JSONDecoder().decode(
        urllib2.urlopen(access_token_url, "").read())
    info['top_session'] = new_info['top_session']
    info['refresh_token'] = new_info['refresh_token']
    d.auth_info = JSONEncoder().encode(info)
    d.save(force_update=True)

    # here begin the goods sync
    info = JSONDecoder().decode(d.auth_info)
    params = {
        'method': 'taobao.trades.bought.get',
        'session': info['top_session'],
        'fields':
        'tid,created,seller_nick,orders.oid,orders.pic_path,orders.total_fee,orders.title',
        'partner_id': 'top-apitools',
        'format': 'json',
        'page_no': page,
        'status': 'TRADE_FINISHED'
    }

    op = OpenTaobao(TAOBAO_KEY, TAOBAO_SECRET)
    deal_info = JSONDecoder().decode(
        op.get_result(params))['trades_bought_get_response']

    if deal_info.has_key('trades') and deal_info['trades']:
        if (page == 1):
            print "now is page1"
            new_latest = deal_info['trades']['trade'][0]['tid']
        for trade in deal_info['trades']['trade']:
            if (info.has_key('latest') and (trade['tid'] == info['latest'])):
                info['latest'] = new_latest
                d.auth_info = JSONEncoder().encode(info)
                d.save(force_update=True)

                sync_taobao.apply_async(
                    args=[did, 1, None],
                    countdown=84000)  # wait for tommorow to do again this task
                print "I am break and do it tomorrow"
                break

            for order in trade['orders']['order']:
                print "I am in again"
                new_paw = Paw.objects.create(
                    source=d,
                    type="taobao",
                    content=u"在" + trade['seller_nick'] + u"店</br>花费" +
                    order['total_fee'] + u"</br>购买了" + order["title"],
                    create_time=trade['created'])
                if order.has_key('pic_path'):
                    new_img = Img(album=new_paw,
                                  upload_time=new_paw.create_time)
                    origin_tmp = NamedTemporaryFile(delete=True)
                    origin_tmp.write(urllib2.urlopen(order['pic_path']).read())
                    origin_tmp.flush()
                    new_img.original.save(origin_tmp.name.split('/')[-1] +
                                          '.jpg',
                                          File(origin_tmp),
                                          save=False)
                    thumb_tmp = NamedTemporaryFile(delete=True)
                    thumb_tmp.write(
                        urllib2.urlopen(order['pic_path'] + '_sum.jpg').read())
                    thumb_tmp.flush()
                    new_img.thumbnail.save(thumb_tmp.name.split('/')[-1] +
                                           '.jpg',
                                           File(thumb_tmp),
                                           save=True)

        if not (info.has_key('latest') and (trade['tid'] == info['latest'])):
            print "do it 1min later"
            sync_taobao.apply_async(args=[did, page + 1, new_latest],
                                    countdown=60)
    else:
        if new_latest is not None:
            info['latest'] = new_latest
            d.auth_info = JSONEncoder().encode(info)
            d.save(force_update=True)
        print "do it tommorrow"
        sync_taobao.apply_async(args=[did, 1, None], countdown=84000)
Esempio n. 4
0
def sync_taobao(did, page, new_latest):
    d = DataSource.objects.get(pk=did)
    
    # here refresh the sessionkey
    
    info = JSONDecoder().decode(d.auth_info)
    sign_str = "appkey"+TAOBAO_KEY+"refresh_token"+info['refresh_token']+"sessionkey"+info['top_session']+TAOBAO_SECRET
    hash = md5.new()
    hash.update(sign_str)
    sign = hash.hexdigest().upper()
    access_token_url = 'http://container.open.taobao.com/container/refresh?appkey=%s&refresh_token=%s&sessionkey=%s&sign=%s' \
                       % (TAOBAO_KEY, info['refresh_token'], info['top_session'], sign)
    new_info = JSONDecoder().decode(urllib2.urlopen(access_token_url, "").read())
    info['top_session'] = new_info['top_session']
    info['refresh_token'] = new_info['refresh_token']
    d.auth_info = JSONEncoder().encode(info)
    d.save(force_update=True)
    
    # here begin the goods sync
    info = JSONDecoder().decode(d.auth_info)
    params = {
                        'method':'taobao.trades.bought.get',
                        'session':info['top_session'],
                        'fields':'tid,created,seller_nick,orders.oid,orders.pic_path,orders.total_fee,orders.title',
                        'partner_id':'top-apitools',
                        'format':'json',
                        'page_no':page,
                        'status':'TRADE_FINISHED'
                    }

    op = OpenTaobao(TAOBAO_KEY,TAOBAO_SECRET)
    deal_info = JSONDecoder().decode(op.get_result(params))['trades_bought_get_response']
    
    if deal_info.has_key('trades') and deal_info['trades']:
        if (page == 1):
            print "now is page1"
            new_latest = deal_info['trades']['trade'][0]['tid']
        for trade in deal_info['trades']['trade']:
            if (info.has_key('latest') and (trade['tid'] == info['latest'])):
                info['latest'] = new_latest
                d.auth_info = JSONEncoder().encode(info)
                d.save(force_update=True)
                
                sync_taobao.apply_async(args = [did, 1, None], countdown = 84000) # wait for tommorow to do again this task
                print "I am break and do it tomorrow"
                break
            
            for order in trade['orders']['order']:
                print "I am in again"
                new_paw = Paw.objects.create(source=d, type="taobao", content=u"在"+trade['seller_nick']+u"店</br>花费"+order['total_fee']+u"</br>购买了"+order["title"], create_time=trade['created'])
                if order.has_key('pic_path'):
                    new_img = Img(album = new_paw, upload_time=new_paw.create_time)
                    origin_tmp = NamedTemporaryFile(delete=True)
                    origin_tmp.write(urllib2.urlopen(order['pic_path']).read())
                    origin_tmp.flush()
                    new_img.original.save(origin_tmp.name.split('/')[-1]+'.jpg', File(origin_tmp), save=False)
                    thumb_tmp = NamedTemporaryFile(delete=True)
                    thumb_tmp.write(urllib2.urlopen(order['pic_path']+'_sum.jpg').read())
                    thumb_tmp.flush()
                    new_img.thumbnail.save(thumb_tmp.name.split('/')[-1]+'.jpg', File(thumb_tmp), save=True)
            
        if not (info.has_key('latest') and (trade['tid'] == info['latest'])):
            print "do it 1min later"
            sync_taobao.apply_async(args = [did, page+1, new_latest], countdown = 60)
    else:
        if new_latest is not None:
            info['latest'] = new_latest
            d.auth_info = JSONEncoder().encode(info)
            d.save(force_update=True)
        print "do it tommorrow"    
        sync_taobao.apply_async(args = [did, 1, None], countdown = 84000)