Esempio n. 1
0
 def get(self):
     "Displays the home page, which lists the latest messages"
     # lets have some basic cachine just in case
     output = memcache.get("index")
     if output is None:
         # we're only showing messages from within the last five days
         # this is for demonstration purposes only and stops 
         # the demo getting swamped with messages
         yesterday = datetime.today() - timedelta(5)
         
         # get all messages posted in the last day and order them
         # by the date posted
         messages = Message.all()
         messages.order('-date')
         messages.filter('date >', yesterday)
         # prepare the context for the template
         context = {
             'messages': messages,
             'debug': settings.DEBUG,
         }
         # calculate the template path
         path = os.path.join(os.path.dirname(__file__), 'templates',
             'index.html')
         # render the template with the provided context
         output = template.render(path, context)
         memcache.add("index", output, settings.CACHE_TIME)
     self.response.out.write(output)
Esempio n. 2
0
    def get(self):
        """
            Fetch All Messages using memcache
        """

        messages = memcache.get("all_messages")

        if not messages:
            messages = Message.all().order("-date").fetch(20)
            memcache.add("all_messages", messages, 30)
            cache_hit = False
        else:
            cache_hit = True

        """
            Make Messages available to the template
        """
        context = {
            'messages': messages,
            'cache_hit': cache_hit
        }

        """
            Render Template
        """
        path = os.path.join(os.path.dirname(__file__), 'base.html')
        self.response.out.write(template.render(path, context))
Esempio n. 3
0
    def get(self):
        "Displays the home page, which lists the latest messages"
        # lets have some basic cachine just in case
        output = memcache.get("index")
        if output is None:
            # we're only showing messages from within the last five days
            # this is for demonstration purposes only and stops
            # the demo getting swamped with messages
            yesterday = datetime.today() - timedelta(5)

            # get all messages posted in the last day and order them
            # by the date posted
            messages = Message.all()
            messages.order('-date')
            messages.filter('date >', yesterday)
            # prepare the context for the template
            context = {
                'messages': messages,
                'debug': settings.DEBUG,
            }
            # calculate the template path
            path = os.path.join(os.path.dirname(__file__), 'templates',
                                'index.html')
            # render the template with the provided context
            output = template.render(path, context)
            memcache.add("index", output, settings.CACHE_TIME)
        self.response.out.write(output)
Esempio n. 4
0
def route_message(request):
    """
    主页的处理函数, 返回主页的响应
    """
    log('本次请求的 method', request.method)
    if request.method == 'POST':
        data = request.form()
    elif request.method == 'GET':
        data = request.query
    else:
        raise ValueError('Unknown method')

    if 'message' in data:
        log('post', data)
        # 应该在这里保存 message_list
        m = Message.new(data)
        m.save()
        # message_list.append(data)

    header = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n'
    body = template('message.html')
    ms = '<br>'.join([str(m) for m in Message.all()])
    body = body.replace('{{messages}}', ms)
    r = header + '\r\n' + body
    return r.encode()
Esempio n. 5
0
def messages():
    messages = list(Message.all().filter('seen', False))
    for m in messages:
        m.seen = True
        m.save()
    return flask.Response('\n\n'.join([m.content for m in messages]),
        mimetype='text/plain')
Esempio n. 6
0
    def get(self):
        
        # Get the id that indicate where is the start point of new messages:
        current_id = int(self.request.get('id'))
        messages = Message.all().order('-postID').filter("postID > ", current_id)
        msg_set  = messages.fetch(10)
 
        self.response.headers['Content-Type'] = 'text/xml'
        self.response.headers['Cache-Control'] = 'no-cache'
        
        # Start writing the xml content:
        self.response.out.write('<?xml version="1.0"?>\n')
        self.response.out.write('    <response>\n')
        self.response.out.write('        <id>%d</id>\n' % Message.max_id() )
        for msg in msg_set:
            if not msg.isRemoved:
                self.response.out.write('        <message>\n')
                self.response.out.write('            <author>%s</author>\n' % msg.author.nickname() )
                self.response.out.write('            <postID>%d</postID>\n' % msg.postID )
                self.response.out.write('            <content>%s</content>\n' % msg.content )
                self.response.out.write('            <rcount>%d</rcount>\n' % msg.rCount )
                self.response.out.write('            <time>%s</time>\n' % msg.postDate )
                self.response.out.write('        </message>\n')            

        self.response.out.write('    </response>\n')
