Exemplo n.º 1
0
 def receive(self, message):
     bodies = message.bodies(content_type='text/plain')
     for body in bodies:
         to = extract_address(message.to)
         sender = extract_address(message.sender.lower())
         if to[0:5].lower() == 'tweet':
             #q = db.GqlQuery("SELECT * FROM Member WHERE email = :1", sender)
             q = Member.selectBy(email=sender)
             if q.count() == 1:
                 member = q[0]
                 if member.twitter_oauth == 1:
                     access_token = OAuthToken.from_string(
                         member.twitter_oauth_string)
                     twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET,
                                        access_token)
                     status = body[1].decode()
                     if len(status) > 140:
                         status = status[0:140]
                     try:
                         logging.info("About to send tweet: " + status)
                         twitter.PostUpdate(status.encode('utf-8'))
                         logging.info("Successfully tweet: " + status)
                     except:
                         logging.error("Failed to tweet for " +
                                       member.username)
             else:
                 logging.error("User " + sender +
                               " doesn't have Twitter link.")
Exemplo n.º 2
0
 def post(self):
     if 'Referer' in self.request.headers:
         go = self.request.headers['Referer']
     else:
         go = '/'
     member = CheckAuth(self)
     if member:
         if member.twitter_oauth == 1:
             status = self.request.get('status')
             if len(status) > 140:
                 status = status[0:140]
             access_token = OAuthToken.from_string(
                 member.twitter_oauth_string)
             twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)
             try:
                 twitter.PostUpdate(status.encode('utf-8'))
                 memcache.delete('member::' + str(member.num) +
                                 '::twitter::home')
             except:
                 logging.error('Failed to tweet: ' + status)
             self.redirect(go)
         else:
             self.redirect('/twitter/link')
     else:
         self.redirect('/')
Exemplo n.º 3
0
 def get(self):
     twitter = OAuthApi(config.CONSUMER_KEY, config.CONSUMER_SECRET)
     request_token = twitter.getRequestToken()
     authorization_url = twitter.getAuthorizationURL(request_token)
     memcache.delete('request_token')
     memcache.add('request_token', request_token, 3600)
     self.redirect(authorization_url)
Exemplo n.º 4
0
 def get(self, screen_name):
     site = GetSite()
     member = CheckAuth(self)
     if member:
         if member.twitter_oauth == 1:
             template_values = {}
             template_values['site'] = site
             template_values['rnd'] = random.randrange(1, 100)
             template_values['member'] = member
             l10n = GetMessages(self, member, site)
             template_values['l10n'] = l10n
             template_values[
                 'page_title'] = site.title + u' › Twitter › ' + screen_name
             template_values['screen_name'] = screen_name
             access_token = OAuthToken.from_string(
                 member.twitter_oauth_string)
             twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)
             rate_limit = memcache.get(
                 str(member.twitter_id) + '::rate_limit')
             if rate_limit is None:
                 try:
                     rate_limit = twitter.GetRateLimit()
                     memcache.set(
                         str(member.twitter_id) + '::rate_limit',
                         rate_limit, 60)
                 except:
                     logging.info('Failed to get rate limit for @' +
                                  member.twitter_screen_name)
             template_values['rate_limit'] = rate_limit
             cache_tag = 'twitter::' + screen_name + '::home'
             statuses = memcache.get(cache_tag)
             if statuses is None:
                 statuses = twitter.GetUserTimeline(user=screen_name,
                                                    count=50)
                 i = 0
                 for status in statuses:
                     statuses[i].source = statuses[i].source.replace(
                         '<a', '<a class="dark"')
                     statuses[i].datetime = datetime.datetime.fromtimestamp(
                         time.mktime(
                             time.strptime(status.created_at,
                                           '%a %b %d %H:%M:%S +0000 %Y')))
                     statuses[i].text = twitter.ConvertMentions(status.text)
                     #statuses[i].text = twitter.ExpandBitly(status.text)
                     i = i + 1
                 memcache.set(cache_tag, statuses, 120)
             template_values['statuses'] = statuses
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'desktop', 'twitter_user.html')
             output = template.render(path, template_values)
             self.response.out.write(output)
         else:
             self.redirect('/settings')
     else:
         self.redirect('/')
