Ejemplo n.º 1
0
// API that updates the level of a permission. Only owners can elevate a user's
// permission. Requires "userKey" of the user whose permission to update, the
// "doorKey" of the involved door, and the desired "level" of the permission.
func updatePermission(
	r *http.Request, c appengine.Context, u *user.User) (*[]Permission, error) {
	uKey, err := ds.DecodeKey(r.FormValue("userKey"))
	if err != nil {
		return nil, ErrNoUserKey
	}
	var dKey *ds.Key
	dKey, err = ds.DecodeKey(r.FormValue("doorKey"))
	if err != nil {
		return nil, ErrNoDoorKey
	}
	var level int
	level, err = strconv.Atoi(r.FormValue("level"))
	if err != nil {
		return nil, Err{"'level' missing or invalid.", http.StatusBadRequest}
	}
	if level != LevelOpener {
		return nil, Err{"Only updating a permission to opener is allowed.",
			http.StatusForbidden}
	}

	// Verify caller is owner of the door.
	p := Permission{}
	cnt := 0
	if cnt, err = ds.NewQuery("Permission").
		Filter("userKey=", ds.NewKey(c, "User", u.ID, 0, nil)).
		Filter("doorKey=", dKey).
		Filter("level=", LevelOwner).
		Count(c); err != nil {
		return nil, err
	}
	if cnt == 0 {
		return nil, Err{
			"Either the door doesn't exist, or you are not an owner on it.",
			http.StatusForbidden}
	}

	p = Permission{}
	k, err := ds.NewQuery("Permission").
		Filter("userKey=", uKey).
		Filter("doorKey=", dKey).
		Run(c).
		Next(&p)
	if err != nil {
		if err == ds.Done {
			err = Err{"User not has asked for permission on this door",
				http.StatusForbidden}
		}
		return nil, err
	}

	p.Level = level
	if _, err = ds.Put(c, k, &p); err != nil {
		return nil, err
	}

	return &[]Permission{p}, nil
}
Ejemplo n.º 2
0
// handler to access pairings as children of a dish (parent)
func pairingHandler(c *context) {
	// validate the dish key
	parentKey, err := datastore.DecodeKey(getParentID(c.r))
	check(err)
	c.checkUser(parentKey)
	kind := "Pairing"
	handler := newDataHandler(c, kind, func() Ided { return &Pairing{} }, "")
	// we don't use the standard handlers for PUT and DELETE
	switch c.r.Method {
	case "PUT":
		// can't modify a pairing, only add/remove
		check(ErrUnsupported)
	case "DELETE":
		// validate the id
		id := getID(c.r)
		key, err := datastore.DecodeKey(id)
		check(err)
		handler.checkUser(key)
		// find the symetrical pairing so we can remove it too
		pairing := Pairing{}
		err = datastore.Get(c.c, key, &pairing)
		check(err)
		otherParent := pairing.Other
		query := datastore.NewQuery(kind).Ancestor(otherParent).Filter("Other=", parentKey).Filter("Description=", pairing.Description).KeysOnly()
		keys, err := query.GetAll(c.c, nil)
		check(err)
		// delete the entry given
		handler.delete(key)
		// delete the symetrical pairing(s)
		datastore.DeleteMulti(handler.c, keys)
		// flush the cache
		clearPairingCache(c, otherParent, key)
	default:
		// use the default handler for "GET" and "POST"
		handler.handleRequest(parentKey,
			func(method string, key *datastore.Key, item Ided) {
				switch method {
				case "POST":
					// after a "POST" to create a new item,
					//  add the symetrical entry for the other dish
					pairing := item.(*Pairing)
					// create the matching entry
					other := pairing.Other
					newPairKey := datastore.NewIncompleteKey(c.c, kind, other)
					pairing.Other = parentKey
					pairing.Id = ""
					newPairKey, err := datastore.Put(c.c, newPairKey, pairing)
					check(err)
					clearPairingCache(c, other, nil)
				}
			})
	}
}
Ejemplo n.º 3
0
// Revokes a user's permission to a door. Can only be done by the owner of the
// door or the user whose permission to revoke.
func deletePermission(
	r *http.Request, c appengine.Context, u *user.User) (*[]Permission, error) {
	uKey, err := ds.DecodeKey(r.FormValue("userKey"))
	if err != nil {
		return nil, ErrNoUserKey
	}
	var dKey *ds.Key
	dKey, err = ds.DecodeKey(r.FormValue("doorKey"))
	if err != nil {
		return nil, ErrNoDoorKey
	}

	// Verify caller is user in question or door owner.
	callerKey := ds.NewKey(c, "User", u.ID, 0, nil)
	if callerKey != uKey {
		cnt := 0
		if cnt, err = ds.NewQuery("Permission").
			Filter("userKey=", callerKey).
			Filter("doorKey=", dKey).
			Filter("level=", LevelOwner).
			Count(c); err != nil {
			return nil, err
		}
		if cnt == 0 {
			return nil, Err{"Only door owner can delete others' permission.",
				http.StatusForbidden}
		}
	}

	p := Permission{}
	k, err := ds.NewQuery("Permission").
		Filter("userKey=", uKey).
		Filter("doorKey=", dKey).
		Run(c).
		Next(&p)
	if err != nil {
		if err == ds.Done {
			err = Err{"Permission does not exist", http.StatusForbidden}
		}
		return nil, err
	}

	if err = ds.Delete(c, k); err != nil {
		return nil, err
	}

	return &[]Permission{}, nil
}
Ejemplo n.º 4
0
func ID(c appengine.Context, id string) *Team {
	k, err := datastore.DecodeKey(id)
	if err != nil {
		return nil
	}
	return Key(c, k)
}
Ejemplo n.º 5
0
// GetListHelper is a helper function that retrieves a list and it's
// items from the datastore. If a failure occured, false is returned
// and a response was returned to the request. This case should be
// terminal.
func GetListHelper(c appengine.Context, w http.ResponseWriter,
	r *http.Request, key string) (*List, bool) {

	// Decode the string version of the key.
	k, err := datastore.DecodeKey(key)
	if err != nil {
		gorca.LogAndUnexpected(c, w, r, err)
		return nil, false
	}

	// Get the list by key.
	var l List
	if err := datastore.Get(c, k, &l); err != nil {
		gorca.LogAndNotFound(c, w, r, err)
		return nil, false
	}

	// Get all of the items for the list.
	var li ItemsList
	q := datastore.NewQuery("Item").Ancestor(k).Order("Order")
	if _, err := q.GetAll(c, &li); err != nil {
		gorca.LogAndUnexpected(c, w, r, err)
		return nil, false
	}

	l.Items = li

	return &l, true
}
Ejemplo n.º 6
0
func Cardsetdetail(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	// get key
	encodedKey := r.FormValue("key")
	decodedKey, err := datastore.DecodeKey(encodedKey)
	if err != nil {
		err.Error()
	}

	// delete mode
	if r.FormValue("action") == "delete" {
		err = datastore.Delete(c, decodedKey)
		if err != nil {
			err.Error()
		}
		http.Redirect(w, r, "/cardsetlist", 303)
	}

	// get cardset
	cardset := new(Cardset)
	err = datastore.Get(c, decodedKey, cardset)
	if err != nil {
		err.Error()
	}

	// output html
	material := make(map[string]string)
	material["Name"] = cardset.Name
	material["Key"] = encodedKey
	Output(w, "page/cardset/cardsetdetail.html", material)
}
Ejemplo n.º 7
0
// LoadConference loads a conference from the datastore given its unique id.
func LoadConference(ctx appengine.Context, id string) (*Conference, error) {
	k, err := datastore.DecodeKey(id)
	if err != nil {
		return nil, fmt.Errorf("wrong key %q: %v", id, err)
	}
	return loadConference(ctx, k)
}
Ejemplo n.º 8
0
func captchaImageHandler(response http.ResponseWriter, request *http.Request) {
	context := appengine.NewContext(request)
	if request.FormValue(KEY_CAPTCHA_ID) == "" {
		http.Error(response, utils.MSG_WRONG_PARAMETERS, http.StatusBadRequest)
		return
	}

	key, err := datastore.DecodeKey(request.FormValue(KEY_CAPTCHA_ID))
	if err != nil {
		log.Fatal(err)
	}

	captcha := new(model.Captcha)
	err = datastore.Get(context, key, captcha)
	if err != nil {
		http.Error(response, ERR_CAPTCHA_NOT_FOUND, http.StatusNotFound)
		return
	}
	if captcha.Viewed {
		http.Error(response, ERR_CAPTCHA_VIEWED, http.StatusForbidden)
		return
	}
	captcha.Viewed = true
	key, err = datastore.Put(context, key, captcha)
	if err != nil {
		log.Fatal(err)
		return
	}

	response.Header().Set("content-type", "image/png")
	png.Encode(response, genCaptchaImage(captcha.Value))
}
Ejemplo n.º 9
0
// Marks a bid as placed. This is purely informational for the user.
func PlaceBid(c appengine.Context, bidId string) error {
	var key *datastore.Key
	if k, err := datastore.DecodeKey(bidId); err != nil {
		return err
	} else {
		key = k
	}

	f := func(c appengine.Context) error {
		var bid Bid
		if err := datastore.Get(c, key, bidCodec{&bid}); err != nil {
			return err
		}

		if bid.State != InQueue {
			c.Infof("Not placing bid %v : State=%v", key, bid.State)
			return nil
		}

		bid.State = Placed

		if _, err := datastore.Put(c, key, bidCodec{&bid}); err != nil {
			return err
		}
		return nil
	}

	return datastore.RunInTransaction(c, f, nil)
}
Ejemplo n.º 10
0
func deleteOneItem(rw http.ResponseWriter, req *http.Request, keyString string) {
	// To access datastore and to log
	c := appengine.NewContext(req)
	c.Infof("deleteOneItem()")

	// Result
	r := http.StatusNoContent
	defer func() {
		// Return status. WriteHeader() must be called before call to Write
		if r == http.StatusNoContent {
			rw.WriteHeader(http.StatusNoContent)
		} else {
			http.Error(rw, http.StatusText(r), r)
		}
	}()

	key, err := datastore.DecodeKey(keyString)
	if err != nil {
		c.Errorf("%s in decoding key string", err)
		r = http.StatusBadRequest
		return
	}

	// Delete the entity
	if err := datastore.Delete(c, key); err != nil {
		c.Errorf("%s, in deleting entity by key", err)
		r = http.StatusNotFound
		return
	}
	c.Infof("Key %s is deleted", keyString)
}
Ejemplo n.º 11
0
func DeliveryHandler(w http.ResponseWriter, r *http.Request) {
	keyId := bone.GetValue(r, "key")
	c := appengine.NewContext(r)
	key, err := datastore.DecodeKey(keyId)
	var dbRequest MainRequest
	if err = datastore.Get(c, key, &dbRequest); err != nil {
		c.Errorf("%s", err)
	}

	var status *postmates.Status

	if dbRequest.Pm_delivery_id == "" {
		status, err = postmates.RescueDelivery(c)
		if status != nil {
			dbRequest.Pm_delivery_id = status.ID
			if _, err := datastore.Put(c, key, &dbRequest); err != nil {
				c.Errorf("%s", err)
			}
		}
	} else {
		status, err = postmates.GetStatus(c, dbRequest.Pm_delivery_id)
		if err != nil {
			c.Errorf("%s", err)
		}
	}

	// send back important info
	err = json.NewEncoder(w).Encode(&status)
	if err != nil {
		c.Errorf("%s", err)
	}
}
Ejemplo n.º 12
0
//TimeOverrideSubmit handles saving of time overrides into Datastore.
func TimeOverrideSubmit(c util.Context) (err error) {
	date, err := time.Parse(dateFormat, c.R.FormValue("date"))
	if err != nil {
		return
	}

	on, err := time.Parse(timeFormat, c.R.FormValue("on"))
	if err != nil {
		return
	}

	off, err := time.Parse(timeFormat, c.R.FormValue("off"))
	if err != nil {
		return
	}
	tc := timeConfig.New(util.NormalizeDate(date), util.NormalizeTime(on), util.NormalizeTime(off))
	var k *datastore.Key
	if _, ok := c.Vars["id"]; ok {
		k, err = datastore.DecodeKey(c.Vars["id"])
		if err != nil {
			return
		}
	} else {
		k = nil
	}
	tc.SetKey(k)
	err = tc.Save(c)
	if err != nil {
		return
	}
	http.Redirect(c.W, c.R, "/admin/config", 303)
	return
}
Ejemplo n.º 13
0
// handler to switch which library the user is looking at
func switchHandler(c *context) {
	// verify the library key
	desiredKey, err := datastore.DecodeKey(getID(c.r))
	check(err)
	if desiredKey.Kind() != "Library" {
		check(ErrUnknownItem)
	}
	// start by getting the user's own library
	lid, l, _ := getOwnLibrary(c.c, c.u)
	if !lid.Equal(desiredKey) {
		// user want's to see someone else's library, check if they have
		// permission
		perm := getLibPerm(c.c, c.uid, desiredKey)
		if perm == nil {
			check(ErrPermissionDenied)
			return
		}
	} else {
		// we use nil to indicate the user wants their own library
		desiredKey = nil
	}
	// we verified that the desiredKey is a library the user has permission to access
	//  save their preference
	if desiredKey != nil {
		l.UserPreferredLibrary = desiredKey.Encode()
	} else {
		l.UserPreferredLibrary = ""
	}
	_, err = datastore.Put(c.c, lid, l)
	check(err)
	memcache.Gob.Set(c.c, &memcache.Item{Key: lid.Encode(), Object: l})
	// redirect the user back to the index to use the updated library preference
	indexHandler(c)
}
Ejemplo n.º 14
0
func batchDestroy(c appengine.Context, w http.ResponseWriter, r *http.Request) {
	keyStr := []string{}
	z, err := gzip.NewReader(r.Body)
	maybePanic(err)
	d := json.NewDecoder(z)
	maybePanic(d.Decode(&keyStr))
	c.Infof("Got %v keys to destroy", len(keyStr))

	keys := []*datastore.Key{}
	for _, k := range keyStr {
		key, err := datastore.DecodeKey(k)
		if err != nil {
			c.Errorf("Error decoding key: %v: %v", k, err)
			http.Error(w, err.Error(), 500)
			return
		}
		keys = append(keys, key)
	}

	err = datastore.DeleteMulti(c, keys)
	if err != nil {
		c.Infof("Error deleting things: %v", err)
		http.Error(w, err.Error(), 500)
		return
	}

	w.WriteHeader(204)
}
Ejemplo n.º 15
0
func IsSess(w http.ResponseWriter, r *http.Request, c appengine.Context) (Sess, bool) {
	var s Sess
	now := time.Now().Add(time.Duration(GMTADJ) * time.Second)
	if ck, err := r.Cookie("ebfmex-pub-sessid-ua"); err == nil {
		key, _ := datastore.DecodeKey(ck.Value)
		if err := datastore.Get(c, key, &s); err != nil {
			// no hay sesión
			//http.Error(w, err.Error(), http.StatusInternalServerError)
		} else {
			/* se verifica el control de sesion */
			if cr, err := r.Cookie("ebfmex-pub-sesscontrol-ua"); err == nil {
				if s.Md5 != cr.Value {
					// Md5 no coincide, intenta entrar con otra cookie
					return s, false
				} else if now.After(s.Expiration) {
					// Sesión expirada
					return s, false
				}
				// OK
				// Hay sesión
				return s, true
			}
		}
	}
	return s, false
}
Ejemplo n.º 16
0
func gameGet(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	id := r.FormValue("Id")
	gameKey, err := datastore.DecodeKey(id)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	q := datastore.NewQuery("move").Ancestor(gameKey).Order("-Timestamp").Limit(1)
	moves := make([]Move, 0, 1)
	if _, err := q.GetAll(c, &moves); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	response := GameGetResponse{
		Type: moves[0].Type,
		Data: string(moves[0].Data),
	}

	data, err := json.Marshal(response)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Write(data)
}
Ejemplo n.º 17
0
func appendToEntry(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	args := r.URL.Query()
	rawKey := args.Get("key")
	key, err := datastore.DecodeKey(rawKey)

	if err != nil {
		c.Errorf("Failed to parse decode key '%v': %v", rawKey, err)
		return
	}

	var e DiaryEntry
	err = datastore.Get(c, key, &e)
	if err != nil {
		c.Errorf("failed to fetch entry: %v", err)
		return
	}

	var doc bytes.Buffer

	entryAppendTemplate.Execute(&doc, EntryContent{
		Date:    e.Date,
		Content: strings.Replace(string(e.Content), "\n", "<br>\n\n", -1),
		Key:     rawKey,
	})

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	baseTemplate.Execute(w, BodyContent{
		Body:  doc.String(),
		Title: e.Date.Format("Monday, 2. Jan"),
	})

}
Ejemplo n.º 18
0
func saveParagraph(w http.ResponseWriter, r *http.Request) {
	if !checkUser(w, r) {
		return
	}
	ctx := appengine.NewContext(r)
	dec := json.NewDecoder(r.Body)
	var p Paragraph
	if err := dec.Decode(&p); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	var err error
	var key *datastore.Key
	keyString := r.FormValue("key")
	if keyString != "" {
		key, err = datastore.DecodeKey(keyString)
	} else {
		key = datastore.NewIncompleteKey(ctx, "Paragraph", nil)
	}
	if err == nil {
		key, err = datastore.Put(ctx, key, &p)
	}
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-type", "text/plain; charset=utf-8")
	fmt.Fprintf(w, "%s", key.Encode())
}
Ejemplo n.º 19
0
/**
 * データストアからゲームを削除する
 * 削除を命令したユーザとゲームの所有者が一致していることを事前に確認すること
 * この関数内ではチェックを行わない
 * @param {string} encodedGameKey エンコード済みのゲームキー
 */
