Exemplo n.º 1
0
 def test_auth(self):
     #Use refresh token to get new access token
     profile = Profile.objects.get(pk=1)
     args = {
               'client_id': settings.RENREN_APP_API_KEY,
               'client_secret': settings.RENREN_APP_SECRET_KEY,
               'refresh_token' : profile.renren_refresh_token, 
               'grant_type' : 'refresh_token',
             }
     response = urllib.urlopen(RENREN_ACCESS_TOKEN_URI + "?" + urllib.urlencode(args)).read()
     parsed = json.loads(response)
     access_token = parsed["access_token"]
     refresh_token = parsed['refresh_token']
     
     #use access token to get new session key
     session_key_request_args = dict(oauth_token=access_token)
     response = urllib.urlopen(RENREN_SESSION_KEY_URI + "?" + urllib.urlencode(session_key_request_args)).read()
     session_key = json.loads(response)["renren_token"]["session_key"]
     
     #Store the updated data
     profile.renren_refresh_token = refresh_token
     if profile.renren_access_token != access_token:
         print 'access token changed!'
     profile.renren_access_token = access_token
     profile.save()
     
     
     client = RenRenAPIClient(access_token, None, settings.RENREN_APP_API_KEY, settings.RENREN_APP_SECRET_KEY)
     
     #get user info with session key
     params = dict(method="users.getInfo", fields="uid,name,tinyurl,headurl")
     rruser = client.request(params)
     user_info = parse_json(rruser)[0]
     print user_info['tinyurl']
     self.stdout.write('Finished authorization\n')
     
     from main.utils import generate_random_file_name
     gift = Wishlist_Gift.objects.get(taobao_id=13668834356)
     buyers = Wishlist_User.objects.filter(pk__gt=10)
     buyers_str = ','.join([b.renren_name.encode('utf-8') for b in buyers])
     buyers_renren_id = [b.renren_account for b in buyers]
     caption = '我向' + buyers_str + '许下了心愿:' + gift.title.encode('utf-8') + '。来许愿板帮我实现吧:) ' + 'give'
     params = dict(method="photos.upload", caption=caption)
     temp_name = generate_random_file_name(32)
     temp_file_addr = settings.MEDIA_ROOT + 'apps/wishlist/' + temp_name
     temp_file = open(temp_file_addr, 'wb')
     temp_file.write(urllib2.urlopen(gift.pic_url).read())
     temp_file.close()
     headers,postdata = client.pack_image(temp_file_addr, params, caption)
     conn = httplib.HTTPConnection('api.renren.com')
     conn.request('POST', 'http://api.renren.com/restserver.do', headers=headers, body=postdata)
     resp = conn.getresponse()
     
     p_info = parse_json(resp.read())
     try:
         img = Image.open(temp_file_addr)
         width, height = img.size
         #At most three friends can be wished for, so this is more than enough
         pos = ((130,150), (130,470), (260,310), (390,150), (390,470))
         nf = len(buyers_renren_id)
         pid = p_info['pid']
         uid = p_info['uid']
         for i in range(nf): 
             params = dict(method="photos.tag",photo_id=pid,owner_id=uid,frame_width=80,frame_height=80)
             params["photo_width"] = width
             params["photo_height"] = height
             params["top"] = pos[i][0]
             params["left"] = pos[i][1]
             params["tagged_user_id"] = buyers_renren_id[i]
             client.request(params)
     except:
         pass
Exemplo n.º 2
0
def suggest_follow(request):
    """
    Suggest both user and topic to follow
    """
    if not assert_register(request):
        return redirect('main.views.index.index')
    template_name = 'main/account/sign_up3.html'
    if request.session['status'] == 'complete_profile':
        template_name = 'main/account/registration_follow.html'
    profile = Profile.objects.get(pk=request.session['uid'])
#    if not (profile.reader_access_token or profile.renren_account or profile.sina_account):
#        messages.error(request, '请至少连接一个账号')
#        return redirect(APP_URL + "register/connect/")
    
    if request.session.has_key('name'):
        name = request.session['name']
    else: name = profile.name
    
    if request.session.has_key('bio'):
        bio = request.session['bio']
    elif profile.bio: 
        bio = profile.bio
    else:
        bio = ''
    
    #If user has connected with RenRen, then set his RenRen image by default
    #Reference: http://stackoverflow.com/questions/1393202/django-add-image-in-an-imagefield-from-image-url
    try:
        if profile.image and profile.image != 'profile/profile100x100.jpg':
            raise Exception
        
        from PIL import Image #@UnresolvedImport
        #For handling weired bug of PIL Linux package that only identifies BMP image;
        # See http://www.chipx86.com/blog/2008/07/25/django-tips-pil-imagefield-and-unit-tests/
        Image.init()
        import urllib2
        from main.utils import generate_random_file_name
        import os

        dot_index = profile.renren_head_url.rfind('.')
        image_extension = profile.renren_head_url[dot_index:]
        image_name =  generate_random_file_name(32)+image_extension 
        
        temp_name = generate_random_file_name(32)+image_extension
        temp_file_addr = MEDIA_ROOT + 'profile/' + temp_name
        temp_file = open(temp_file_addr, 'wb')
        temp_file.write(urllib2.urlopen(profile.renren_head_url).read())
        temp_file.close()
        temp_file = open(temp_file_addr, 'rb') #open for read and assign to image field in model
        
        #Deletes old image if exists
        if profile.image and profile.image != 'profile/profile100x100.jpg':
            image_addr = MEDIA_ROOT + profile.image.name
            os.remove(image_addr) #If path is a directory, OSError is raised;So no worry about removing directory
        if profile.image_small and profile.image_small != 'profile/profile25x25.jpg':
            image_small_addr = MEDIA_ROOT + profile.image_small.name
            os.remove(image_small_addr)
        
        
        profile.image.save(image_name, temp_file)
        image_small_name =  generate_random_file_name(32)+image_extension 
        profile.image_small.save(image_small_name, temp_file)
        profile.save()
        
        temp_file.close()
        os.remove(temp_file_addr)
        
    except Exception, e:
        error = repr(e)
        pass