Exemplo n.º 5
0
 def get(self):
     self.session = Session()
     member = CheckAuth(self)
     if member:
         twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET)
         request_token = twitter.getRequestToken()
         authorization_url = twitter.getAuthorizationURL(request_token)
         self.session['request_token'] = request_token
         self.redirect(authorization_url)
     else:
         self.redirect('/signin')
Exemplo n.º 6
0
Arquivo: t.py Projeto: cwyark/v2ex
 def get(self):
     self.session = Session()
     member = CheckAuth(self)
     if member:
         twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET)
         request_token = twitter.getRequestToken()
         authorization_url = twitter.getAuthorizationURL(request_token)
         self.session['request_token'] = request_token
         self.redirect(authorization_url)
     else:
         self.redirect('/signin')
Exemplo n.º 7
0
 def get(self):
     member = CheckAuth(self)
     site = GetSite()
     if member:
         if member.twitter_oauth == 1:
             template_values = {}
             template_values['site'] = site
             template_values['rnd'] = random.randrange(1, 100)
             template_values['member'] = member
             l10n = GetMessages(self, member, site)
             template_values['l10n'] = l10n
             template_values[
                 'page_title'] = site.title + u' › Twitter › Direct Messages › Inbox'
             access_token = OAuthToken.from_string(
                 member.twitter_oauth_string)
             twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)
             rate_limit = memcache.get(
                 str(member.twitter_id) + '::rate_limit')
             if rate_limit is None:
                 try:
                     rate_limit = twitter.GetRateLimit()
                     memcache.set(
                         str(member.twitter_id) + '::rate_limit',
                         rate_limit, 60)
                 except:
                     logging.info('Failed to get rate limit for @' +
                                  member.twitter_screen_name)
             template_values['rate_limit'] = rate_limit
             cache_tag = 'member::' + str(
                 member.num) + '::twitter::dm::inbox'
             messages = memcache.get(cache_tag)
             if messages is None:
                 messages = twitter.GetDirectMessages()
                 i = 0
                 for message in messages:
                     messages[i].datetime = datetime.datetime.fromtimestamp(
                         time.mktime(
                             time.strptime(message.created_at,
                                           '%a %b %d %H:%M:%S +0000 %Y')))
                     messages[i].text = twitter.ConvertMentions(
                         message.text)
                     #statuses[i].text = twitter.ExpandBitly(status.text)
                     i = i + 1
                 memcache.set(cache_tag, messages, 120)
             template_values['messages'] = messages
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'desktop', 'twitter_dm_inbox.html')
             output = template.render(path, template_values)
             self.response.out.write(output)
         else:
             self.redirect('/settings')
     else:
         self.redirect('/')
Exemplo n.º 8
0
 def get(self):
     request_token = memcache.get('request_token')
     twitter = OAuthApi(config.CONSUMER_KEY, config.CONSUMER_SECRET, request_token)
     access_token = twitter.getAccessToken()
     twitter = OAuthApi(config.CONSUMER_KEY, config.CONSUMER_SECRET, access_token)
     user = twitter.GetUserInfo()
     author = Author.all().get()
     author.twitter_oauth = 1
     author.twitter_oauth_key = access_token.key
     author.twitter_oauth_secret = access_token.secret
     author.twitter_oauth_string = access_token.to_string()
     author.twitter_id = int(user.id)
     author.twitter_name = user.name
     author.twitter_screen_name = user.screen_name
     author.twitter_location = user.location
     author.twitter_description = user.description
     author.twitter_profile_image_url = user.profile_image_url
     author.twitter_url = user.url
     author.twitter_statuses_count = user.statuses_count
     author.twitter_followers_count = user.followers_count
     author.twitter_friends_count = user.friends_count
     author.twitter_favourites_count = user.favourites_count
     author.put()
     self.redirect('/writer/settings/')