Esempio n. 7
0
def fetch_all(event, context):
    content = Message.all().serialize()
    response = {
        'isBase64Encoded': False,
        'statusCode': 200,
        'body': content,
    }
    print(json.dumps(response))
    return response
Esempio n. 8
0
  def get(self, channelid):
    channel = self._getentity(Channel, channelid)
    if channel is None: return

    template_values = {
      'channel': channel,
      'messages': Message.all().filter('channel =', channel),
    }
    path = os.path.join(os.path.dirname(__file__), 'messagelist.html')
    self.response.out.write(template.render(path, template_values))
Esempio n. 9
0
def poll():
    messages = []
    topic_key = request.args.get('topic_key')
    if topic_key:
        topic = Topic.get(topic_key)
        if topic:
            offset = int(request.args.get('offset'))
            l = Message.all().filter('topic', topic).order('created_at').fetch(limit=100, offset=offset)
            messages = [{'content': m.content, 'email': m.author.email, 'created_at': pretty_date(m.created_at), 'topic_key': str(m.topic.key())} for m in l]
    return jsonify(messages=messages)
Esempio n. 10
0
	def get(self):
		messages = Message.all().order('-datetime')

		results = []
		for message in messages:
			results.append(message.to_dict())

		
		response = {"list" : results, "total" : len(results)}
		json = simplejson.dumps(response)
		self.response.out.write(json)
Esempio n. 11
0
def discussion(topic_key):
    messages = None
    if topic_key:
        topic = Topic.get(topic_key)
        if not topic:
            flash('No topic found', 'error')
            return redirect(url_for('index'))
        child_topics = []
        for child_topic_key in topic.child_topics:
            child_topics.append(Topic.get(child_topic_key))
        messages = Message.all().filter('topic', topic).order('-created_at').fetch(limit=50)
    return render_template('discussion.html', messages=messages, topic=topic, child_topics=child_topics)
Esempio n. 12
0
    def post(self):
        print "this is post in LoginHandler"
        data = json.loads(self.request.body)
        print data

        print type(data)
        
        fullname = data.get('fullname')       
        password = data.get('password')
        print fullname  
        print password
        try:
            u = self.auth.get_user_by_password(fullname, password, remember=True,
                                           save_session=True)
            all_users = User.query().fetch()
            logging.info(all_users) 
            user_list = []
            print u.get('name')
            curren_user = u.get('name')
            for user in all_users:
                user_list.append(user.name)
                #print user.name
            
            print user_list
            
            print type(user_list)
           
            message_list = []
            message = Message.all()
            current_message = message.filter("receiver =", "%s"%curren_user )
            print current_message

            for msg in message:
                message_list.append(msg.message) 
            print message_list    
            userlist = user_list
            messagelist = message_list
            
            result = {'userlist': userlist, 'messagelist': messagelist, 'curren_user':curren_user }
            self.response.headers['content-type'] = 'application/json'
            
            self.response.write(json.dumps(result))


        except (InvalidAuthIdError, InvalidPasswordError) as e:
            logging.info(
                'Login failed for user %s because of %s', fullname, type(e))
            # self._serve_page(True)
            stat = "invalid user"
            result = {'stat': stat}
            self.response.headers['content-type'] = 'application/json'
            self.response.write(json.dumps(result))
Esempio n. 13
0
def list_messages(event, context):
    conversation_id = event.get('pathParameters', {}).get('conversation_id')
    messages = Message.all(conversation_id)

    response = {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Origin': '*'
        },
        'body': json.dumps(messages)
    }

    return response
Esempio n. 14
0
    def get(self):    

        users = User.query().fetch()
        user_list = []
        for user in users:
            user_list.append(user) 

        message = Message.all() 
        message_list = []
        for msg in message:
            message_list.append(msg)               
    
        self.render_template('user_list.html', {'user_list': user_list, 'message_list': message_list})
Esempio n. 15
0
 def distribute_message(self, message):
     message_json = json.dumps({
         'author': message.author.display_name(),
         'message': message.text       
     })
     related_messages = Message.all().filter('conver =', message.conver).fetch(1000)
     participating_permausers = [message.author for message in related_messages]
     participating_permausers.extend(message.conver.get_watchers())
     pp_ids = [pp.user_id() for pp in participating_permausers]
     pp_ids = list(set(pp_ids))
     for pp_id in pp_ids:
         # ugly, but for now everyone can just get the messages
         channel.send_message(pp_id + str(message.conver.key().id_or_name()), message_json)
