Esempio n. 1
0
// addIndexToZip generates an index.html file for the given Overlay and adds
// it to the provided zip file.
func addIndexToZip(c appengine.Context, z *zip.Writer, oKey *datastore.Key, o *Overlay) error {
	w, err := z.Create(fmt.Sprintf("%s/index.html", oKey.Encode()))
	if err != nil {
		return err
	}
	return zipTemplate.Execute(w, o)
}
Esempio n. 2
0
func redirectToBid(bidKey *datastore.Key, w http.ResponseWriter, r *http.Request) {
	bidUrl, _ := url.Parse("/bid/" + bidKey.Encode())
	bidUrl = r.URL.ResolveReference(bidUrl)
	w.Header().Set("Location", bidUrl.RequestURI())
	w.Header().Set("X-Bid-Key", bidKey.Encode())
	w.WriteHeader(http.StatusSeeOther)
}
Esempio n. 3
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())
}
Esempio n. 4
0
func (g *gapDatabase) getKeyString(key *datastore.Key) string {
	if tmp := key.IntID(); tmp != 0 {
		return strconv.FormatInt(tmp, 10)
	} else {
		return key.StringID()
	}
}
Esempio n. 5
0
// Valid only if k has no descendents of its own kind.
func exists(c appengine.Context, k *datastore.Key) (bool, error) {
	count, err := datastore.NewQuery(k.Kind()).KeysOnly().Ancestor(k).Count(c)
	if err != nil {
		return false, err
	}
	return (count != 0), err
}
Esempio n. 6
0
func updateFeed(c appengine.Context, cl *http.Client, fk *datastore.Key) error {
	resp, err := cl.Get(fk.StringID())
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	decoder := xml.NewDecoder(resp.Body)
	var rfeed RSS
	err = datastore.Get(c, fk, &rfeed)
	if err != nil {
		return err
	}
	if rfeed.IsAtom {
		var afeed Atom
		err = decoder.Decode(&afeed)
		if err != nil {
			return err
		}
		return afeed.update(c, fk)
	} else {
		err = decoder.Decode(&rfeed)
		if err != nil {
			return err
		}
		return rfeed.update(c, fk)
	}
	panic("unreachable")
}
Esempio n. 7
0
// Transactions in phase FINISHED will cause the price to be credited on the seller's
// account, and the fee to be deducted.
// All other phases will lead to price and fee being reimbursed to the buyer.
// Returns ErrTransactionTooYoung if the transaction has not passed its timout at the
// time of the call.
// Returns ErrTransactionAlreadyRetired if the transaction has already been retired at
// the time of the call.
func RetireTransaction(c appengine.Context, key *datastore.Key) error {
	f := func(c appengine.Context) error {
		now := time.Now()
		dao := NewGaeAccountingDao(c, true)
		var tx Transaction
		if err := datastore.Get(c, key, txCodec{&tx}); err != nil {
			return err
		}

		if err := tx.Retire(dao, key.Encode(), now); err == ErrTooYoung {
			return ErrTransactionTooYoung
		} else if err == ErrAlreadyRetired {
			return ErrTransactionAlreadyRetired
		} else if err != nil {
			return err
		}

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

		return dao.Flush()
	}

	return datastore.RunInTransaction(c, f, &datastore.TransactionOptions{XG: true})
}
Esempio n. 8
0
func SetSess(w http.ResponseWriter, c appengine.Context, key *datastore.Key, email string, name string) (string, *datastore.Key, error) {
	now := time.Now().Add(time.Duration(GMTADJ) * time.Second)
	h := md5.New()
	io.WriteString(h, key.Encode())
	io.WriteString(h, fmt.Sprintf("%s", now))
	md5 := fmt.Sprintf("%x", h.Sum(nil))
	ex := now.AddDate(0, 0, Expiracion)
	s := Sess{
		Md5:        md5,
		Id:         key.Encode(),
		User:       email,
		Name:       name,
		Expiration: ex,
	}
	cKey, err := datastore.Put(c, datastore.NewKey(c, "Sess", email, 0, nil), &s)
	if err != nil {
		return "", nil, err
	}
	// Se crean 2 cookies, una con el key de sesión otra con el número random llave
	//csc := http.Cookie{ Name: "ebfmex-pub-sesscontrol-ua", Value: md5, Expires: ex, Path: "/" }
	//http.SetCookie(w, &csc)
	//csc = http.Cookie{ Name: "ebfmex-pub-sessid-ua", Value: cKey.Encode(), Expires: ex, Path: "/" }
	//http.SetCookie(w, &csc)
	//w.Header().Add("Set-Cookie", fmt.Sprintf("ebfmex-pub-sesscontrol-ua=%s; expires=%s; path=/;", md5, ex.Format("Mon Jan 2 15:04:05")))
	w.Header().Add("Set-Cookie", fmt.Sprintf("ebfmex-pub-sesscontrol-ua=%v; expires=%v; path=/;", md5, ex.Format(time.ANSIC)))
	//w.Header().Add("Set-Cookie", fmt.Sprintf("ebfmex-pub-sessid-ua=%s; expires=%s; path=/;", cKey.Encode(), ex.Format("Mon Jan 2 15:04:05")))
	w.Header().Add("Set-Cookie", fmt.Sprintf("ebfmex-pub-sessid-ua=%v; expires=%v; path=/;", cKey.Encode(), ex.Format(time.ANSIC)))
	return md5, cKey, err
}
Esempio n. 9
0
File: ds.go Progetto: gaego/ds
// Get given a *datastore.Key returns a single entity from the store
func Get(c appengine.Context, key *datastore.Key, dst interface{}) (err error) {
	sc := getConfig(key.Kind())
	needMemory := true
	needMemcache := true
	if sc.Memory {
		err = memory.Get(c, key, dst)
		if err == nil {
			needMemory = false
			goto Complete
		}
	}
	if sc.Memcache {
		err = memcache.Get(c, key, dst)
		if err == nil {
			needMemcache = false
			goto Complete
		}
	}
	if sc.Datastore {
		err = dsds.Get(c, key, dst)
		if err == nil {
			goto Complete
		}
	}
	return
Complete:
	// Save the entity to any caches that it should be saved to.
	if sc.Memcache && needMemcache {
		_, _ = memcache.Put(c, key, dst)
	}
	if sc.Memory && needMemory {
		_, _ = memory.Put(c, key, dst)
	}
	return
}
Esempio n. 10
0
// Generic get by function
func GetByKey(m Model, key *datastore.Key) string {
	if err := datastore.Get(c, key, m); err != nil {
		session.AddFlash("An error occured while loading: " + err.Error())
		return ""
	}
	return key.Encode()
}
Esempio n. 11
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
}
Esempio n. 12
0
// This will reimburse the bid's price and fee to the buyer.
func RetireBid(c appengine.Context, key *datastore.Key) error {
	f := func(c appengine.Context) error {
		now := time.Now()
		dao := NewGaeAccountingDao(c, true)
		var bid Bid
		if err := datastore.Get(c, key, bidCodec{&bid}); err != nil {
			return err
		}

		if bid.State == Matched {
			c.Infof("Not retiring matched bid %v", key)
			return nil
		}

		if err := bid.Retire(dao, key.Encode(), now); err != nil {
			return err
		}

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

		return dao.Flush()
	}

	if err := datastore.RunInTransaction(c, f, &datastore.TransactionOptions{XG: true}); err != nil {
		return err
	}

	return nil
}
Esempio n. 13
0
func ajaxEncode(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	c := appengine.NewContext(r)
	var err error

	kind := trimmedFormValue(r, "kind")
	stringID := trimmedFormValue(r, "stringid")
	intIDstr := trimmedFormValue(r, "intid")
	appID := trimmedFormValue(r, "appid")
	namespace := trimmedFormValue(r, "namespace")

	// Parent (optional)
	kind2 := trimmedFormValue(r, "kind2")
	stringID2 := trimmedFormValue(r, "stringid2")
	intIDstr2 := trimmedFormValue(r, "intid2")

	// Grand-parent (optional)
	kind3 := trimmedFormValue(r, "kind3")
	stringID3 := trimmedFormValue(r, "stringid3")
	intIDstr3 := trimmedFormValue(r, "intid3")

	c.Infof("Encoding %v\n", []string{
		appID, namespace,
		kind, stringID, intIDstr,
		kind2, stringID2, intIDstr2,
		kind3, stringID3, intIDstr3,
	})

	var key, parent, grandparent *datastore.Key

	if kind2 != "" {
		if kind3 != "" {
			grandparent, err = CreateKey(c, appID, namespace, kind3, stringID3, intID64(intIDstr3), nil)
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}
		}
		parent, err = CreateKey(c, appID, namespace, kind2, stringID2, intID64(intIDstr2), grandparent)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
	}

	key, err = CreateKey(c, appID, namespace, kind, stringID, intID64(intIDstr), parent)
	if err != nil {
		c.Errorf("Failed: %v\n", err.Error())
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	//fmt.Fprint(w, keyString)
	w.Header().Set("Content-Type", "application/json")
	keyString := key.Encode()
	fmt.Fprint(w, Response{
		"keystring": keyString,
	})
	c.Infof("Encoded %v\n", keyString)
}
Esempio n. 14
0
// SetDatastoreKey sets the datastore Key and updates the records ID if needed.
// Advanced use only.
func (r *Record) SetDatastoreKey(key *datastore.Key) *Record {

	if key == nil {

		r.setID(NoIDValue)
		r.datastoreKey = nil

	} else {

		// does the key have an ID?
		if key.IntID() > 0 {

			// set the ID
			r.setID(key.IntID())

		}

		// set the key
		r.datastoreKey = key

	}

	// chain
	return r

}
Esempio n. 15
0
func cacheSetFeed(c appengine.Context, k *datastore.Key, f FeedInfo) error {
	id := k.StringID()
	if len(id) > mcacheKeyMax { // silently don't set the value
		c.Infof("Not caching feed with a big key: %s", id)
		return nil
	}
	return memcache.Gob.Set(c, &memcache.Item{Key: k.StringID(), Object: f})
}
Esempio n. 16
0
func indexOfKey(keys []*datastore.Key, key *datastore.Key) int {
	for i := range keys {
		if keys[i].Encode() == key.Encode() {
			return i
		}
	}
	return -1
}
Esempio n. 17
0
// clear the pairing cache for the specified dish/pair that is changed
func clearPairingCache(c *context, dishKey *datastore.Key, pairingKey *datastore.Key) {
	url := c.lid.Encode() + "/dish/" + dishKey.Encode() + "/pairing/"
	memcache.Delete(c.c, url)
	if pairingKey != nil {
		url += pairingKey.Encode()
		memcache.Delete(c.c, url)
	}
}
Esempio n. 18
0
func cacheGetFeed(c appengine.Context, k *datastore.Key) (FeedInfo, error) {
	id := k.StringID()
	if len(id) > mcacheKeyMax {
		return FeedInfo{}, ErrKeyTooBig
	}
	var f FeedInfo
	_, err := memcache.Gob.Get(c, id, &f)
	return f, err
}
Esempio n. 19
0
func (d *TvRecordDriver) Delete(key *ds.Key) error {
	if err := d.Driver.Delete(key); err != nil {
		d.Logger.Info("Deleted the record: (%s)", key.String()[:8])
		return err
	} else {
		d.Logger.Info("Deleted the record: (%s)", key.String()[:8])
		return nil
	}
}
Esempio n. 20
0
// returns true iff the key is part of the current library
func (self *context) isInLibrary(key *datastore.Key) bool {
	// check if the library is an ancestor of this key
	for key != nil {
		if self.lid.Equal(key) {
			return true
		}
		key = key.Parent()
	}
	return false
}
Esempio n. 21
0
func couchit(c appengine.Context, k *datastore.Key, v url.Values) error {
	vals := url.Values{
		"key": []string{k.Encode()},
	}
	for k, v := range v {
		vals[k] = v
	}
	_, err := taskqueue.Add(c, taskqueue.NewPOSTTask("/couchit", vals),
		"couchit")
	return err
}
Esempio n. 22
0
func newFolderRef(userID UserID, key *datastore.Key) FolderRef {
	ref := FolderRef{
		UserID: userID,
	}

	if key != nil {
		ref.FolderID = formatId("folder", key.IntID())
	}

	return ref
}
Esempio n. 23
0
func TestDatastoreKeyForPersistedRecord(t *testing.T) {

	people := CreateTestModelWithPropertyType("modeltwo")
	person := people.New().setID(123)

	var key *datastore.Key = person.DatastoreKey()

	assertEqual(t, int64(123), key.IntID())
	assertEqual(t, people.RecordType(), key.Kind())

}
Esempio n. 24
0
func TestDatastoreKeyForUnpersistedRecord(t *testing.T) {

	people := CreateTestModel()
	person := people.New()

	var key *datastore.Key = person.DatastoreKey()

	assertEqual(t, int64(0), key.IntID())
	assertEqual(t, people.RecordType(), key.Kind())

}
Esempio n. 25
0
// break up the text into words and add/remove keywords  for the dish
func updateDishKeywords(c *context, key *datastore.Key, dish *Dish) {
	words := make(map[string]bool)
	addWords(dish.Name, words)
	addWords(dish.Source, words)
	addWords(dish.Text, words)
	addTags(c.c, key, words)
	if updateKeywords(c.c, key, words) {
		// if we made changes, we need to clear the cache
		cacheKey := c.lid.Encode() + "/dish/" + key.Encode() + "/keywords/"
		memcache.Delete(c.c, cacheKey)
	}
}
Esempio n. 26
0
// default data handler for "GET" to fetch one item
// returns the fetched item
func (self *dataHandler) get(key *datastore.Key) Ided {
	// create the object
	object := self.factory()
	// fetch it from the data sstore
	err := datastore.Get(self.c, key, object)
	check(err)
	// ensure the item has the proper Id in the JSON to the client
	object.SetID(key.Encode())
	// send the object to the client and cache it
	self.sendJSON(object)
	return object
}
Esempio n. 27
0
// cacheDevListForAccKey puts the specified Device list into the cache (memcache).
func cacheDevListForAccKey(c appengine.Context, accKey *datastore.Key, devices []*ds.Device) {
	mk := prefixDevListForAccKey + strconv.FormatInt(accKey.IntID(), 10)

	data, err := json.Marshal(devices) // This can't really fail
	if err != nil {
		c.Errorf("Failed to encode device list to JSON: %v", err)
	}

	if err = memcache.Set(c, &memcache.Item{Key: mk, Value: data}); err != nil {
		c.Warningf("Failed to set %s in memcache: %v", mk, err)
	}
}
Esempio n. 28
0
/*
	Método para borrar todas las palabras de SearchData
*/
func DelOfertaSearchData(c appengine.Context, key *datastore.Key) error {
	q := datastore.NewQuery("SearchData").Filter("Sid =", key.Encode()).KeysOnly()
	n, _ := q.Count(c)
	sd := make([]*datastore.Key, 0, n)
	if _, err := q.GetAll(c, &sd); err != nil {
		return nil
	}
	if err := datastore.DeleteMulti(c, sd); err != nil {
		return err
	}
	return nil
}
Esempio n. 29
0
// update the ingredient's keywords
func updateIngredientKeywords(c *context, key *datastore.Key,
	ing *Ingredient) {
	words := make(map[string]bool)
	addWords(ing.Name, words)
	addWords(ing.Category, words)
	addTags(c.c, key, words)
	if updateKeywords(c.c, key, words) {
		// if we made changes, we need to clear the cache
		cacheKey := c.lid.Encode() + "/ingredient/" + key.Encode() + "/keywords/"
		memcache.Delete(c.c, cacheKey)
	}
}
Esempio n. 30
0
func postBlog(c appengine.Context, b *blogEntry) error {
	k := datastore.NewKey(c, "Blog", "", 0, nil)
	var (
		k2  *datastore.Key
		err error
	)
	if k2, err = datastore.Put(c, k, b); err != nil {
		println("")
		return err
	}
	b.Id = k2.IntID()
	return nil
}