Exemplo n.º 9
0
 def get(self):
     self.session = Session()
     member = CheckAuth(self)
     host = self.request.headers['Host']
     if host == 'localhost:10000' or host == '127.0.0.1:10000':
         # Local debugging logic
         if member:
             request_token = self.session['request_token']
             twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET,
                                request_token)
             access_token = twitter.getAccessToken()
             twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)
             user = twitter.GetUserInfo()
             memcache.delete('Member_' + str(member.num))
             member = db.GqlQuery("SELECT * FROM Member WHERE num = :1",
                                  member.num)[0]
             member.twitter_oauth = 1
             member.twitter_oauth_key = access_token.key
             member.twitter_oauth_secret = access_token.secret
             member.twitter_oauth_string = access_token.to_string()
             member.twitter_sync = 0
             member.twitter_id = user.id
             member.twitter_name = user.name
             member.twitter_screen_name = user.screen_name
             member.twitter_location = user.location
             member.twitter_description = user.description
             member.twitter_profile_image_url = user.profile_image_url
             member.twitter_url = user.url
             member.twitter_statuses_count = user.statuses_count
             member.twitter_followers_count = user.followers_count
             member.twitter_friends_count = user.friends_count
             member.twitter_favourites_count = user.favourites_count
             member.put()
             memcache.set('Member_' + str(member.num), member, 86400)
             self.redirect('/settings')
         else:
             self.redirect('/signin')
     else:
         # Remote production logic
         if member and 'request_token' in self.session:
             request_token = self.session['request_token']
             twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET,
                                request_token)
             access_token = twitter.getAccessToken()
             twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)
             user = twitter.GetUserInfo()
             memcache.delete('Member_' + str(member.num))
             member = db.GqlQuery("SELECT * FROM Member WHERE num = :1",
                                  member.num)[0]
             member.twitter_oauth = 1
             member.twitter_oauth_key = access_token.key
             member.twitter_oauth_secret = access_token.secret
             member.twitter_oauth_string = access_token.to_string()
             member.twitter_sync = 0
             member.twitter_id = user.id
             member.twitter_name = user.name
             member.twitter_screen_name = user.screen_name
             member.twitter_location = user.location
             member.twitter_description = user.description
             member.twitter_profile_image_url = user.profile_image_url
             member.twitter_url = user.url
             member.twitter_statuses_count = user.statuses_count
             member.twitter_followers_count = user.followers_count
             member.twitter_friends_count = user.friends_count
             member.twitter_favourites_count = user.favourites_count
             member.put()
             memcache.set('Member_' + str(member.num), member, 86400)
             self.redirect('/settings')
         else:
             oauth_token = self.request.get('oauth_token')
             if host == 'v2ex.appspot.com':
                 self.redirect(
                     'http://www.v2ex.com/twitter/oauth?oauth_token=' +
                     oauth_token)
             else:
                 self.redirect(
                     'http://v2ex.appspot.com/twitter/oauth?oauth_token=' +
                     oauth_token)