Esempio n. 16
0
	def get(self):
		# We fetch all the accounts
		authors = Account.all()
		
		# We fetch the last ten messages
		message_query = Message.all().order('-date')
		messages = message_query.fetch(10)
		
		# Check if user is logged in
		unknown_user = False
		if users.get_current_user():
			# Generate the logout url
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
			anon = False

			# We check that the user is registered
			accounts = Account.all()
			accounts.filter('user = '******'Login'
			anon = True
	  
		# Check if user is admin
		is_admin = users.is_current_user_admin()
	    
		# Choose a random title
   		titles = ('<a>PINT</a>Spot', '<a>PINT</a>ed', '<a>PINT</a>Me', '<a>PINT</a>Soft', '<a>PINT</a>Hard', '<a>PINT</a>SM', '<a>PINT</a>ware', '<a>PINT</a>BDSM', '<a>PINT</a>BSD', '<a>PINT</a>LSD', '<a>PINT</a>ou (or ubuntu)', '<a>PINT</a>ubuntu', 'i<a>PINT</a>', 'you<a>PINT</a>', 'Google <a>PINT</a>', '<a>PINT</a>Please', '<a>PINT</a>Sorry', '<a>PINT</a>Welcomed', '<a>PINT</a>Again', '<a>PINT</a>guin', 'JustOne<a>PINT</a>', 'JustAnother<a>PINT</a>', 'OneMore<a>PINT</a>', 'Bier&<a>PINT</a>', '<a>PINT</a>OfVodka', '<a>PINT</a>ade', '<a>PINT</a>aid', '<a>PINT</a>ADD', '<a>PINT</a>INC', '<a>PINT</a>agramme', '<a>PINT</a>-A-Gramme', '<a>PINT</a>-A-Kilo', 'Pound-A-<a>PINT</a>', 'Fish<a>PINT</a>', '<a>PINT</a>Sized', 'Mystic<a>PINT</a>', 'Super<a>PINT</a>', 'Hyper<a>PINT</a>', 'Quantic<a>PINT</a>', 'QuantumOf<a>PINT</a>', 'Electro<a>PINT</a>', 'Royal<a>PINT</a>', 'Republican<a>PINT</a>', 'YesWeCan...<a>PINT</a>', 'WhatTheFucking...<a>PINT</a>', 'IVotedFor<a>PINT</a>', 'WhatSThe<a>PINT</a>', '<a>PINT</a>Aday', '<a>PINT</a>IsMine', 'my<a>PINT</a>!', '<a>PINT</a>Book', '<a>PINT</a>Book-Air', 'less Air, more <a>PINT</a>', 'Apple<a>PINT</a>', 'Web<a>PINT</a>', 'Command+<a>PINT</a>', 'Ctrl+Meta+Alt+<a>PINT</a>', ':<a>PINT</a>', '3Click<a>PINT</a>', 'Black<a>PINT</a>', '<a>PINT</a>sh', '<a>PINT</a> (<a>PINT</a> Is Not Twilight)', 'tinP', 'tniP', 'Tonight<a>PINT</a>', 'Coffee<a>PINT</a>', 'Breakfast<a>PINT</a>', 'Bacon<a>PINT</a>', '<a>PINT</a>Pause', '<a>PINT</a>-nic', '<a>PINT</a>Address', '<a>PINT</a>Phone', 'Multi<a>PINT</a>', 'Simple<a>PINT</a>...', 'FourFingers<a>PINT</a>', 'Start<a>PINT</a>', 'Stop<a>PINT</a>', '<a>PINT</a>', '<a>PINT</a>EGER', 'FloatOr<a>PINT</a>', '<a>PINT</a>Pointer', 'Master<a>PINT</a>er', 'License<a>PINT</a>er', 'GNU<a>PINT</a>', '<a>PINT</a>ix', '<a>PINT</a>ux', '<a>PINT</a>ium', '<a>PINT</a>OS', 'ThanksForThe<a>PINT</a>', 'LordOfThe<a>PINT</a>', 'Piss<a>PINT</a>', '<a>PINT</a>8', '666 Number Of The <a>PINT</a>', 'Bug<a>PINT</a>', 'BlueScreenOf<a>PINT</a>', '<a>PINT</a>Panic', '<a>PINT</a>OSleep', '<a>PINT</a>craft', 'War<a>PINT</a>', '<a>PINT</a>OfDead', '<a>PINT</a>sOfTheCaribeans', 'TheLast<a>PINT</a>', '<a>PINT</a>:Revolution', '<a>PINT</a>:Resurrection', 'Evil<a>PINT</a>', 'TheIncredible<a>PINT</a> ', 'X<a>PINT</a> ', 'Y<a>PINT</a>', 'Why<a>PINT</a>', 'Inexhaustible<a>PINT</a>', 'SauronS<a>PINT</a>', 'Sleepy<a>PINT</a>', 'NeverSleep<a>PINT</a>', '<a>PINT</a>Wars', 'P1N7')
		random_title = random.choice(titles)
		
		# These values are to be sent to the template
		template_values = {
			'random_title': random_title,
			'unknown_user': unknown_user,
			'messages': messages,
			'authors': authors,
			'url': url,
			'url_linktext': url_linktext,
			'anon': anon,
			'is_admin': is_admin
		}
	
		# We get the template path then show it
		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, template_values))
