Esempio n. 1
0
 def get(self, action):
     if action == 'request':
         expired = datetime.datetime.now() - datetime.timedelta(minutes=10)
         expired_tokens = OAuthRequestToken.all().filter('created <', expired).fetch(20)
         for token in expired_tokens:
             token.delete()
             
     elif action == 'access':
         expired = datetime.datetime.now() - datetime.timedelta(hours=6)
         expired_tokens = OAuthAccessToken.all().filter('modified <', expired).fetch(20)
         
         q = taskqueue.Queue('background')
         for i, token in enumerate(expired_tokens):
             key_name = token.key().name()
             t = taskqueue.Task(url='/task/access', params=dict(key_name=key_name), countdown=i*2)
             q.add(t)
     
     elif action == 'graph':
         q = taskqueue.Queue('fastest')
         t = taskqueue.Task(url='/task/graph')
         q.add(t)
         
     elif action == 'image':
         expired = datetime.datetime.now() - datetime.timedelta(days=7)
         expired_tokens = UserStatus.all().filter('profile_image_updated <', expired).fetch(10)
         
         q = taskqueue.Queue('background')
         for i, token in enumerate(expired_tokens):
             key_name = token.key().name()
             t = taskqueue.Task(url='/task/image', params=dict(key_name=key_name), countdown=i*2)
             q.add(t)
Esempio n. 2
0
 def verify_oauth_token(self, key_name):
     ent = OAuthAccessToken.get_by_key_name(key_name)
     if not ent: return True
     
     token  = dict(token        = ent.oauth_token,
                   token_secret = ent.oauth_token_secret)
     
     conf = DBYAML.load('oauth')
     consumer = dict(consumer_key    = conf.get('consumer_key'   ),
                     consumer_secret = conf.get('consumer_secret'))
     
     oauth = OAuth(consumer, token)        
     try:
         res = TwitterAPI(oauth).verify()
         
     except urlfetch.DownloadError:
         return False
         
     except urlfetch.InvalidURLError:
         logging.debug('delete: access token')
         ent.delete()
         return True
     
     else:
         ent.randint = random.randint(0, 1000)
         ent.put()
         return res
Esempio n. 3
0
    def callback(self):
        oauth_token = self.handler.request.get('oauth_token')
        if not oauth_token: self.login()
        
        chk = libs.cpu.CPUChecker("auth.callback")
        
        # Request Token
        chk.kokokara()
        request_token = OAuthRequestToken.get_request_token(oauth_token)
        chk.kokomade("OAuthRequestToken.get_request_token")
        if not request_token:
            logging.warning('callback: None Request Token')
            return

        chk.kokokara()
        access_url = self.client. \
            get_data_from_signed_url(self.client.access_token_url, request_token)
        request_token.delete()
        chk.kokomade("request_token.delete")
        
        # Access Token
        try:
            params = dict(token.split('=') for token in access_url.split('&'))
        except:
            logging.warning('callback: Invalid URL=%s' % access_url)
            return
        
        name = params.get('screen_name')
        if not name:
            logging.warning('callback: screen_name is None')
            return
        
        chk.kokokara()
        access_token = OAuthAccessToken.get_access_token(params)
        access_token._name = name
        chk.kokomade("OAuthAccessToken.get_access_token")
        
        return access_token
Esempio n. 4
0
def random_tweet(via, count=1):
    
    conf = DBYAML.load('oauth')
    if not conf: return
    
    words = DBYAML.load('words')
    if not words: return
    
    format = DBYAML.load('format')
    if not format: format = '%s'
    
    consumer = dict(consumer_key    = conf.get('consumer_key'   ),
                    consumer_secret = conf.get('consumer_secret'))
    
    from_token = via
    from_user  = from_token._name
    
    # 自爆
    suicide = False
    suicide_rate = DBYAML.load('suicide_rate')
    if suicide_rate:
        if count >= len(suicide_rate):
            suicide_rate = suicide_rate[-1]
        else:
            suicide_rate = suicide_rate[count]
            
        dice = random.random()
        if dice <= suicide_rate:
            suicide = True
    
    
    chk = libs.cpu.CPUChecker("random_tweet")
    chk.kokokara()
    if suicide:
        lst = [ from_token ]
    else:
        lst = OAuthAccessToken.get_random_access_token(5)
        random.shuffle(lst)
        lst.append(from_token)
    chk.kokomade("OAuthAccessToken.get_random_access_token")
    
    word   = random.choice(words)
    status = format % word
    
    for i, item in enumerate(lst):
        logging.debug('random_tweet: try=%d' % (i+1))
        
        token  = dict(token        = item.oauth_token,
                      token_secret = item.oauth_token_secret)
        api = TwitterAPI(OAuth(consumer, token))
        
        chk.kokokara()        
        api_result = None
        try:
            # api_result = api.verify()
            api_result = api.tweet(status=status)
            
        except urlfetch.DownloadError:
            api_result = None
            logging.warning('tweet failed: timeout')
            
        except urlfetch.InvalidURLError:
            api_result = None
            item.delete()
            logging.warning('tweet failed: invalid access_token %s' % item.oauth_token)
            
        chk.kokomade("api_result = api.tweet(status=status)")
        if not api_result: continue
        
        
        chk.kokokara()
        to_user = api_result.get('user', {}).get('screen_name').encode('utf-8')
        status_id = int(api_result.get('id', 0))
        if status_id:
            YouHaShockHistory( from_user = from_user, to_user   = to_user,
                               word      = word     , status_id = status_id ).put()
            logging.info('%s (posted by %s via %s)' % (status, to_user, from_user))
        chk.kokomade("YouHaShockHistory")
        
        
        chk.kokokara()
        expired = datetime.datetime.now() - datetime.timedelta(hours=2)
        if from_token.is_saved():
            # 既存ユーザー
            if from_token.modified < expired:
                from_token.randint = random.randint(0, 1000)
                from_token.put()
        else:
            # 新規ユーザー
            from_token.randint = random.randint(0, 1000)
            from_token.put()
            if item == from_token:
                # 新規ユーザーが自爆したときAPIの結果からアイコン画像のURLをメモしておく
                profile_image_url = api_result.get('user', {}).get('profile_image_url')
                key_name = 'at_%s' % to_user
                memcache.add(key=key_name, value=profile_image_url)
                
        if item != from_token:
            if item.modified < expired:
                item.randint = random.randint(0, 1000)
                item.put()
        chk.kokomade("TokenUpdate")
        
        return True # break
    return False