Exemplo n.º 10
0
Arquivo: t.py Projeto: cwyark/v2ex
 def get(self):
     self.session = Session()
     member = CheckAuth(self)
     host = self.request.headers['Host']
     if host == 'localhost:10000' or host == '127.0.0.1:10000':
         # Local debugging logic
         if member:
             request_token = self.session['request_token']
             twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, request_token)
             access_token = twitter.getAccessToken()
             twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)
             user = twitter.GetUserInfo()
             memcache.delete('Member_' + str(member.num))
             member = db.get(member.key())
             member.twitter_oauth = 1
             member.twitter_oauth_key = access_token.key
             member.twitter_oauth_secret = access_token.secret
             member.twitter_oauth_string = access_token.to_string()
             member.twitter_sync = 0
             member.twitter_id = user.id
             member.twitter_name = user.name
             member.twitter_screen_name = user.screen_name
             member.twitter_location = user.location
             member.twitter_description = user.description
             member.twitter_profile_image_url = user.profile_image_url
             member.twitter_url = user.url
             member.twitter_statuses_count = user.statuses_count
             member.twitter_followers_count = user.followers_count
             member.twitter_friends_count = user.friends_count
             member.twitter_favourites_count = user.favourites_count
             member.put()
             memcache.set('Member_' + str(member.num), member, 86400)
             self.redirect('/settings')
         else:
             self.redirect('/signin')
     else:
         # Remote production logic
         if member and 'request_token' in self.session:
             request_token = self.session['request_token']
             twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, request_token)
             access_token = twitter.getAccessToken()
             twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)
             user = twitter.GetUserInfo()
             memcache.delete('Member_' + str(member.num))
             member = db.get(member.key())
             member.twitter_oauth = 1
             member.twitter_oauth_key = access_token.key
             member.twitter_oauth_secret = access_token.secret
             member.twitter_oauth_string = access_token.to_string()
             member.twitter_sync = 0
             member.twitter_id = user.id
             member.twitter_name = user.name
             member.twitter_screen_name = user.screen_name
             member.twitter_location = user.location
             member.twitter_description = user.description
             member.twitter_profile_image_url = user.profile_image_url
             member.twitter_url = user.url
             member.twitter_statuses_count = user.statuses_count
             member.twitter_followers_count = user.followers_count
             member.twitter_friends_count = user.friends_count
             member.twitter_favourites_count = user.favourites_count
             member.put()
             memcache.set('Member_' + str(member.num), member, 86400)
             self.redirect('/settings')
         else:
             oauth_token = self.request.get('oauth_token')
             if host == 'v2ex.appspot.com':
                 self.redirect('http://www.v2ex.com/twitter/oauth?oauth_token=' + oauth_token)
             else:
                 self.redirect('http://v2ex.appspot.com/twitter/oauth?oauth_token=' + oauth_token)        
