Example #1
0
 def get_profile_image(self, name):
     
     key_name = 'at_%s' % name
     profile_image_url = memcache.get(key=key_name)
     if profile_image_url:
         return profile_image_url
     
     
     consumer  = DBYAML.load('oauth')
     consumer = dict(consumer_key    = consumer.get('consumer_key'   ),
                     consumer_secret = consumer.get('consumer_secret'))
     
     adminuser = DBYAML.load('adminuser')
     adminuser = dict(token=adminuser.get('oauth_token'),
                      token_secret=adminuser.get('oauth_token_secret'))
     
     oauth = OAuth(consumer, adminuser)
     api = TwitterAPI(oauth)
     
     try:
         res = api.show(screen_name=name)
     except urlfetch.DownloadError:
         res = None
     
     if res:
         return res.get('profile_image_url')
Example #2
0
 def default_page(self, errmsg=None):
     info = DBYAML.load('info')
     template_value = dict(info=info, errmsg=errmsg)
     
     description = None
     lst = DBYAML.load('description')
     if lst: description = random.choice(lst)
     if description: template_value['description'] = description
     
     html = template.render('tmpl/index.html', template_value)
     self.response.out.write(html)
Example #3
0
    def get(self, action):

        action = action.split('/')
        action, args = action[0], action[1:]
        
        if action == 'edit':
            filelist = DBYAML.catalog()
            html = template.render('tmpl/edit.html', { 'filelist': filelist })
            self.response.out.write(html)
            
        elif action == 'load' and args:
            self.response.out.write(DBYAML.loadtext(name=args[0]))
Example #4
0
 def post(self, action):
     if action == 'edit':
         params = dict(self.request.POST)
         cmd = params.get('submit')
         if cmd == 'SUBMIT':
             name = params.get('name')
             text = params.get('yaml-text')
             logging.info("%s:%s" % (name, text))
             DBYAML.save(name, text)
             
         elif cmd == 'DELETE':
             DBYAML.delete(params.get('name'))
             
     self.redirect('/admin/edit/')
Example #5
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
Example #6
0
    def get_ranking(self):
        """ランキングを返す"""
        
        blocklist = DBYAML.load('blocklist')
        
        def write_user_ranking(type, limit):
            key_name = 'ranking_%s' % type
            lst = memcache.get(key_name)
            if not isinstance(lst, list):
                lst = []
                if type == 'call':
                    query = UserStatus.all().order('-call_count')
                else:
                    query = UserStatus.all().order('-callee_count')
                    
                for ent in query:
                    name = ent.key().name()[3:]
                    if name in blocklist: continue

                    profile_image_url = ent.profile_image_url
                    if type == 'call':
                        count = ent.call_count
                    else:
                        count = ent.callee_count
                    lst.append( (name, profile_image_url,count) )
                    limit -= 1
                    if limit < 0: break
                memcache.set(key=key_name, value=lst, time=120)
                
            for l in lst:
                self.response.out.write("['%s','%s',%d]," % (l[0], l[1], l[2]))
                
        
        try: limit = int(self.request.get('limit', 5))
        except ValueError: limit = 5
        
        self.response.out.write('{')
        self.response.out.write('call:[')
        write_user_ranking('call', limit)
        self.response.out.write('],')
        
        self.response.out.write('callee:[')
        write_user_ranking('callee', limit)
        self.response.out.write('],')
        
        self.response.out.write('}')
Example #7
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
Example #8
0
 def get(self, action):
     
     cause_error = None
     if action == 'verify':
         conf = DBYAML.load('oauth')
         if not conf: return
         
         now = datetime.datetime.now() + datetime.timedelta(hours=+9)
         logging.info('%s [%s]' % (action, now))
         
         handler = libs.auth.OAuthHandler(handler=self, conf=conf)
         url = handler.login()
         # redirect (not reached)
         
     elif action == 'callback':
         conf = DBYAML.load('oauth')
         if not conf: return
         
         now = datetime.datetime.now() + datetime.timedelta(hours=+9)
         logging.info('%s [%s]' % (action, now))
         
         handler = libs.auth.OAuthHandler(handler=self, conf=conf)
         users_token = handler.callback()
         if users_token:
             
             is_block = False
             blocklist = DBYAML.load('blocklist')
             if blocklist:
                 if users_token._name in blocklist:
                     is_block = True
                     
             if not is_block:
                 # random tweet
                 count  = self.session_counter()
                 result = random_tweet(via=users_token, count=count)
                 
                 if result:
                     # update graph
                     q = taskqueue.Queue('fastest')
                     t = taskqueue.Task(url='/task/graph')
                     q.add(t)
                 else:
                     cause_error = True
                     logging.error('random tweet error!!')
                 
             else:
                 cause_error = True
                 logging.warning('blocking %s' % users_token._name)
                 
         else:
             cause_error = True
             logging.error('callback error!!')
             
         url = '/'
         if cause_error: url = '/error'
         self.redirect(url)
         
     else:
         errmsg = None
         if action == 'error':
             errmsg = 'エラーが発生しました。しばらく待ってからもう一度試してみてください。'
         self.default_page(errmsg=errmsg)