Esempio n. 17
0
 def get(self):
     permauser = PermaUser.get_current_permauser()
     conver_url = utils.unescape(self.request.get('url'))
     conver = Conver.get_for_url(conver_url)
     messages = Message.all().filter('conver =', conver).order('created').fetch(1000)
     self.response.out.write(template.render(
         os.path.join(os.path.dirname(__file__),
         'templates/conver.html'), 
         {
             'token': channel.create_channel(permauser.user_id() + str(conver.key().id_or_name())),
             'conver_url': conver_url,
             'messages': [ {'author': message.author.display_name(), 'text': message.text} for message in messages],
             'loginorout_text': 'Log out',
             'loginorout_url': users.create_logout_url(self.request.uri)
         }
     ))
Esempio n. 18
0
    def testPostMessage(self):
        status, result = views.postMessage(self.n2, simulateUrl(self.n1), '2==>1')
        self.assertEqual(200, status)
        ms = Message.all().order('-timestamp')
        # Race condition: assume nobody else is posting messages!
        self.assertEqual('2==>1', ms[0].text)
        self.assertEqual(self.n2, ms[0].sender.name)
        self.assertEqual(self.n1, ms[0].recipient.name)
        ms[0].delete()

        # Message too long
        status, result = views.postMessage(self.n2, self.n1,
                                           '?' * (LIMITS['TEXT']+1))
        self.assertEqual(400, status)

        # User doesn't exist
        status, result = views.postMessage(self.n1, uuid.uuid4().hex, '??')
        self.assertEqual(404, status)
Esempio n. 19
0
 def get(self):
     permauser = PermaUser.get_current_permauser()
     other_conver_urls = [str(conver.url) for conver in Conver.all().fetch(1000)]
     user_conver_urls  = []
     message_urls = [str(message.conver.url) for message in Message.all().filter('author =', permauser).fetch(1000)]
     message_urls = list(set(message_urls)) # we only want to go through each url once
     for message_url in message_urls:
         other_conver_urls.remove(message_url)
         user_conver_urls.append( message_url)
     self.response.out.write(template.render(
         os.path.join(os.path.dirname(__file__),
         'templates/home.html'), 
         {
             'other_conver_urls': other_conver_urls,
             'user_conver_urls': user_conver_urls,
             'loginorout_text': 'Log out',
             'loginorout_url': users.create_logout_url(self.request.uri)
         }
     ))
Esempio n. 20
0
 def get(self, server, channel):
     key = db.Key.from_path(Channel.kind(), '%s/%s' % (unquote(channel), server))
     channel = Channel.get(key)
     date = self.request.GET.get('date')
     if date:
         start_date = datetime.strptime(date, '%Y-%m-%d').date()
     else:
         start_date = datetime.utcnow().date()
     end_date = start_date + timedelta(days=1)
     messages = Message.all().filter('channel =', channel) \
                 .filter('timestamp >= ', start_date) \
                 .filter('timestamp < ', end_date) \
                 .order('timestamp')
     # date based pagination
     next_day = start_date + timedelta(days=1)
     if next_day > datetime.utcnow().date():
         next_day = None
     previous_day = end_date - timedelta(days=2)
     self.response.out.write(render('templates/channel.html', locals()))
     