Exemplo n.º 11
0
 def post(self, topic_num):
     site = GetSite()
     browser = detect(self.request)
     template_values = {}
     template_values['site'] = site
     template_values['system_version'] = SYSTEM_VERSION
     member = CheckAuth(self)
     template_values['member'] = member
     l10n = GetMessages(self, member, site)
     template_values['l10n'] = l10n
     topic_num_str = str(topic_num)
     if len(topic_num_str) > 8:
         if browser['ios']:
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'mobile',
                                 'topic_not_found.html')
         else:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'desktop', 'topic_not_found.html')
         output = template.render(path, template_values)
         self.response.out.write(output)
         return
     if (member):
         topic = False
         q = db.GqlQuery("SELECT * FROM Topic WHERE num = :1",
                         int(topic_num))
         if (q.count() == 1):
             topic = q[0]
             try:
                 topic.hits = topic.hits + 1
                 topic.put()
             except:
                 topic.hits = topic.hits - 1
         template_values['topic'] = topic
         errors = 0
         # Verification: content
         reply_content_error = 0
         reply_content_error_messages = [
             '', u'请输入回复内容', u'回复内容长度不能超过 2000 个字符'
         ]
         reply_content = self.request.get('content').strip()
         if (len(reply_content) == 0):
             errors = errors + 1
             reply_content_error = 1
         else:
             if (len(reply_content) > 2000):
                 errors = errors + 1
                 reply_content_error = 2
         template_values['reply_content'] = reply_content
         template_values['reply_content_error'] = reply_content_error
         template_values[
             'reply_content_error_message'] = reply_content_error_messages[
                 reply_content_error]
         template_values['errors'] = errors
         if (topic and (errors == 0)):
             reply = Reply(parent=topic)
             q = db.GqlQuery('SELECT * FROM Counter WHERE name = :1',
                             'reply.max')
             if (q.count() == 1):
                 counter = q[0]
                 counter.value = counter.value + 1
             else:
                 counter = Counter()
                 counter.name = 'reply.max'
                 counter.value = 1
             q2 = db.GqlQuery('SELECT * FROM Counter WHERE name = :1',
                              'reply.total')
             if (q2.count() == 1):
                 counter2 = q2[0]
                 counter2.value = counter2.value + 1
             else:
                 counter2 = Counter()
                 counter2.name = 'reply.total'
                 counter2.value = 1
             node = False
             section = False
             if topic:
                 q3 = db.GqlQuery("SELECT * FROM Node WHERE num = :1",
                                  topic.node_num)
                 node = q3[0]
                 #                    q4 = db.GqlQuery("SELECT * FROM Section WHERE num = :1", node.section_num)
                 q4 = Node.all().filter('name =', q3[0].caterogy)
                 section = q4[0]
             reply.num = counter.value
             reply.content = reply_content
             reply.topic = topic
             reply.topic_num = topic.num
             reply.member = member
             reply.member_num = member.num
             reply.created_by = member.username
             topic.replies = topic.replies + 1
             topic.node_name = node.name
             topic.node_title = node.title
             topic.last_reply_by = member.username
             topic.last_touched = datetime.datetime.now()
             ua = self.request.headers['User-Agent']
             if (re.findall('Mozilla\/5.0 \(iPhone', ua)):
                 reply.source = 'iPhone'
             if (re.findall('Mozilla\/5.0 \(iPod', ua)):
                 reply.source = 'iPod'
             if (re.findall('Mozilla\/5.0 \(iPad', ua)):
                 reply.source = 'iPad'
             if (re.findall('Android', ua)):
                 reply.source = 'Android'
             if (re.findall('Mozilla\/5.0 \(PLAYSTATION 3;', ua)):
                 reply.source = 'PS3'
             reply.put()
             topic.put()
             counter.put()
             counter2.put()
             memcache.set('Topic_' + str(topic.num), topic, 86400)
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_desc_compressed')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_asc_compressed')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_filtered_compressed')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_desc_rendered')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_asc_rendered')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_filtered_rendered')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_desc_rendered_mobile')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_asc_rendered_mobile')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_filtered_rendered_mobile')
             memcache.delete('member::' + str(member.num) +
                             '::participated')
             memcache.delete('home_rendered')
             memcache.delete('home_rendered_mobile')
             taskqueue.add(url='/index/topic/' + str(topic.num))
             # Twitter Sync
             if member.twitter_oauth == 1 and member.twitter_sync == 1:
                 access_token = OAuthToken.from_string(
                     member.twitter_oauth_string)
                 twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET,
                                    access_token)
                 link = 'http://' + self.request.headers[
                     'Host'] + '/t/' + str(topic.num) + '#r' + str(
                         reply.num)
                 link_length = len(link)
                 reply_content_length = len(reply.content)
                 available = 140 - link_length - 1
                 if available > reply_content_length:
                     status = reply.content + ' ' + link
                 else:
                     status = reply.content[0:(available -
                                               4)] + '... ' + link
                 self.response.out.write('Status: ' + status)
                 logging.error('Status: ' + status)
                 try:
                     twitter.PostUpdate(status.encode('utf-8'))
                 except:
                     logging.error("Failed to sync to Twitter for Reply #" +
                                   str(reply.num))
             self.redirect('/t/' + str(topic.num) + '#reply' +
                           str(topic.replies))
         else:
             node = False
             section = False
             if topic:
                 q2 = db.GqlQuery("SELECT * FROM Node WHERE num = :1",
                                  topic.node_num)
                 node = q2[0]
                 #                    q3 = db.GqlQuery("SELECT * FROM Section WHERE num = :1", node.section_num)
                 q3 = Node.all().filter('name =', q2[0].caterogy)
                 section = q3[0]
             template_values['node'] = node
             template_values['section'] = section
             if browser['ios']:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'mobile', 'topic.html')
             else:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'desktop', 'topic.html')
             output = template.render(path, template_values)
             self.response.out.write(output)
     else:
         self.redirect('/signin')