Exemplo n.º 3
0
def add_wishlist(request):
    """
    Validates and saves the wishlist, all items passed here should already exist
    Since the invenience of escape and unquote string passed by javascript(results in %u..), use csrf_exempt
    This post is helpful of unescape unicode, but does not work: http://blog.tarotoast.com/2008/03/16/425/
    """
    if 'user_id' not in request.session:
        return HttpResponse('{"code":"1","msg":"尚未授权"}')
    creator_id = request.session['user_id']
    creator = Wishlist_User.objects.get(pk=creator_id)
    #Fill in for next time use
    creator.cell = request.POST['cellphone']
    creator.address = request.POST['address']
    creator.email = request.POST['email']
    creator.save() 
    client = RenRenAPIClient(creator.renren_access_token, None, RENREN_APP_KEY, RENREN_APP_SECRET)
    buyer_ids = request.POST['buyers_str'].strip(',').split(',')
    item_ids = request.POST['items_str'].strip(',').split(',')
    pub_photo = True if request.POST['pub_photo'] == 'true' else False
    pub_status = True if  request.POST['pub_status'] == 'true' else False
    notes = request.POST['notes_str'].strip('`#`').split('`#`')
    notes_dict = {}
    for note in notes:
        sindex = note.find(':')
        note_str = note[sindex+1:]
        notes_dict[note[:sindex]] = note_str if note_str != u'款式备注' else ''
    
    gifts = []
    for item_id in item_ids:        
            gift = Wishlist_Gift.objects.get(taobao_id=long(item_id))
            gifts.append(gift)     
    buyers = []
    for buyer_id in buyer_ids:        
        buyer, created = Wishlist_User.objects.get_or_create(renren_account=long(buyer_id))
        if created: #Loop up the info from friends table
            #try:
                friend_info = Wishlist_Friends.objects.filter(friend_renren=long(buyer_id))[0]
                buyer.renren_name = friend_info.friend_name
                buyer.sex = friend_info.friend_sex
                buyer.renren_tiny_url = friend_info.friend_tiny_url
                buyer.renren_head_url = friend_info.friend_head_url
                buyer.save()
            #except:
            #    pass
        buyers.append(buyer)    
        wishlist = Wishlist()
        wishlist.creator_id = creator_id
        wishlist.buyer = buyer
        wishlist.cell = request.POST['cellphone']
        wishlist.address = request.POST['address']
        wishlist.email = request.POST['email']
        wishlist.love_words = request.POST['love_words']
        wishlist.pub_photo = pub_photo
        wishlist.pub_status = pub_status
        wishlist.save()
        
        for gift in gifts:
            relation = Wishlist_Membership(wishlist=wishlist, gift=gift, note=notes_dict[item_id])
            relation.save()
    
    #Notify all the buyers
    params = {
              'method':'notifications.send',
              'format' : 'json',
              'to_ids': request.POST['buyers_str'].strip(','),
              'notification': '<xn:name uid="' + str(creator.renren_account) + '" linked="true"/> 向你许下一个心愿,去<a href="' + RENREN_APP_URL + 'give/">许愿板</a>看看吧!'
    }
    result = parse_json(client.request(params))  #On success return: { "result" : 1 }
    
    
    pub_photo = False #Disable this function
    if pub_photo:
        try:
            buyers_names = ','.join([b.renren_name.encode('utf-8') for b in buyers])
            buyers_renren_id = [b.renren_account for b in buyers]       
            for gift in gifts:
                caption = '我向' + buyers_names + '许下了心愿:' + gift.title.encode('utf-8') + '。来许愿板帮我实现吧:) ' + RENREN_APP_URL + 'give/'
                params = dict(method="photos.upload", caption=caption)
                temp_name = generate_random_file_name(32)
                temp_file_addr = settings.MEDIA_ROOT + 'apps/wishlist/' + temp_name
                temp_file = open(temp_file_addr, 'wb')
                temp_file.write(urllib2.urlopen(gift.pic_url).read())
                temp_file.close()
                headers,postdata = client.pack_image(temp_file_addr, params, caption)
                conn = httplib.HTTPConnection('api.renren.com')
                conn.request('POST', 'http://api.renren.com/restserver.do', headers=headers, body=postdata)
                resp = conn.getresponse()
                
                p_info = parse_json(resp.read())
                img = Image.open(temp_file_addr)
                width, height = img.size
                #At most three friends can be wished for, so this is more than enough
                pos = ((130,150), (130,470), (260,310), (390,150), (390,470))
                nf = len(buyers_renren_id)
                pid = p_info['pid']
                uid = p_info['uid']
                for i in range(nf): 
                    params = dict(method="photos.tag",photo_id=pid,owner_id=uid,frame_width=80,frame_height=80)
                    params["photo_width"] = width
                    params["photo_height"] = height
                    params["top"] = pos[i][0]
                    params["left"] = pos[i][1]
                    params["tagged_user_id"] = buyers_renren_id[i]
                    client.request(params)
                os.remove(temp_file_addr)
        except Exception,e:
            #logger.error(e)
            pass