Пример #1
0
func OnConnect(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	roomName, userName := ParseClientId(r.FormValue("from"))

	c.Debugf("Connected user %s to room %s", userName, roomName)

	if room, err := GetRoom(c, roomName); err == nil {

		// see if user is in room
		if room.HasUser(userName) {
			c.Debugf("User already in room")
			// user already in the room
			// just send "connected" again in
			// case it was missed last time

			// or see if it's full
		} else if room.Occupants() == 2 {
			c.Debugf("Room Full, sending 'full' to %s", userName)
			if err := channel.Send(c, MakeClientId(roomName, userName), "full"); err != nil {
				c.Criticalf("OnConnect: Error while sending full:", err)
			}
			return

			// or add a user to the room
		} else {
			room.AddUser(userName)
			err = PutRoom(c, roomName, room)
			if err != nil {
				c.Criticalf("OnConnect: Connected could not put room %s: ", roomName, err)
				return
			}
		}

		// send connected to both when room is complete
		if room.Occupants() == 2 {
			otherUser := room.OtherUser(userName)
			c.Debugf("Room Complete, sending 'connected' to %s and %s", userName, otherUser)
			if err := channel.Send(c, MakeClientId(roomName, otherUser), "connected"); err != nil {
				c.Criticalf("OnConnect: Error while sending connected:", err)
			}
			if err := channel.Send(c, MakeClientId(roomName, userName), "connected"); err != nil {
				c.Criticalf("OnConnect: Error while sending connected:", err)
			}
		} else {
			c.Debugf("Waiting for another user before sending 'connected'")
		}

	} else {
		c.Criticalf("OnConnect: Could not get room %s: ", roomName, err)
	}
}
Пример #2
0
func publishToChannels(c appengine.Context, msg *Message) error {
	q := datastore.NewQuery("Endpoint").KeysOnly()
	endpoints, err := q.GetAll(c, nil)
	if err != nil {
		c.Errorf("Error getting enpoints: %v", err)
		return err
	}
	message, err := json.Marshal(msg)
	if err != nil {
		c.Errorf("Error marshaling msg -> json: %v", err)
		return err
	}
	errc := make(chan error)
	for _, e := range endpoints {
		go func(e *datastore.Key) {
			err := channel.Send(c, strconv.FormatInt(e.IntID(), 10), string(message))
			if err != nil {
				// Send failed. Delete the endpoint.
				if err := datastore.Delete(c, e); err != nil {
					c.Errorf("deleting endpoint: %v", err)
				}
			}
			errc <- err
		}(e)
	}
	for i := 0; i < len(endpoints); i++ {
		if err := <-errc; err != nil {
			c.Errorf("sending message: %v", err)
		}
	}
	return nil
}
Пример #3
0
func Handle(w http.ResponseWriter, r *http.Request) {
	context := appengine.NewContext(r)

	now := time.Now()
	expire := now.AddDate(30, 0, 0)
	zcookie, _ := r.Cookie("z")
	if zcookie == nil {
		zcookie = &http.Cookie{}
		zcookie.Name = "z"
		zcookie.Value = make_hash("127.0.0.1", r.RemoteAddr, now.UnixNano())
		zcookie.Expires = expire
		zcookie.Path = "/"
		zcookie.Domain = config.DOMAIN
		http.SetCookie(w, zcookie)
	}
	context.Infof("%s", zcookie.Value)

	w.Header().Set("Content-type", "image/gif")
	w.Header().Set("Cache-control", "no-cache, must-revalidate")
	w.Header().Set("Expires", "Sat, 26 Jul 1997 05:00:00 GMT")

	fmt.Fprintf(w, "%s", GIF)

	channel.Send(context, "pi", zcookie.Value+"\n"+r.RemoteAddr+"\n"+r.Referer()+"\n"+r.FormValue("r")+"\n"+r.UserAgent())
}
Пример #4
0
func OnMessage(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	roomName, userName := ParseClientId(r.FormValue("from"))

	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		c.Criticalf("OnMessage: Error while reading body: %s", err)
		return
	}
	r.Body.Close()

	room, err := GetRoom(c, roomName)
	if err != nil {
		c.Criticalf("OnMessage: Error while retreiving room %s:", roomName, err)
		return
	}

	c.Debugf("received channel data message from %s in %s: %s", userName, roomName, b)

	otherUser := room.OtherUser(userName)
	if otherUser != "" {
		if err := channel.Send(c, MakeClientId(roomName, otherUser), string(b)); err != nil {
			c.Criticalf("OnMessage: Error while sending JSON:", err)
			return
		}
	}

	w.Write([]byte("OK"))
}
Пример #5
0
func PostDing(c appengine.Context, key *datastore.Key, message string) os.Error {
	// If no message was passed, use a default
	if len(message) == 0 {
		message = "Ding-A-Ling!"
	}

	// Clients associated with this dinger
	var clients []Client

	// Return all clients associated with this dinger
	q := datastore.NewQuery(CLIENT_KEY_KIND).Ancestor(key)
	keys, err := q.GetAll(c, &clients)
	if err != nil {
		return err
	}

	// Iterate over all clients
	for i, k := range keys {
		client := &(clients[i])

		// Send the message to this client
		err = channel.Send(c, client.Id, message)
		if err != nil {
			// Error sending message, remove this client from the data store. Log any errors but
			// don't report them to the user
			err = datastore.Delete(c, k)
			if err != nil {
				c.Errorf("Error deleting client: %v", err)
			}
		}
	}

	return nil
}
Пример #6
0
func (r *Room) Send(c appengine.Context, message string) error {
	var clients []Client

	_, err := memcache.JSON.Get(c, r.Name, &clients)
	if err != nil && err != memcache.ErrCacheMiss {
		return err
	}

	if err == memcache.ErrCacheMiss {
		q := datastore.NewQuery("Client").Ancestor(r.Key(c))
		_, err = q.GetAll(c, &clients)
		if err != nil {
			return err
		}
		err = memcache.JSON.Set(c, &memcache.Item{
			Key: r.Name, Object: clients,
		})
		if err != nil {
			return err
		}
	}

	for _, client := range clients {
		err = channel.Send(c, client.ClientID, message)
		if err != nil {
			c.Errorf("sending %q: %v", message, err)
		}
	}

	return nil
}
Пример #7
0
func (self *channelAPI) forwardToSession(userid string, sessionid string, message string) (err os.Error) {
	//  log.Printf("Sending to session %v: %v", userid+ "/" + sessionid, message)
	err = channel.Send(self.c, userid+"/"+sessionid, message)
	if err != nil {
		log.Printf("Failed sending to channel %v", userid+"/"+sessionid)
	}
	return nil
}
Пример #8
0
func sendHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	id := r.FormValue("clientID")
	msg := r.FormValue("msg")
	if err := channel.Send(c, id, msg); err != nil {
		c.Errorf("channel send failed: %v", err)
	}
}
Пример #9
0
func hotload(w http.ResponseWriter, r *http.Request) {
	file := r.FormValue("file")
	c := appengine.NewContext(r)
	err := channel.Send(c, "hotload", file)
	if err != nil {
		// handle error
	}
	// return token to the client in an HTTP response
	fmt.Fprintln(w, "sending message")
}
Пример #10
0
func handleDelayedNotify(w http.ResponseWriter, r *http.Request) {
	log.Printf("Task started")
	c := appengine.NewContext(r)
	// Read the form data
	perma_blobref := r.FormValue("perma")
	// Allow for further notification tasks to be enqueued
	memcache.Delete(c, "notify-"+perma_blobref)
	// Find out about the users of this permanode
	s := newStore(c)
	data, err := s.GetPermaNode(perma_blobref)
	if err != nil {
		http.Error(w, "Err: Failed reading permanode", http.StatusInternalServerError)
		return
	}
	perma := grapher.NewPermaNode(nil)
	perma.FromMap(perma_blobref, data)
	message := fmt.Sprintf(`{"type":"notification", "perma":"%v", "lastseq":%v}`, perma_blobref, perma.SequenceNumber()-1)
	// For all users find all channels on which they are listening
	for _, user := range perma.Users() {
		// Do we know this user?
		userid, err := isLocalUser(c, user)
		if err != nil {
			// TODO: In the case of federation this is not really an error?
			log.Printf("Err: Unknown user %v", user)
			continue
		}
		// Mark that there is an unread file
		err = addUnread(c, userid, perma_blobref)
		if err != nil {
			log.Printf("Err writing unread: %v", err)
		}
		// Notify browser instances where this user is logged in
		var channels []channelStruct
		query := datastore.NewQuery("channel").Filter("UserEmail =", user)
		for it := query.Run(c); ; {
			var data channelStruct
			_, e := it.Next(&data)
			if e == datastore.Done {
				break
			}
			if e != nil {
				log.Printf("Err: in query: %v", e)
				break
			}
			channels = append(channels, data)
		}
		for _, ch := range channels {
			log.Printf("Sending to %v", ch.UserID+"/"+ch.SessionID)
			err := channel.Send(c, ch.UserID+"/"+ch.SessionID, message)
			if err != nil {
				log.Printf("Failed sending to channel %v", ch.UserID+"/"+ch.SessionID)
			}
		}
	}
}
Пример #11
0
func broadcastState(c appengine.Context, g *poker.GameState) error {
	for _, watcher := range g.Watchers {
		json, err := g.ClientState(watcher).JSON()
		if err != nil {
			return err
		}
		err = channel.Send(c, watcher+g.Id(), json)
		if err != nil {
			c.Errorf("sending Game: %v", err)
		}
	}
	return nil
}
Пример #12
0
func OnDisconnect(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	roomName, userName := ParseClientId(r.FormValue("from"))
	if room, err := GetRoom(c, roomName); err == nil {

		if room.HasUser(userName) == false {
			c.Debugf("OnDisconnect: User %s not found in room %s", userName, roomName)
			return
		}

		// get the other user before we remove the current one
		otherUser := room.OtherUser(userName)
		empty := room.RemoveUser(userName)
		c.Debugf("OnDisconnect: Removed user %s from room %s", userName, roomName)

		err := PutRoom(c, roomName, room)
		if err != nil {
			c.Criticalf("OnDisconnect: Could not put room %s: ", roomName, err)
			return
		}

		if empty {
			c.Debugf("OnDisconnect: Room is now empty.")

		} else if otherUser != "" {
			c.Debugf("Removed %s. Sending 'disconnected' to %s", userName, MakeClientId(roomName, otherUser))
			if err := channel.Send(c, MakeClientId(roomName, otherUser), "disconnected"); err != nil {
				c.Criticalf("OnDisconnect: Error while sending 'disconnected':", err)
			}
			c.Debugf("Removed %s. Sending 'disconnected' to %s", userName, MakeClientId(roomName, userName))
			if err := channel.Send(c, MakeClientId(roomName, userName), "disconnected"); err != nil {
				c.Criticalf("OnDisconnect: Error while sending 'disconnected':", err)
			}
		}
	} else {
		c.Criticalf("OnDisconnect: Could not get room %s: ", roomName, err)
	}
}
Пример #13
0
func (self *channelAPI) forwardToUser(username string, message string) (err os.Error) {
	channels, err := self.channelsByUser(username)
	if err != nil {
		return err
	}
	for _, ch := range channels {
		log.Printf("Sending to user %v", ch.UserID+"/"+ch.SessionID)
		err = channel.Send(self.c, ch.UserID+"/"+ch.SessionID, message)
		if err != nil {
			log.Printf("Failed sending to channel %v", ch.UserID+"/"+ch.SessionID)
		}
	}

	return nil
}
Пример #14
0
func handleStartStream(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	buff := make([]string, BUFFSIZE)
	for i := 0; i < 400; i++ {
		f := math.Sin(float64(i)*8.0*math.Pi/100.0) + math.Sin(float64(i)*4.0*math.Pi/100.0)
		f = f / 2
		buff[i%BUFFSIZE] = strconv.FormatFloat(f, 'f', -1, 64)
		if i%BUFFSIZE == BUFFSIZE-1 {
			msg := strings.Join(buff, ",")
			channel.Send(c, "placeholder", msg)
		}
	}

	jsonEncoder := json.NewEncoder(w)
	jsonEncoder.Encode(StartStreamResponse{"done"})
}
Пример #15
0
func fetch(w http.ResponseWriter, r *http.Request) {

	c := appengine.NewContext(r)

	imageUrl := r.FormValue("image")
	c.Infof("THIS IS IMAGE URL %v", imageUrl)
	client := urlfetch.Client(c)
	resp, err := client.Get(imageUrl)
	if error3(err, c, w) {
		return
	}

	blob, err := blobstore.Create(c, resp.Header.Get("Content-Type"))
	if error3(err, c, w) {
		return
	}
	written, err := io.Copy(blob, resp.Body)
	if error3(err, c, w) {
		return
	}
	if written < 100 {
		c.Infof("image is too small %v", written)
		return
	}
	err = blob.Close()
	if error3(err, c, w) {
		return
	}

	blobkey, err := blob.Key()
	if error3(err, c, w) {
		return
	}

	thumbnailUrl, err := image.ServingURL(c, blobkey, &image.ServingURLOptions{Size: 100})
	if error3(err, c, w) {
		return
	}
	t := thumbnailUrl.String()
	errr := channel.Send(c, "qwerty", t)
	if error3(errr, c, w) {
		return
	}
	// c.Infof("THIS IS IMAGE URL %v", t)
}
Пример #16
0
func (self *channelAPI) forwardToFollowers(perma_blobref string, message string) (err os.Error) {
	channels, err := self.channelsByFollowers(perma_blobref)
	if err != nil {
		return err
	}
	for _, ch := range channels {
		// Do not send to the session that caused this
		if ch.UserID+"/"+ch.SessionID == self.userID+"/"+self.sessionID {
			continue
		}
		log.Printf("Sending to %v", ch.UserID+"/"+ch.SessionID)
		err = channel.Send(self.c, ch.UserID+"/"+ch.SessionID, message)
		if err != nil {
			log.Printf("Failed sending to channel %v", ch.UserID+"/"+ch.SessionID)
		}
	}

	self.sendSlowNotifications(perma_blobref)
	return nil
}
Пример #17
0
/*
	関数 Message(gamekey, message)
	- ゲームの参加者全員にメッセージを送信する
*/
func Message(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	gamekey := r.FormValue("gamekey")
	message := r.FormValue("message")

	memory, err := memcache.Get(c, gamekey)
	Check(c, err)
	value := memory.Value

	players := []map[string]string{}
	msg := map[string]string{}
	json.Unmarshal(value, &players)
	json.Unmarshal(([]byte)(message), &msg)

	for i := range players {
		if players[i]["id"] != msg["id"] {
			c.Debugf(msg["id"] + "->" + players[i]["id"] + " : " + msg["content"])
			err := channel.Send(c, players[i]["id"], msg["content"])
			Check(c, err)
		}
	}
}
Пример #18
0
func background(c appengine.Context) {
	uv, pv := count_uv_pv(c, 15)
	c.Infof("uv: %d, pv: %d", uv, pv)
	channel.Send(c, "pi", fmt.Sprintf("%d %d", uv, pv))
}
Пример #19
0
func SendMessage(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	token := r.FormValue("id")
	data := r.FormValue("json")
	channel.Send(c, token, data)
}
Пример #20
0
func interview_send(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	token := r.FormValue("id")
	code := r.FormValue("code")
	channel.Send(c, token, code)
}
Пример #21
0
		return
	}

	token, err := channel.Create(ctx, clientID)
	if err != nil {
		ctx.Infof("create(%q): %s", clientID, err)
		http.Error(w, "unable to create channel", http.StatusInternalServerError)
		return
	}

	io.WriteString(w, token)
}

var broadcastPaste = delay.Func("broadcastPaste", func(ctx appengine.Context, url string) {
	q := datastore.NewQuery("client").KeysOnly()
	keys, err := q.GetAll(ctx, nil)
	if err != nil {
		ctx.Errorf("getall: %s", err)
		return
	}
	ctx.Infof("Found %d clients", len(keys))
	for _, client := range keys {
		clientID := client.StringID()
		if err := channel.Send(ctx, clientID, url); err != nil {
			ctx.Errorf("send(%q): %s", clientID, err)
			continue
		}
		ctx.Infof("Sent URL to %q", clientID)
	}
})