Exemplo n.º 12
0
 def post(self, node_name):
     site = GetSite()
     browser = detect(self.request)
     template_values = {}
     template_values['site'] = site
     template_values['system_version'] = SYSTEM_VERSION
     member = CheckAuth(self)
     l10n = GetMessages(self, member, site)
     template_values['l10n'] = l10n
     template_values[
         'page_title'] = site.title + u' › ' + l10n.create_new_topic.decode(
             'utf-8')
     if (member):
         template_values['member'] = member
         q = db.GqlQuery("SELECT * FROM Node WHERE name = :1", node_name)
         node = False
         if (q.count() == 1):
             node = q[0]
         template_values['node'] = node
         section = False
         if node:
             #                q2 = db.GqlQuery("SELECT * FROM Section WHERE num = :1", node.section_num)
             q2 = Node.all().filter('name =', node.category)
             if (q2.count() == 1):
                 section = q2[0]
         template_values['section'] = section
         errors = 0
         # Verification: title
         topic_title_error = 0
         topic_title_error_messages = [
             '', u'请输入主题标题', u'主题标题长度不能超过 120 个字符'
         ]
         topic_title = self.request.get('title').strip()
         if (len(topic_title) == 0):
             errors = errors + 1
             topic_title_error = 1
         else:
             if (len(topic_title) > 120):
                 errors = errors + 1
                 topic_title_error = 2
         template_values['topic_title'] = topic_title
         template_values['topic_title_error'] = topic_title_error
         template_values[
             'topic_title_error_message'] = topic_title_error_messages[
                 topic_title_error]
         # Verification: content
         topic_content_error = 0
         topic_content_error_messages = [
             '', u'请输入主题内容', u'主题内容长度不能超过 9999 个字符'
         ]
         topic_content = self.request.get('content').strip()
         if (len(topic_content) == 0):
             errors = errors + 1
             topic_content_error = 1
         else:
             if (len(topic_content) > 9999):
                 errors = errors + 1
                 topic_content_error = 2
         template_values['topic_content'] = topic_content
         template_values['topic_content_error'] = topic_content_error
         template_values[
             'topic_content_error_message'] = topic_content_error_messages[
                 topic_content_error]
         # Verification: type
         if site.use_topic_types:
             types = site.topic_types.split("\n")
             if len(types) > 0:
                 topic_type = self.request.get('type').strip()
                 try:
                     topic_type = int(topic_type)
                     if topic_type < 0:
                         topic_type = 0
                     if topic_type > len(types):
                         topic_type = 0
                     if topic_type > 0:
                         detail = types[topic_type - 1].split(':')
                         topic_type_label = detail[0]
                         topic_type_color = detail[1]
                 except:
                     topic_type = 0
             else:
                 topic_type = 0
             options = '<option value="0">&nbsp;&nbsp;&nbsp;&nbsp;</option>'
             i = 0
             for a_type in types:
                 i = i + 1
                 detail = a_type.split(':')
                 if topic_type == i:
                     options = options + '<option value="' + str(
                         i
                     ) + '" selected="selected">' + detail[0] + '</option>'
                 else:
                     options = options + '<option value="' + str(
                         i) + '">' + detail[0] + '</option>'
             tt = '<div class="sep5"></div><table cellpadding="5" cellspacing="0" border="0" width="100%"><tr><td width="60" align="right">Topic Type</td><td width="auto" align="left"><select name="type">' + options + '</select></td></tr></table>'
             template_values['tt'] = tt
         else:
             template_values['tt'] = ''
         template_values['errors'] = errors
         if (errors == 0):
             topic = Topic(parent=node)
             q = db.GqlQuery('SELECT * FROM Counter WHERE name = :1',
                             'topic.max')
             if (q.count() == 1):
                 counter = q[0]
                 counter.value = counter.value + 1
             else:
                 counter = Counter()
                 counter.name = 'topic.max'
                 counter.value = 1
             q2 = db.GqlQuery('SELECT * FROM Counter WHERE name = :1',
                              'topic.total')
             if (q2.count() == 1):
                 counter2 = q2[0]
                 counter2.value = counter2.value + 1
             else:
                 counter2 = Counter()
                 counter2.name = 'topic.total'
                 counter2.value = 1
             topic.num = counter.value
             topic.title = topic_title
             topic.content = topic_content
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'portion', 'topic_content.html')
             output = template.render(path, {'topic': topic})
             topic.content_rendered = output.decode('utf-8')
             topic.node = node
             topic.node_num = node.num
             topic.node_name = node.name
             topic.node_title = node.title
             topic.created_by = member.username
             topic.member = member
             topic.member_num = member.num
             topic.last_touched = datetime.datetime.now()
             ua = self.request.headers['User-Agent']
             if (re.findall('Mozilla\/5.0 \(iPhone;', ua)):
                 topic.source = 'iPhone'
             if (re.findall('Mozilla\/5.0 \(iPod;', ua)):
                 topic.source = 'iPod'
             if (re.findall('Mozilla\/5.0 \(iPad;', ua)):
                 topic.source = 'iPad'
             if (re.findall('Android', ua)):
                 topic.source = 'Android'
             if (re.findall('Mozilla\/5.0 \(PLAYSTATION 3;', ua)):
                 topic.source = 'PS3'
             if site.use_topic_types:
                 if topic_type > 0:
                     topic.type = topic_type_label
                     topic.type_color = topic_type_color
             node.topics = node.topics + 1
             node.put()
             topic.put()
             counter.put()
             counter2.put()
             memcache.delete('feed_index')
             memcache.delete('Node_' + str(topic.node_num))
             memcache.delete('Node::' + str(node.name))
             memcache.delete('home_rendered')
             memcache.delete('home_rendered_mobile')
             taskqueue.add(url='/index/topic/' + str(topic.num))
             # Twitter Sync
             if member.twitter_oauth == 1 and member.twitter_sync == 1:
                 access_token = OAuthToken.from_string(
                     member.twitter_oauth_string)
                 twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET,
                                    access_token)
                 status = topic.title + ' #' + topic.node.name + ' http://' + self.request.headers[
                     'Host'] + '/t/' + str(topic.num)
                 try:
                     twitter.PostUpdate(status.encode('utf-8'))
                 except:
                     logging.error("Failed to sync to Twitter for Topic #" +
                                   str(topic.num))
             self.redirect('/t/' + str(topic.num) + '#reply0')
         else:
             if browser['ios']:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'mobile', 'new_topic.html')
             else:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'desktop', 'new_topic.html')
             output = template.render(path, template_values)
             self.response.out.write(output)
     else:
         self.redirect('/signin')
