bin zhang avatar bin zhang committed a33bdf8

init gaechat

Comments (0)

Files changed (5)

+syntax: glob
+*.pyc
+.pydevproject
+.project
+.settings
+.idea
+juzike.db
+houtai/juzike/media/picture/**
+application: iamsk-info
+version: 4
+runtime: python
+api_version: 1
+
+handlers:
+- url: /.*
+  script: chat.py
+# -*- coding: utf-8 -*-
+#!/usr/bin/env python
+import datetime
+import os
+import random
+import re
+
+from django.utils import simplejson
+from google.appengine.api import channel
+from google.appengine.api import users
+from google.appengine.ext import db
+from google.appengine.ext import webapp
+from google.appengine.ext.webapp import template
+from google.appengine.ext.webapp.util import run_wsgi_app
+
+cities = ['beijing', 'xian', 'zhuhai']
+
+class Room(db.Model):
+    name = db.StringProperty()
+    # 加入此聊天室的用户列表
+    users = db.ListProperty(users.User)
+    message = db.StringProperty()
+    curtime = db.DateTimeProperty(auto_now=True)
+
+class RoomUpdater():
+  room = None
+  def __init__(self, room):
+    self.room = room
+  def get_room_message(self):
+    user = users.get_current_user()
+    curtime = self.room.curtime.strftime('%Y-%m-%d %H:%M:%S')
+    roomUpdate = {
+      'name': self.room.name,
+      'user': user.nickname(),
+      'message': self.room.message,
+      'curtime': curtime,
+    }
+    return simplejson.dumps(roomUpdate)
+  def send_update(self):
+    message = self.get_room_message()
+    for user in self.room.users:
+        channel.send_message(user.user_id() + self.room.name, message)
+  def say_words(self, message, user):
+    if message and user:
+      self.room.message = message
+      self.room.put()
+      self.send_update()
+    return
+
+class RoomFromRequest():
+  """根据请求(name)获取Room"""
+  room = None
+  def __init__(self, request):
+    user = users.get_current_user()
+    name = request.get('name')
+    if user and name:
+      self.room = Room.get_by_key_name(name)
+  def get_room(self):
+    return self.room
+
+class SayWords(webapp.RequestHandler):
+  """说话"""
+  def post(self):
+    room = RoomFromRequest(self.request).get_room()
+    user = users.get_current_user()
+    if room and user:
+      message = self.request.get('message')
+      RoomUpdater(room).say_words(message, user)
+
+class OpenedPage(webapp.RequestHandler):
+  def post(self):
+    room = RoomFromRequest(self.request).get_room()
+    RoomUpdater(room).send_update()
+
+class MainPage(webapp.RequestHandler):
+    """主页面"""
+    def get(self):
+        template_values = {'cities': cities}
+        path = os.path.join(os.path.dirname(__file__), 'index.html')
+        self.response.out.write(template.render(path, template_values))
+
+class RoomPage(webapp.RequestHandler):
+    """聊天室页面"""
+    def get(self):
+        user = users.get_current_user()
+        name = self.request.get('name')
+        if user:
+            if name and name in cities:
+                room = Room.get_by_key_name(name)
+                if room:
+                    if user not in room.users:
+                        room.users.append(user)
+                    room.message = '%s joined in.' % user.nickname()
+                    room.put()
+                else:
+                    room = Room(key_name = name,
+                                name = name,
+                                message = 'welcome to chatting, %s' % user.nickname())
+                    room.users.append(user)
+                    room.put()
+                room_link = '/room/?name=' + name
+                token = channel.create_channel(user.user_id() + name)
+                template_values = {'token': token,
+                                   'me': user.user_id(),
+                                   'name': name,
+                                   'room_link': room_link,
+                                   'initial_message': RoomUpdater(room).get_room_message()
+                                  }
+                path = os.path.join(os.path.dirname(__file__), 'room.html')
+                self.response.out.write(template.render(path, template_values))
+            else:
+                self.redirect('/')
+        else:
+          self.redirect(users.create_login_url(self.request.uri))
+
+application = webapp.WSGIApplication([
+    ('/', MainPage),
+    ('/room/', RoomPage),
+    ('/opened', OpenedPage),
+    ('/saywords', SayWords)], debug=True)
+
+def main():
+  run_wsgi_app(application)
+
+if __name__ == "__main__":
+  main()
+<html>
+  <head>
+      <title>Simple ChatRoom based on Google Channel</title>
+  </head>
+  <body>
+    <div id='display-area'>
+      <h2>Simple ChatRoom based on Google Channel</h2>
+      <div id="city-list">
+        <table id="city-table">
+            <tr><td><a href="/room/?name=beijing">北京</a></td></tr>
+            <tr><td><a href="/room/?name=xian">西安</a></td></tr>
+            <tr><td><a href="/room/?name=zhuhai">珠海</a></td></tr>
+        </table>
+      </div>
+    </div>
+  </body>
+</html>
+<html>
+  <head>
+      <title>Simple ChatRoom based on Google Channel</title>
+      <script src='/_ah/channel/jsapi'></script>
+  </head>
+  <body>
+    <script type='text/javascript'>
+      var state = {
+        name: '{{ name }}',
+        me: '{{ me }}'
+      };
+      sendMessage = function(path, opt_param) {
+        path += '?name=' + state.name;
+        if (opt_param) {
+          path += '&' + opt_param;
+        }
+        var xhr = new XMLHttpRequest();
+        xhr.open('POST', path, true);
+        xhr.send();
+      };
+      sayWords = function(message) {
+        sendMessage('/saywords', 'message=' + message);
+      }
+      onOpened = function() {
+        sendMessage('/opened');
+      };
+      onMessage = function(m) {
+        newState = JSON.parse(m.data);
+        state.user = newState.user || state.user;
+        state.curtime = newState.curtime || state.curtime;
+        state.message = newState.message || state.message;
+        var message = document.getElementById('message-table');
+        var temp_tr = document.createElement("tr");
+        var temp_td = document.createElement("tr");
+        var temp_node = document.createTextNode(state.user + ' said "' + state.message + '" at ' + state.curtime);
+        temp_td.appendChild(temp_node);
+        temp_tr.appendChild(temp_td);
+        message.appendChild(temp_tr);
+      }
+      openChannel = function() {
+        var token = '{{ token }}';
+        var channel = new goog.appengine.Channel(token);
+        var handler = {
+          'onopen': onOpened,
+          'onmessage': onMessage,
+          'onerror': function() {},
+          'onclose': function() {}
+        };
+        var socket = channel.open(handler);
+        socket.onopen = onOpened;
+        socket.onmessage = onMessage;
+      }
+      initialize = function() {
+        openChannel();
+        var say = document.getElementById('say');
+        say.onclick = function(){
+            var words = document.getElementById('words').value;
+            sayWords(words);
+        };
+        onMessage({data: '{{ initial_message }}'});
+      }
+      setTimeout(initialize, 100);
+    </script>
+    <div id='display-area'>
+      <h2>Simple ChatRoom based on Google Channel</h2>
+      <div id="message-list">
+        <table id="message-table">
+        </table>
+      </div>
+      <br/>
+      <div>
+        <input type="text" value="say words..." name="words" id="words" />
+        <input type="button" value="SAY" name="say" id="say" />
+      </div>
+      <br/>
+      <div id='this-game' float='top'>
+        Invite other people to chat: <span id='this-game-link'><a href='{{ room_link }}'>{{ room_link }}</a></span>
+      </div>
+    </div>
+  </body>
+</html>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.