Exemplo n.º 1
0
func AddClient(c appengine.Context, id string) (string, os.Error) {

	q := datastore.NewQuery("Client")
	var gg []*Client
	var check = 0

	if _, err := q.GetAll(c, &gg); err != nil {
		return "", err
	}

	for _, client := range gg {
		if client.ClientID == id {
			check = check + 1
		}
	}

	if check == 0 {
		key := datastore.NewIncompleteKey("Client")
		client := Client{ClientID: id}

		_, err := datastore.Put(c, key, &client)
		if err != nil {
			return "", err
		}
	}

	memcache.Delete(c, "sut")

	return channel.Create(c, id)

}
Exemplo n.º 2
0
func idhandler(w http.ResponseWriter, r *http.Request) {
	c = appengine.NewContext(r)
	clientID := strconv.Itoa(rand.Int())

	// add nick to db
	keysCache := &memcache.Item{
		Key:   clientID,
		Value: []byte(r.FormValue("nick")),
	}
	memcache.Set(c, keysCache)
	// add user to list
	userList := getUserList()
	if !stringInSlice(clientID, userList) {
		keys := append(userList, clientID)
		setUserList(keys)
	}
	// create channel
	tok, _ := channel.Create(c, clientID)
	responseList := []map[string]string{{"tok": tok, "id": clientID}}
	for _, id := range userList {
		nick := getNick(id)
		responseList = append(responseList, map[string]string{"nick": nick, "id": id})
	}
	response, _ := json.Marshal(responseList)
	fmt.Fprint(w, string(response))
}
Exemplo n.º 3
0
func GetToken(c appengine.Context, h *hunt.Hunt, t *team.Team, admin bool) string {
	// Channel name format: huntID.timestamp
	timestamp := fmt.Sprintf("%d", time.Now().UnixNano())
	channelName := fmt.Sprintf("%s.%s", h.ID, timestamp)
	token, err := channel.Create(c, channelName)
	if err != nil {
		c.Errorf("Error: %v", err)
		return ""
	}
	listener := Listener{
		Channel:   channelName,
		Timestamp: timestamp,
		Admin:     admin,
		Open:      false,
	}
	if t != nil {
		listener.TeamID = t.ID
	}
	_, err = datastore.Put(c, datastore.NewIncompleteKey(c, listenerKind, h.Key), &listener)
	if err != nil {
		c.Errorf("Error: %v", err)
		return ""
	}
	return token
}
Exemplo n.º 4
0
// Make a client of the specified dinger and return the id and token associated with the new client.
func MakeClient(c appengine.Context, dingerKey *datastore.Key) (*Client, os.Error) {
	// Create a key for this client
	key := datastore.NewKey(CLIENT_KEY_KIND, "", 0, dingerKey)

	// Generate some id for the client. It'll be the SHA1 sum of the dinger id and some random number.
	hashWriter := sha1.New()
	fmt.Fprint(hashWriter, KeyToDingerId(dingerKey))

	// Append a random integer
	randId, err := rand.Int(rand.Reader, big.NewInt(0x7fffffffffffffff))
	if err != nil {
		return nil, err
	}
	fmt.Fprint(hashWriter, randId)

	// Base64 encode the client id
	id := base64.URLEncoding.EncodeToString(hashWriter.Sum())

	// Create a channel for this client.
	tok, err := channel.Create(c, id)
	if err != nil {
		return nil, err
	}

	// Create the client record and store it
	client := &Client{Id: id, Token: tok}
	key, err = datastore.Put(c, key, client)
	if err != nil {
		return nil, err
	}

	return client, nil
}
Exemplo n.º 5
0
Arquivo: hello.go Projeto: hundt/poker
func goToGame(w http.ResponseWriter, r *http.Request) {
	g, err := poker.LoadGame(r.FormValue("id"), r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	c := appengine.NewContext(r)
	u := user.Current(c)
	tok, err := channel.Create(c, u.Email+g.Id())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if addWatcher(g, u.Email) {
		err := g.Save(r)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
	json, err := g.ClientState(u.Email).JSON()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defineNames(w)
	if err := gameTemplate.Execute(w, json); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	fmt.Fprintf(w, "<script>channel('%s')</script>", tok)
}
Exemplo n.º 6
0
func root(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	clientTemplate := template.Must(template.ParseFile("client.html"))
	token_value := strconv.Itoa(rand.Int())
	token_key, _ := channel.Create(c, token_value)
	clientTemplate.Execute(w, token_key)
	map_clients[token_key] = token_value
}
Exemplo n.º 7
0
func getchannel(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	tok, err := channel.Create(c, "hotload")
	if err != nil {
		// handle error
	}
	// return token to the client in an HTTP response
	fmt.Fprintln(w, tok)
}
Exemplo n.º 8
0
func initChannel(pfc *PFContext) (interface{}, error) {
	if pfc.ChannelID == "" {
		return nil, NewReadableError(_l("Missing Client ID"), nil)
	}

	if token, err := channel.Create(pfc.C, pfc.ChannelID); err != nil {
		return nil, NewReadableError(_l("Error initializing channel"), &err)
	} else {
		return map[string]string{"token": token}, nil
	}
}
Exemplo n.º 9
0
func handleCreateChannel(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	token, err := channel.Create(c, "placeholder")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	w.Header().Set("Content-type", "text/json; charset=utf-8")
	jsonEncoder := json.NewEncoder(w)
	jsonEncoder.Encode(CreateChannelResponse{token})
}
Exemplo n.º 10
0
func connect(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	users++
	id := strconv.Itoa(users)
	tok, err := channel.Create(c, id)
	if err != nil {
		http.Error(w, "Couldn't create Channel", http.StatusInternalServerError)
		c.Errorf("channel.Create: %v", err)
		return
	}
	payload, _ := json.Marshal(map[string]string{"me": id, "token": tok})
	fmt.Fprint(w, string(payload))
}
Exemplo n.º 11
0
// AddClient puts a Client record to the datastore with the Room as its
// parent, creates a channel and returns the channel token.
func (r *Room) AddClient(c appengine.Context, id string) (string, error) {
	key := datastore.NewKey(c, "Client", id, 0, r.Key(c))
	client := &Client{id}
	_, err := datastore.Put(c, key, client)
	if err != nil {
		return "", err
	}

	// Purge the now-invalid cache record (if it exists).
	memcache.Delete(c, r.Name)

	return channel.Create(c, id)
}
Exemplo n.º 12
0
func handleWrPage(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	queryMap := r.URL.Query()
	table := queryMap.Get("t")
	id := queryMap.Get("u")
	token, err := channel.Create(c, table+"-"+id)
	err = tableTemplate.Execute(w, map[string]string{
		"userToken": token,
	})
	if err != nil {
		c.Errorf("tableTemplate: %v", err)
	}
}
Exemplo n.º 13
0
func interview_create(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	tok, err := channel.Create(c, r.FormValue("id"))
	callback := r.FormValue("callback")
	if err != nil {
		http.Error(w, "Couldn't create Channel", http.StatusInternalServerError)
		c.Errorf("channel.Create: %v", err)
		return
	}
	if callback == "" {
		callback = "callback"
	}
	fmt.Fprintf(w, callback+"('%s')", tok)
}
Exemplo n.º 14
0
func whiteboardHandler(w http.ResponseWriter, r *http.Request) {
	vm := NewWhiteboardVM()
	c := appengine.NewContext(r)

	code := r.FormValue("x")
	repo := repository.NewRepo(c)
	candidate, interviewer, err := repo.GetSession(code)

	if err != nil {
		c.Errorf("repo.GetSession: %v", err)
		http.Redirect(w, r, "/", http.StatusMovedPermanently)
		return
	}

	vm.Candidate, vm.Interviewer = candidate, interviewer

	tc := twilio.NewTwilioCapability(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

	vm.IsInterviewer = (code == interviewer)
	if vm.IsInterviewer {
		vm.Message = "Interviewer mode."
		tc.AllowClientOutgoing(TWILIO_APP_SID, nil)
	} else {
		vm.Message = "Candidate mode."
		tc.AllowClientIncoming(candidate)
	}

	tokenExpiration := time.Duration(48) * time.Hour

	twilioToken, err := tc.Generate(tokenExpiration)

	if err != nil {
		c.Errorf("capability.Generate: %s", err)
		http.Error(w, "Twilio setup error.", http.StatusInternalServerError)
		return
	}
	vm.TwilioToken = twilioToken

	// Create channel token.
	tok, err := channel.Create(c, code)
	if err != nil {
		c.Errorf("template.ParseSetFiles: %s", err)
		http.Error(w, "Channel error.", http.StatusInternalServerError)
		return
	}
	vm.ChannelToken = tok

	renderPage(w, c, "view/whiteboard.html", vm)
}
Exemplo n.º 15
0
func OnToken(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	roomName := r.FormValue("room")
	if roomName != "" {
		userName := Random(10)
		clientId := MakeClientId(roomName, userName)
		token, err := channel.Create(c, clientId)
		if err != nil {
			c.Criticalf("Error while creating token: %s", err)
		}
		w.Write([]byte("user="******"&token=" + token))
	} else {
		w.WriteHeader(http.StatusBadRequest)
	}
}
Exemplo n.º 16
0
func newClient(context appengine.Context, r *http.Request) *Client {
	c := new(Client)
	c.name = r.FormValue("name")
	c.action = r.FormValue("action")

	// ユーザIDが設定されていなければ新しく設定する
	c.id = r.FormValue("id")
	if c.id == "" {
		c.id = CreateId()
	}

	var err error
	c.token, err = channel.Create(context, c.id)
	Check(context, err)
	return c
}
Exemplo n.º 17
0
func GetToken(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	tok, err := channel.Create(c, r.FormValue("id"))
	callback := r.FormValue("callback")
	if err != nil {
		http.Error(w, "Couldn't create Channel", http.StatusInternalServerError)
		c.Errorf("channel.Create: %v", err)
		return
	}
	if callback == "" {
		w.Header().Set("Content-type", "text/javascript")
		fmt.Fprintf(w, "%s", tok)
	} else {
		fmt.Fprintf(w, callback+"('%s')", tok)
	}
}
Exemplo n.º 18
0
func getToken(c appengine.Context, playerId string) (string, error) {
	item, err := memcache.Get(c, "token::"+playerId)
	if err != nil {
		tok, err := channel.Create(c, playerId)
		if err != nil {
			return "", err
		}
		memcache.Set(c, &memcache.Item{
			Key:        "token::" + playerId,
			Value:      []byte(tok),
			Expiration: 2 * time.Hour,
		})
		return tok, nil
	}
	tok := string(item.Value)
	return tok, nil
}
Exemplo n.º 19
0
func joinRoom(c appengine.Context, roomId string, email string) (string, error) {
	room := newRoom()
	item, err := memcache.JSON.Get(c, roomId, room)
	if err != nil {
		return "", err
	}

	room.Users[email] = true
	item.Object = room

	if err := memcache.JSON.Set(c, item); err != nil {
		return "", err
	}

	publish(c, roomId, email, "")
	return channel.Create(c, email+roomId)
}
Exemplo n.º 20
0
func handleFrontPage(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.Error(w, "404 Not Found", http.StatusNotFound)
		return
	}
	c := appengine.NewContext(r)
	userid, sessionid, err := getSession(c, r)
	if err != nil {
		http.Redirect(w, r, "/login/login.html", 307)
		return
	}

	if frontPageTmplErr != nil {
		w.WriteHeader(http.StatusInternalServerError) // 500
		fmt.Fprintf(w, "Page template is bad: %v", frontPageTmplErr)
		return
	}

	tok, err := channel.Create(c, userid+"/"+sessionid)
	if err != nil {
		http.Error(w, "Couldn't create Channel", http.StatusInternalServerError)
		c.Errorf("channel.Create: %v", err)
		return
	}

	var ch channelStruct
	ch.UserID = userid
	ch.Token = tok
	ch.SessionID = sessionid
	_, err = datastore.Put(c, datastore.NewKey("channel", userid+"/"+sessionid, 0, nil), &ch)
	if err != nil {
		return
	}

	b := new(bytes.Buffer)
	data := map[string]interface{}{"userid": userid, "token": tok, "session": sessionid}
	if err := frontPageTmpl.Execute(b, data); err != nil {
		w.WriteHeader(http.StatusInternalServerError) // 500
		fmt.Fprintf(w, "tmpl.Execute failed: %v", err)
		return
	}

	w.Header().Set("Content-Length", strconv.Itoa(b.Len()))
	b.WriteTo(w)
}
Exemplo n.º 21
0
func channelListen(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)

	clientID := r.FormValue("clientID")
	if clientID == "" {
		http.Error(w, "no ClientID specified", http.StatusBadRequest)
		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)
}
Exemplo n.º 22
0
func handle(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		Execute("get", w, nil)
	case "POST":
		wID := r.FormValue("ID")
		wToken, err := channel.Create(appengine.NewContext(r), wID)
		if err != nil {
			Execute("get", w, map[string]string{"Error": err.Error()})
		} else {
			Execute(
				"post",
				w,
				map[string]string{
					"ID":    wID,
					"Token": wToken,
				},
			)
		}
	case "PUT":
		ctx := appengine.NewContext(r)

		keys, err := datastore.NewQuery("Channels").KeysOnly().GetAll(ctx, nil)
		if err != nil {
			panic(err)
		}

		for _, key := range keys {
			if err := channel.SendJSON(
				ctx,
				key.StringID(),
				map[string]interface{}{
					"message": r.FormValue("Message"),
					"ID":      r.FormValue("ID"),
				},
			); err != nil {
				panic(err)
			}
		}
	}
}
Exemplo n.º 23
0
// create new client and put on datastore
func NewClient(c appengine.Context) (*ClientInfo, error) {

	// key
	key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "ClientInfo", nil), &ClientInfo{"", ""})

	// create token and clientID
	clientID := fmt.Sprintf("%d", key.IntID())
	tok, err := channel.Create(c, clientID)
	if err != nil {
		return nil, err
	}

	client := &ClientInfo{clientID, tok}
	c.Infof("Regist %#v", client)
	_, err = datastore.Put(c, key, client)
	if err != nil {
		return nil, err
	}

	return client, nil
}
Exemplo n.º 24
0
Arquivo: main.go Projeto: kiran-mk/go
func handler(w http.ResponseWriter, r *http.Request) {
	uuid := ""
	c := appengine.NewContext(r)
	pubInstance := messaging.New(c, uuid, w, r, publishKey, subscribeKey, secretKey, "", false)
	if pubInstance == nil {
		c.Errorf("Couldn't create pubnub instance")
		http.Error(w, "Couldn't create pubnub instance", http.StatusInternalServerError)
		return
	}
	nuuid := pubInstance.GetUUID()

	session, err := store.Get(r, "example-session")
	if err != nil {
		c.Errorf("Session store error %s", err.Error())
		http.Error(w, "Session store error", http.StatusInternalServerError)
		return
	}

	//Enhancement: can be kept in memcache
	tok, err := channel.Create(c, nuuid)
	if err != nil {
		http.Error(w, "Couldn't create Channel", http.StatusInternalServerError)
		c.Errorf("channel.Create: %v", err)
		return
	}
	session.Values["token"] = tok

	err1 := mainTemplate.Execute(w, map[string]string{
		"token":        tok,
		"uuid":         nuuid,
		"subscribeKey": subscribeKey,
		"publishKey":   publishKey,
		"secretKey":    secretKey,
	})
	if err1 != nil {
		c.Errorf("mainTemplate: %v", err1)
	}
}
Exemplo n.º 25
0
Arquivo: main.go Projeto: kiran-mk/go
func connect(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	pubKey := q.Get("pubKey")
	subKey := q.Get("subKey")
	uuid := q.Get("uuid")
	secKey := q.Get("secKey")
	cipher := q.Get("cipher")
	ssl := q.Get("ssl")
	bSsl := false
	if ssl == "1" {
		bSsl = true
	}

	c := appengine.NewContext(r)
	messaging.SetSessionKeys(c, w, r, pubKey, subKey, secKey, cipher, bSsl, uuid)

	session, err := store.Get(r, "example-session")
	if err != nil {
		c.Errorf("Session store error %s", err.Error())
		http.Error(w, "Session store error", http.StatusInternalServerError)
		return
	}

	tok, err := channel.Create(c, uuid)

	if err != nil {
		http.Error(w, "Couldn't create Channel", http.StatusInternalServerError)
		c.Errorf("channel.Create: %v", err)
		return
	}
	session.Values["token"] = tok
	err1 := session.Save(r, w)
	if err1 != nil {
		c.Errorf("error1, %s", err1.Error())
	}
	fmt.Fprintf(w, tok)
}
Exemplo n.º 26
0
func getChannelToken(c appengine.Context, w http.ResponseWriter, req *http.Request) (string, error) {
	tokenCookie, err := req.Cookie("token")
	if err != nil {
		low, _, err := datastore.AllocateIDs(c, "Endpoint", nil, 1)
		if err != nil {
			return "", err
		}
		browserId := strconv.FormatInt(low, 10)
		token, err := channel.Create(c, browserId)
		if err != nil {
			return "", err
		}
		cookie := http.Cookie{Name: "token", Value: token, MaxAge: 7200} /* two hours */
		http.SetCookie(w, &cookie)

		epkey := datastore.NewKey(c, "EndpointUser", "", low, nil)
		if _, err := datastore.Put(c, epkey, &EndpointUser{Token: token, CreatedOn: time.Now()}); err != nil {
			return "", err
		}

		return token, nil
	}
	return tokenCookie.Value, nil
}
Exemplo n.º 27
0
// processHandler initiates the processing of an Overlay, including kicking off
// appropriate slice tasks.
func processHandler(c appengine.Context, w http.ResponseWriter, r *http.Request) *appError {
	if r.Method != "POST" {
		return &appError{nil, "must use POST", http.StatusMethodNotAllowed}
	}

	// Get the Overlay from the datastore.
	k, o, err := getOverlay(r)
	if err != nil {
		return appErrorf(err, "overlay not found")
	}

	// Process the request.
	if o.TopLeft, err = parsePair(r.FormValue("topLeft")); err != nil {
		return appErrorf(err, "invalid parameter topLeft")
	}
	if o.TopRight, err = parsePair(r.FormValue("topRight")); err != nil {
		return appErrorf(err, "invalid parameter topLeft")
	}
	if o.BottomRight, err = parsePair(r.FormValue("bottomRight")); err != nil {
		return appErrorf(err, "invalid parameter bottomRight")
	}

	// Compute the transformation matrix.
	a := graphics.I.Scale(1/float64(o.Width), 1/float64(o.Height)).
		Mul(inverse(graphics.Affine{
			o.TopRight[0] - o.TopLeft[0], o.BottomRight[0] - o.TopRight[0], o.TopLeft[0],
			o.TopRight[1] - o.TopLeft[1], o.BottomRight[1] - o.TopRight[1], o.TopLeft[1],
			0, 0, 1,
		}))
	o.Transform = []float64(a[:])

	// TODO(cbro): get min/max zoom from user.
	o.MinZoom = 0
	o.MaxZoom = 21

	// Compute tiles to be generated.
	var tiles []*Tile
	for zoom := o.MinZoom; zoom <= o.MaxZoom; zoom++ {
		tiles = append(tiles, tilesForZoom(o, zoom)...)
	}
	o.Tiles = len(tiles)

	// Create a channel between the app and the client's browser.
	token, err := channel.Create(c, k.Encode())
	if err != nil {
		return appErrorf(err, "couldn't create browser channel")
	}

	// Put the updated Overlay into the datastore.
	if _, err := datastore.Put(c, k, o); err != nil {
		return appErrorf(err, "could not save overlay to datastore")
	}

	// Create tasks to generate tiles.
	tasks := tileTasks(k.Encode(), tiles)
	if err := addTasks(c, tasks, tileQueue); err != nil {
		return appErrorf(err, "could not start tiling process")
	}

	// Create task to start slice process.
	task := taskqueue.NewPOSTTask("/slice", url.Values{"key": {k.Encode()}})
	for i := 0; i < sliceBackends; i++ {
		host := appengine.BackendHostname(c, sliceBackend, i)
		task.Header.Set("Host", host)
		if _, err := taskqueue.Add(c, task, sliceQueue); err != nil {
			return appErrorf(err, "could not start tiling process")
		}
	}

	// Send channel token as response.
	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte(token))
	return nil
}
Exemplo n.º 28
0
func EditPost(blog_config map[string]interface{}) func(w http.ResponseWriter, req *http.Request) {
	template_dir := "templates/"
	l := func(w http.ResponseWriter, req *http.Request) {
		appcontext := appengine.NewContext(req)

		context := map[string]interface{}{}

		name := req.URL.Query().Get(":name")
		if name != "" {
			query := post.GetPostsMatchingUrl(req.URL.Query().Get(":name"))
			idx, err := post.GetCount(appcontext, query)

			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}

			if idx < 1 {
				context["articlesource"] = "Enter your post here!"
				context["labels"] = "visible"
				context["title"] = "No post with that URL found, making new post!"
			} else {
				var ps []post.Post
				keys, err := query.GetAll(appcontext, &ps)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
				}

				p := ps[0]
				tags, err := post.GetTagSlice(appcontext, keys[0])
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
				}

				content, err := post.GetPostContent(appcontext, p)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
				}

				context["articlesource"] = content
				context["labels"] = strings.Join(tags, ", ")
				context["title"] = p.Title
			}
		} else {
			context["articlesource"] = "Enter your post here!"
			context["labels"] = "visible, enter, labels, here"
			context["title"] = "enter title here"
		}

		key := fmt.Sprintf("%v", rand.Int())
		tok, err := channel.Create(appcontext, key)
		if err != nil {
			http.Error(w, "Couldn't create Channel", http.StatusInternalServerError)
			appcontext.Errorf("channel.Create: %v", err)
			return
		}

		posturl := "/admin/post?g=" + key
		uploadurl, err := blobstore.UploadURL(appcontext, posturl, nil)
		if err != nil {
			http.Error(w, "Couldn't create blob URL", http.StatusInternalServerError)
			appcontext.Errorf("blobstore.UploadURL: %v", err)
			return
		}

		context["token"] = tok
		context["session"] = key
		context["uploadurl"] = uploadurl

		total_con := config.Stringify_map(config.Merge(blog_config, context))
		c := mustache.RenderFile(template_dir+"edit.html.mustache", total_con)
		io.WriteString(w, c)

		if err != nil {
			appcontext.Errorf("mainTemplate: %v", err)
		}
	}
	return admin_layout(blog_config, l)
}
Exemplo n.º 29
0
func start(w http.ResponseWriter, r *http.Request) {
	target := r.FormValue("target")
	c := appengine.NewContext(r)

	client := urlfetch.Client(c)
	resp, err := client.Get("http://" + target)
	if error3(err, c, w) {
		return
	}

	len := int(resp.ContentLength)
	buf := make([]byte, len)
	read, err := resp.Body.Read(buf)
	if error3(err, c, w) {
		return
	}
	if read != len {
		http.Error(w, fmt.Sprintf("Target page Content-Length is %v but read %v bytes", len, read), http.StatusInternalServerError)
		return
	}

	rx, _ := regexp.Compile("<img .*? src=\"(.*?)\"")
	images := rx.FindAllSubmatch(buf, len)
	if images == nil {
		w.Header().Set("Content-Type", "text/plain")
		fmt.Fprintf(w, "HTTP GET returned status %v\nNo images found\n\n", resp.Status)
		w.Write(buf)
		return
	}

	for _, image := range images {

		addr := string(image[1])
		// c.Infof("THIS IS IMAGE URL %v", addr)
		if strings.Index(addr, "http") == 0 {
			task := taskqueue.NewPOSTTask("/fetch", url.Values{"image": {addr}})
			_, err := taskqueue.Add(c, task, "default")
			if error3(err, c, w) {
				return
			}

		}
	}

	tok, err := channel.Create(c, "qwerty")
	if error3(err, c, w) {
		return
	}

	if templates == nil {
		var err error
		templates, err = template.ParseFiles("templates/gallery.html")
		if error3(err, c, w) {
			return
		}
	}

	w.Header().Set("Content-Type", "text/html")
	templates.ExecuteTemplate(w, "gallery.html", tok)

}
Exemplo n.º 30
0
func main(w http.ResponseWriter, r *http.Request) {

	c := appengine.NewContext(r)
	u := user.Current(c) // assumes 'login: required' set in app.yaml

	tkey := r.FormValue("chatkey")
	// chatkeyのクエリが空でここに来た場合、chatkeyを
	// このユーザのIDとする(=新しいchat部屋を作る)
	if tkey == "" {
		tkey = u.ID
	}

	// channel を uID+tkeyで作る
	// どのチャット部屋のどのユーザかが決まる
	tok, err := channel.Create(c, u.ID+tkey)
	if err != nil {
		http.Error(w, "Couldn't create Channel", http.StatusInternalServerError)
		c.Errorf("channel.Create: %v", err)
		return
	}

	// 現在のチャット部屋の最新の
	// 発言内容を20件取得
	q := datastore.NewQuery("message").Ancestor(tinychatKey(c, tkey)).Order("-Date").Limit(20)
	messages := make([]Message, 0, 20)
	if _, err := q.GetAll(c, &messages); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// u.IDで部屋の参加者リストに自分がいるかを検索
	q = datastore.NewQuery("Member").Ancestor(memberKey(c, tkey)).
		Filter("ID =", u.ID)
	members := make([]Member, 0, 1)
	if _, err := q.GetAll(c, &members); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// 見つからなければ自分をメンバリストに追加
	if len(members) == 0 {
		m := Member{
			ID: u.ID,
		}
		key := datastore.NewIncompleteKey(c, "Member", memberKey(c, tkey))
		_, err := datastore.Put(c, key, &m)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	// HTML出力のための準備
	d := Display{
		Token:    tok,
		Me:       u.ID,
		Chat_key: tkey,
		Messages: messages,
	}

	err = mainTemplate.Execute(w, d)
	if err != nil {
		c.Errorf("mainTemplate: %v", err)
	}
}