func (this *Model) deleteGame(encodedGameKey string) {
	gameKey, err := datastore.DecodeKey(encodedGameKey)
	check(this.c, err)

	err = datastore.Delete(this.c, gameKey)
	check(this.c, err)
}
Ejemplo n.º 20
0
func getAdminEditPage(c appengine.Context, path string) string {

	u := user.Current(c)
	if u == nil || !user.IsAdmin(c) {
		url, _ := user.LoginURL(c, "/admin/edit")
		return fmt.Sprintf(`<a href="%s">Sign in or register</a>`, url)
	}

	//homepage, _ := template.New("template").Funcs(template.FuncMap{"DateToStringAdmin": DateToStringAdmin}).ParseFiles("site/editpodcast.html")

	homepage := template.Must(
		template.
			New("editpodcast.html").
			Funcs(template.FuncMap{"DateToStringAdmin": DateToStringAdmin}).
			ParseFiles("site/editpodcast.html"))

	pA := strings.Split(path, `/`)
	keyString := pA[3]
	key, _ := datastore.DecodeKey(keyString)

	var p Podcast
	datastore.Get(c, key, &p)

	p.Key = key.Encode()
	//p.PubDateFormatted = getValidDate(time.SecondsToUTC(int64(p.PubDate) / 1000000))

	html := bytes.NewBufferString("")
	homepage.Execute(html, p)

	return html.String()

}
Ejemplo n.º 21
0
///////////////// For Story Api Method /////////////////
func GetStories(params martini.Params, w http.ResponseWriter, r *http.Request) string {
	w.Header().Set("Content-Type", "application/json")

	if r.Method != "GET" {
		return "error: illegal access."
	}

	c := appengine.NewContext(r)

	keyStr := params["key"]
	message := ""
	if keyStr != "" {
		// get a story to show.
		key, err := datastore.DecodeKey(keyStr)
		if err != nil {
			return "error: decode Key failed: " + keyStr
		}

		var s Story
		if err = datastore.Get(c, key, &s); err != nil {
			return "error: get datastore failed."
		}

		message += s.Id
		message += ","
		message += s.Title
		message += ","
		message += s.Desc
		message += ","
		message += strconv.FormatFloat(s.Point, 'f', -1, 64)
	} else {
		// fetch all story to show.
		q := datastore.NewQuery("story").Order("-Id").Limit(10)
		var stories []*Story
		_, err := q.GetAll(c, &stories)
		if err != nil {
			return "error: queryall datastore failed."
		}

		items := len(stories)
		if items > 0 {
			message = "there have items:" + strconv.FormatInt(int64(items), 10) + "\n"
		} else {
			message = "null"
		}

		for _, s := range stories {
			message += s.Id
			message += ","
			message += s.Title
			message += ","
			message += s.Desc
			message += ","
			message += strconv.FormatFloat(s.Point, 'f', -1, 64)
			message += "\n"
		}
	}

	return message
}
Ejemplo n.º 22
0
// create a new context to wrap data
//  creates a new library if user has none
//  sets the context if user wants to view a library othe than their own
//  caches library in memcache
func newContext(w http.ResponseWriter, r *http.Request) *context {
	c := appengine.NewContext(r)
	u := user.Current(c)
	uid := u.ID
	if len(uid) == 0 {
		uid = u.Email
	}
	lid, l, init := getOwnLibrary(c, u)
	// check if the user wants to use a different library
	upl, err := datastore.DecodeKey(l.UserPreferredLibrary)
	if err != nil {
		//fmt.Fprintf(w, "No UPL %v", l.UserPreferredLibrary)
		upl = nil
	}
	readOnly := false
	// use an alternate library if the user wants to
	if upl != nil && !lid.Equal(upl) {
		// check for permision
		perm := getLibPerm(c, uid, upl)
		//fmt.Fprintf(w, "Try UPL %v, %v\n", l.UserPreferredLibrary, perm)
		var otherlib *Library = nil
		if perm != nil {
			otherlib = &Library{}
			_, err = memcache.Gob.Get(c, upl.Encode(), otherlib)
			//fmt.Fprintf(w, "cache %v %v\n", err, otherlib)
			if err != nil {
				err = datastore.Get(c, upl, otherlib)
				//fmt.Fprintf(w, "ds %v %v\n", err, otherlib)
			}
			if err == nil {
				lid = upl
				l = otherlib
				// save the library back to the cache
				memcache.Gob.Set(c, &memcache.Item{Key: upl.Encode(), Object: otherlib})
			}
		}
		if l != otherlib {
			// user can't get to this library, update thieir record
			//  so we dont fail all the time
			l.UserPreferredLibrary = ""
			datastore.Put(c, lid, l)
			memcache.Gob.Set(c, &memcache.Item{Key: lid.Encode(), Object: l})
		} else {
			readOnly = perm.ReadOnly
		}
	}
	// create the context with all of the data we gathered
	ctxt := &context{w, r, c, u, uid, l, lid, readOnly}
	// if this is a new library, populate it with data
	if init {
		file, err := os.Open("mealplanner/base.json")
		if err != nil {
			file, err = os.Open("base.json")
		}
		if err == nil {
			importFile(ctxt, file)
		}
	}
	return ctxt
}
Ejemplo n.º 23
0
// GET http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM
//
func (u ProfileApi) read(r *restful.Request, w *restful.Response) {
	c := appengine.NewContext(r.Request)

	// Decode the request parameter to determine the key for the entity.
	k, err := datastore.DecodeKey(r.PathParameter("profile-id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Retrieve the entity from the datastore.
	p := Profile{}
	if err := datastore.Get(c, k, &p); err != nil {
		if err.Error() == "datastore: no such entity" {
			http.Error(w, err.Error(), http.StatusNotFound)
		} else {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		return
	}

	// Check we own the profile before allowing them to view it.
	// Optionally, return a 404 instead to help prevent guessing ids.
	// TODO: Allow admins access.
	if p.Email != user.Current(c).String() {
		http.Error(w, "You do not have access to this resource", http.StatusForbidden)
		return
	}

	w.WriteEntity(p)
}
Ejemplo n.º 24
0
// Get details about a visualization
func getVisualization(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	vars := mux.Vars(r)

	key, err := datastore.DecodeKey(vars["key"])
	if err != nil {
		common.Serve404(w)
		return
	}

	var e model.Visualization
	err = datastore.Get(c, key, &e)
	if err != nil {
		if err == datastore.ErrNoSuchEntity {
			common.Serve404(w)
			return
		}
		common.ServeError(c, w, err)
		return
	}

	res := map[string]interface{}{
		"Owner": key.Parent().StringID(),
		"Title": e.Title,
		"Date":  e.Date,
		"Files": e.Files,
	}

	common.WriteJson(c, w, res)
}
Ejemplo n.º 25
0
// getList fetches the list with the id given in the url and encodes it in
// JSON format into the http response.
func getList(w io.Writer, r *http.Request) error {
	c := appengine.NewContext(r)

	// Get the list id from the URL.
	id := mux.Vars(r)["list"]

	// Decode the obtained id into a datastore key.
	key, err := datastore.DecodeKey(id)
	if err != nil {
		return appErrorf(http.StatusBadRequest, "invalid list id")
	}

	// Fetch the list from the datastore.
	list := &List{}
	err = datastore.Get(c, key, list)
	if err == datastore.ErrNoSuchEntity {
		return appErrorf(http.StatusNotFound, "list not found")
	}
	if err != nil {
		return fmt.Errorf("fetch list: %v", err)
	}

	// Set the ID field with the id from the request url and encode the list.
	list.ID = id
	return json.NewEncoder(w).Encode(&list)
}
Ejemplo n.º 26
0
func (db *AppEngineDB) SaveGeneralData(d *GeneralData) error {
	if d.UserID == "" {
		return errors.New("model: invalid UserID")
	}

	var (
		key *datastore.Key
		err error
	)

	if d.Key == "" {
		key = datastore.NewIncompleteKey(db.ctx, "GeneralData", nil)
	} else {
		key, err = datastore.DecodeKey(d.Key)
		if err != nil {
			return err
		}
	}

	key, err = datastore.Put(db.ctx, key, d)
	if err != nil {
		return err
	}

	d.Key = key.Encode()
	return nil
}
Ejemplo n.º 27
0
func DeleteInvestment(c appengine.Context, key string) error {
	k, err := datastore.DecodeKey(key)
	if err != nil {
		return err
	}
	return datastore.Delete(c, k)
}
Ejemplo n.º 28
0
func (db *AppEngineDB) SaveUsages(u []Usage) error {
	n := len(u)
	keys := make([]*datastore.Key, n, n)
	for i, v := range u {
		if v.UserID != "" {
			if v.Key != "" {
				key, err := datastore.DecodeKey(v.Key)
				if err == nil {
					keys[i] = key
				}
			} else {
				keys[i] = datastore.NewIncompleteKey(db.ctx, "Usage", nil)
			}
		}
	}

	keys, err := datastore.PutMulti(db.ctx, keys, u)
	if err != nil {
		return err
	}

	for i, v := range keys {
		u[i].Key = v.Encode()
	}
	return nil
}
Ejemplo n.º 29
0
//Presentation handles showing page with details about a presentation.
func Presentation(c util.Context) (err error) {
	pk, err := datastore.DecodeKey(c.Vars["id"])
	if err != nil {
		return
	}

	p, err := presentation.GetByKey(pk, c)
	if err != nil {
		return
	}
	as, err := action.GetFor(p, c)
	if err != nil {
		return
	}

	a := prepareActions(as)

	desc := blackfriday.MarkdownCommon(p.Description)

	acts, err := activation.GetForPresentation(pk, c)
	if err != nil {
		return
	}

	util.RenderLayout("presentation.html", "Info o prezentácií", struct {
		P           *presentation.Presentation
		A           map[string][]time.Time
		Desc        template.HTML
		ZeroTime    time.Time
		Domain      string
		Activations []*activation.Activation
		Tz          *time.Location
	}{p, a, template.HTML(desc), time.Date(0001, 01, 01, 00, 00, 00, 00, utc), appengine.DefaultVersionHostname(c), acts, util.Tz}, c, "/static/js/underscore-min.js", "/static/js/presentation.js")
	return
}
Ejemplo n.º 30
0
Archivo: anif.go Proyecto: hamax/avy
// Get a file that is part of a visualization
func getVisualizationFile(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	vars := mux.Vars(r)

	// Get visualization object
	key, err := datastore.DecodeKey(vars["key"])
	if err != nil {
		common.Serve404(w)
		return
	}

	var e model.Visualization
	err = datastore.Get(c, key, &e)
	if err != nil {
		if err == datastore.ErrNoSuchEntity {
			common.Serve404(w)
			return
		}
		common.ServeError(c, w, err)
		return
	}

	// Find blob key
	filename := vars["filename"]
	for i := range e.Files {
		if e.Files[i].Filename == filename {
			blobstore.Send(w, appengine.BlobKey(e.Files[i].BlobKey))
			return
		}
	}

	common.Serve404(w)
}