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 }
// 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 }
// 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() }
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) }
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 }
// 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) }
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()) }
// 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}) }
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) }
// 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) } }
func indexOfKey(keys []*datastore.Key, key *datastore.Key) int { for i := range keys { if keys[i].Encode() == key.Encode() { return i } } return -1 }
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 }
// 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) } }
// 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 }
/* 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 }
// 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) } }
// default data handler for "PUT" to update one item // returns the updated item func (self *dataHandler) update(key *datastore.Key) Ided { // create object to receive data object := self.factory() // read the JSON readJSON(self.r, object) // don't let user change the ID object.SetID(key.Encode()) // save to the datastore _, err := datastore.Put(self.c, key, object) check(err) // send JSON back to the client and cache it self.sendJSON(object) return object }
// default data handler for "DELETE" to remove one itme func (self *dataHandler) delete(key *datastore.Key) { // delete the item err := datastore.Delete(self.c, key) check(err) // remove this item from the cache cacheKey := self.lid.Encode() + self.r.URL.Path memcache.Delete(self.c, cacheKey) // remove the parent from the cache too // strip off the key from the URL parentURL := cacheKey[:len(cacheKey)-len(key.Encode())] memcache.Delete(self.c, parentURL) // also without the / memcache.Delete(self.c, parentURL[:len(parentURL)-1]) }
func updateUnique(c appengine.Context, k *datastore.Key, uuid string) error { vals := url.Values{ "key": []string{k.Encode()}, } header := http.Header{ "Content-Type": []string{"application/x-www-form-urlencoded"}, uuidHeader: []string{uuid}, } _, err := taskqueue.Add(c, &taskqueue.Task{ Path: "/updateUnique", Payload: []byte(vals.Encode()), Header: header, }, "updateunique") return err }
// get a permision item for the specified library // checks memcache before datastore func getLibPerm(c appengine.Context, uid string, libKey *datastore.Key) *Perm { accessCacheKey := uid + "Perm" + libKey.Encode() perm := &Perm{} _, err := memcache.Gob.Get(c, accessCacheKey, perm) if err != nil { query := datastore.NewQuery("Perm").Ancestor(libKey).Filter("UserId =", uid).Limit(1) iter := query.Run(c) if _, err = iter.Next(perm); err == nil { // save the permision back to the cache memcache.Gob.Set(c, &memcache.Item{Key: accessCacheKey, Object: perm}) } else { return nil } } return perm }
func (db FlightDB) KeyToFlight(key *datastore.Key) (*f.Flight, error) { ff := f.FrozenFlight{} if err := datastore.Get(db.C, key, &ff); err != nil { return nil, err } flight, err := ff.Thaw() if err != nil { return nil, err } flight.EnterUTC, flight.LeaveUTC = flight.Track.TimesInBox(sfo.KBoxSnarfingCatchment) flight.SetDatastoreKey(key.Encode()) return flight, nil }
// Transactional function to enqueue a bid, while keeping accounts in balance func EnqueueBid(c appengine.Context, bid *Bid) (*datastore.Key, error) { var bidKey *datastore.Key f := func(c appengine.Context) error { dao := NewGaeAccountingDao(c, true) if err := bid.CheckBalance(dao); err != nil { return err } //parentKey := ArticleKey(c, bid.Article) //parentKey := AccountKey(c, bid.Participant) if key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Bid", nil), bidCodec{bid}); err != nil { return err } else { bidKey = key } if err := bid.Book(dao, bidKey.Encode()); err != nil { return err } if err := addRetireBidTask(c, bidKey.Encode(), bid); err != nil { return err } // Encode the new bid as a hotBid and put it into a pull queue hot := newHotBid(bidKey, bid) if bytes, err := json.Marshal(*hot); err != nil { return err } else { var task taskqueue.Task task.Method = "PULL" task.Payload = bytes task.Tag = string(bid.Article) taskqueue.Add(c, &task, "hotbids") } return dao.Flush() } if err := datastore.RunInTransaction(c, f, &datastore.TransactionOptions{XG: true}); err != nil { return nil, err } return bidKey, nil }
func postStats(c appengine.Context, k *datastore.Key) error { st := Stats{} err := datastore.Get(c, k, &st) if err != nil { c.Infof("Failed to load %v: %v, trying alt data", k, err) err = loadOldStyle(c, k, &st) if err != nil { return err } } if st.Data == nil || len(st.Data) < 2 { c.Infof("No content found, ignoring %v.", k.Encode()) return nil } if err := st.uncompress(); err != nil { c.Infof("Decompression of stat data failed: %v, left %s (skipping)", err, st.Data) return nil } doc := map[string]interface{}{} err = json.Unmarshal(st.Data, &doc) if err != nil { c.Infof("Problem parsing stat data from %v (%v): %v - ignoring", k, k.Encode(), err) return nil } doc["timestamp"] = st.Timestamp doc["type"] = "stats" doc["active_version"] = true doc["api_ver"] = st.ApiVer doc["addr"] = st.Addr doc["geo"] = map[string]interface{}{ "countryCode": st.Country, "cityName": st.City, "regionName": st.Region, "latitude": st.Lat, "longitude": st.Lon, } _, err = storeInCouch(c, doc, fmt.Sprintf("stats_%d", k.IntID())) return err }
func PutInvestment(c appengine.Context, i *Investment) error { var k *datastore.Key if i.Key == "" { k = datastore.NewIncompleteKey(c, investmentEntityName, investmentKey(c)) } else { decoded, err := datastore.DecodeKey(i.Key) if err != nil { return err } k = decoded } k, err := datastore.Put(c, k, i) if err != nil { return err } i.Key = k.Encode() return err }
// checkDone tests whether we have generated all the tiles. // If so, it creates a zip task on the zipper backend. func checkDone(c appengine.Context, oKey *datastore.Key) (done bool, err error) { // Create a zip task if we're done and one hasn't been created already. tx := func(c appengine.Context) error { o := new(Overlay) err := datastore.Get(c, oKey, o) if err != nil { return err } // Check whether we have generated all the tiles. count, err := datastore.NewQuery("Tile").Ancestor(oKey).Count(c) if err != nil { return err } done = o.Tiles >= count if !done || o.Zip != "" { return nil } // Create a task to build the zip file, // targeting the zipper backend. task := taskqueue.NewPOSTTask("/zip", url.Values{ "key": {oKey.Encode()}, }) if !appengine.IsDevAppServer() { host := appengine.BackendHostname(c, zipBackend, -1) task.Header.Set("Host", host) } if _, err := taskqueue.Add(c, task, zipQueue); err != nil { return err } // Store a sentinel value in Zip field to prevent a // second zip task from being created. // This value will be overwritten by the zip task. o.Zip = zipSentinel _, err = datastore.Put(c, oKey, o) return err } if err := datastore.RunInTransaction(c, tx, nil); err != nil { return false, err } return done, nil }
func loginPost(w http.ResponseWriter, r *http.Request) { responseType, client, err := params(r) if err != nil { err.WriteTo(w) return } email, password := r.FormValue("email"), r.FormValue("password") emailHash := model.UserEmail(email) context := appengine.NewContext(r) query := datastore.NewQuery("User").Filter("EmailHash =", emailHash) found, hasEntries := false, false var foundKey *datastore.Key for row := query.KeysOnly().Run(context); ; { key, e := row.Next(nil) if e == datastore.Done { break } query := datastore.NewQuery("Authentication").Filter("Type =", "password").Filter("User ="******"/oauth2/auth?response_type="+url.QueryEscape(responseType)+"&client_id="+ url.QueryEscape(client.Id)+"&msgs="+url.QueryEscape("Incorrect Email or Password"), 303).ServeHTTP(w, r) } } if !hasEntries { http.RedirectHandler("/oauth2/auth?response_type="+url.QueryEscape(responseType)+"&client_id="+ url.QueryEscape(client.Id)+"&msgs="+url.QueryEscape("Incorrect Email or Password"), 303).ServeHTTP(w, r) } }
func Login(rw http.ResponseWriter, req *http.Request, sess sessions.Session) { username := req.FormValue("username") password := req.FormValue("pass") c := appengine.NewContext(req) q := datastore.NewQuery("User") var key *datastore.Key for t := q.Run(c); ; { var u User k, err := t.Next(&u) c.Debugf("username: %s", u.Username) c.Debugf("password: %s", u.Password) if err != nil || k == nil { http.Redirect(rw, req, "/admin/auth?error=Failed to login", http.StatusFound) return } if !strings.EqualFold(username, u.Username) { http.Redirect(rw, req, "/admin/auth?error=Failed to login", http.StatusFound) return } if !strings.EqualFold(password, u.Password) { http.Redirect(rw, req, "/admin/auth?error=Failed to login", http.StatusFound) return } key = k break } if key == nil { http.Redirect(rw, req, "/admin/auth?error=Failed to login", http.StatusFound) return } sess.Set("auth", key.Encode()) http.Redirect(rw, req, "/admin", http.StatusFound) return }
// addTilesToZip fetches all the Tile records for a given Overlay, fetches // their associated image blobs, and adds them to the provided zip file. func addTilesToZip(c appengine.Context, z *zip.Writer, oKey *datastore.Key) error { base := oKey.Encode() q := datastore.NewQuery("Tile").Ancestor(oKey) for i := q.Run(c); ; { var t Tile if _, err := i.Next(&t); err == datastore.Done { break } else if err != nil { return err } name := fmt.Sprintf("%s/%d/%d/%d.png", base, t.Zoom, t.X, t.Y) w, err := z.Create(name) if err != nil { return err } if _, err = w.Write(t.Image); err != nil { return err } } return nil }
// Create and show gamelist page func Gamelist(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) gamekey := r.FormValue("gamekey") if gamekey != "" { c.Debugf(gamekey) Matching(w, r, gamekey, 2) } else { // get all games from datastore q := datastore.NewQuery("Game") games := q.Run(c) gameNum, _ := q.Count(c) // Create <li> of any games liTemplate := ` <li> <a href="/gamelist?gamekey=%s" data-transition="slide"> <div>%s</div> <div>ルール:%s</div> <div>カードセット:%s</div> <div>人数:2/4</div> </a> </li> ` game := new(Game) material := make(map[string]string) cardset := new(Cardset) rule := new(Rule) var gamekey *datastore.Key for i := 0; i < gameNum; i++ { gamekey, _ = games.Next(game) datastore.Get(c, game.Cardset, cardset) datastore.Get(c, game.Rule, rule) material["GameList"] += fmt.Sprintf(liTemplate, gamekey.Encode(), game.Name, rule.Name, cardset.Name) } Output(w, "page/game/gamelist.html", material) } }
func (self *DSHelpper) Entity2Model(key *datastore.Key, entity interface{}) (model interface{}) { // get entity type, name, value entityValue := reflect.ValueOf(entity).Elem() entityType := entityValue.Type() entityName := entityType.String() arr := strings.Split(entityName, ".") entityName = arr[len(arr)-1] // set model name, type, value modelName := entityName[0 : len(entityName)-6] // trimright has bug // modelName := strings.TrimRight(entityName, "Entity") modelType := self.structMap[modelName] modelValue := reflect.New(modelType).Elem() // copy field count := entityValue.NumField() for i := 0; i < count; i++ { field := entityType.Field(i) fieldType := field.Type fieldValue := entityValue.Field(i) modelField := modelValue.FieldByName(field.Name) modelFieldType := modelField.Type() // []byte 2 string situation if fieldType == self.structMap["ByteArray"] && modelFieldType == self.structMap["String"] { bytes := fieldValue.Interface().([]byte) str := string(bytes) fieldValue = reflect.ValueOf(str) } modelField.Set(fieldValue) } modelIDField := modelValue.FieldByName("ID") idValue := reflect.ValueOf(key.Encode()) modelIDField.Set(idValue) model = modelValue.Interface() return model }