Esempio n. 21
0
def get_messages():
    if os.environ['FLASK_ENV'] != 'production':
        message = Message()
        messages = map(
            lambda t: {
                'id':
                t[0],
                'date':
                int(
                    datetime.strptime(t[1], '%Y-%m-%d %H:%M:%S').timestamp() *
                    1000),
                'user':
                t[2],
                'content':
                t[3]
            }, message.all())
        return json.dumps(list(messages))
    else:
        lambda_res = aws_client.invoke(
            FunctionName=
            "arn:aws:lambda:us-east-1:272559496018:function:getMessages")

        payload = json.loads(lambda_res["Payload"].read().decode('utf-8'))
        parsed_data = map(
            lambda t: {
                'id':
                t['id'],
                'date':
                int(
                    datetime.strptime(
                        t['date'],
                        '%a %b %d %Y %H:%M:%S GMT+0000 (Coordinated Universal Time)'
                    ).timestamp() * 1000),
                'user':
                t['user'],
                'content':
                t['content']
            }, payload['body']['messages'])

        return json.dumps(list(parsed_data))
Esempio n. 22
0
  def get(self):
    thread_id = self.request.get('thread')
    thread = gql_limit1(Thread, thread_id = thread_id)
    messages = Message.all().filter('thread_id = ', thread_id)

    formatted_messages = []
    for message in messages:
      if message.content_type == 'text/plain':
        message.body = strip_tags(message.body).strip().\
                                                replace(' ', '&nbsp;').\
                                                replace('\n\n', '</p><p>').\
                                                replace('\n', '<br>')
        message.body = '<p>' + message.body + '</p>'
      formatted_messages.append(message)
    
    if len(formatted_messages) == 0:
      render(self, 'info.html', error_message = "No messages in this thread.")
      return

    user = users.get_current_user()
    already_seen = None
    if user:
      # If user is logged in, mark these messages as viewed.
      max_viewed = max(msg.date for msg in formatted_messages)
      userthread = gql_limit1(UserThread, thread_id = thread_id, user = user)
      if not userthread:
        userthread = UserThread(user = user, thread_id = thread_id,
                                last_viewed = max_viewed)
      else:
        already_seen = userthread.last_viewed
        for message in formatted_messages:
          if message.date <= already_seen:
            message.read = True
      userthread.last_viewed = max_viewed
      userthread.put()


    render(self, 'thread.html', thread=thread, already_seen=already_seen,
           messages=formatted_messages)
Esempio n. 23
0
 def post(self):
     print "this is post in usermessageHandler"
     data = json.loads(self.request.body)
     print data
     print type(data)
     reciver = data.get('reciver')
     message= data.get('message')
     
     print reciver
     print Message
     user_message = Message(receiver = reciver,message= message)
     user_message.put()
     message_list = []
     message = Message.all() 
     for msg in message:
         message_list.append(msg.message)
         
         print msg.message
     print message_list 
     self.response.headers['content-type'] = 'text/plain'
     self.response.write(json.dumps(message_list))
     print reciver
     
     print Message
Esempio n. 24
0
 def get(self):
     tar_id = int(self.request.get('id'))
     targets = Message.all().filter("postID =", tar_id)
     for msg in targets:
         msg.release()
Esempio n. 25
0
 def get(self):
     path = os.path.join(os.path.dirname(__file__), "templates/index.html")
     messages = Message.all()
     self.response.out.write(template.render(path, {"messages": messages}))
Esempio n. 26
0
def delete_all_messages():
  while Message.all().fetch(CHUNK):
    db.delete(Message.all().fetch(CHUNK))
Esempio n. 27
0
sys.path.append("/home/louis/Data/Apps/google_appengine")
sys.path.append("/home/louis/Data/Apps/google_appengine/lib/yaml/lib")

from google.appengine.ext.remote_api import remote_api_stub
from google.appengine.ext import db

def auth_func():
  return raw_input('Username:'******'Password:'******'log4gae'
host = '%s.appspot.com' % app_id
row_count = 250

remote_api_stub.ConfigureRemoteDatastore(app_id, '/remote_api', auth_func, host)

from models import Message
q = Message.all()

while True:
  print 'Deleting %i rows...' % row_count
  e = q.fetch(row_count)
  try:
    db.delete(e)
    print "Done"
  except:
    print "Timed out, retrying"


#code.interact('App Engine interactive console for %s' % (app_id,), None, locals())
Esempio n. 28
0
 def get(self):
     template_values = engine.globals
     template_values['messages'] = Message.all()
     template = engine.jinja_environment.get_template('messages/inbox.html')
     self.response.out.write(template.render(template_values))
Esempio n. 29
0
def delete_all_messages():
    while Message.all().fetch(CHUNK):
        db.delete(Message.all().fetch(CHUNK))
Esempio n. 30
0
 def get(self):
     messages = Message.all().order('-inserted')
     vals = {
         'messages' : messages,
     }
     self.template( 'message-list.html', vals, 'admin' );