Exemplo n.º 13
0
 def post(self, request):
     message = xmpp.Message(self.request.POST)
     to = extract_address(message.to.lower())
     sender = extract_address(message.sender.lower())
     member = GetMemberByEmail(sender)
     if member:
         if member.twitter_oauth == 1:
             access_token = OAuthToken.from_string(member.twitter_oauth_string)
             twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)
             status = message.body
             result = None
             if len(status) > 140:
                 status = status[0:140]
             try:
                 if message.command is not None:
                     command = message.command.lower()
                     if command == 'mentions' or command == 'm' or command == 'r':
                         logging.info('About to get mentions for @' + member.twitter_screen_name)
                         statuses = twitter.GetReplies()
                         msg = ''
                         i = 0
                         for s in statuses:
                             msg = msg + '@' + s.user.screen_name + ': ' + s.text + "\n\n"
                             i = i + 1
                             if i > 5:
                                 break
                         xmpp.send_message(message.sender, msg)
                     if command == 'search' or command == 'q' or command == 's':
                         q = re.findall('/' + command + ' (.+)', message.body)[0]
                         url = 'http://twitter.com/search.json?q=' + urllib.quote(q)
                         response = urlfetch.fetch(url)
                         logging.info(response.status_code)
                         data = json.loads(response.content)
                         msg = ''
                         i = 0
                         for s in data['results']:
                             msg = msg + '@' + s['from_user'] + ': ' + s['text'] + "\n\n"
                             i = i + 1
                             if i > 5:
                                 break
                         xmpp.send_message(message.sender, msg)
                 else:
                     if status.lower() == 'ls':
                         logging.info('About to get home timeline for @' + member.twitter_screen_name)
                         statuses = twitter.GetHomeTimeline(count = 5)
                         msg = ''
                         i = 0
                         for s in statuses:
                             msg = msg + '@' + s.user.screen_name + ': ' + s.text + "\n\n"
                         xmpp.send_message(message.sender, msg)
                     else:
                         logging.info("About to send tweet: " + status)
                         result = twitter.PostUpdate(status.encode('utf-8'))
                         logging.info("Successfully tweet: " + status)
             except:
                 logging.error("Failed to tweet for " + member.username)
             if result is not None:
                 msg = 'OK: http://twitter.com/' + result.user.screen_name + '/status/' + str(result.id)
                 xmpp.send_message(message.sender, msg)
         else:
             logging.error("User " + sender + " doesn't have Twitter link.")
     else:
         logging.error("Cannot find a corresponding member for " + message.sender)