示例#1
0
文件: web.go 项目: dbratus/impack
func cut(resp http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)

	minuteBack, _ := time.ParseDuration("-1m")
	cutPoint := time.Now().Add(minuteBack)

	q := datastore.NewQuery("SpriteInfo").
		Filter("Timestamp <", cutPoint)

	itr := q.Run(ctx)

	var spriteInfo SpriteInfo

	cnt := 0
	var k *datastore.Key
	var itrErr error

	for k, itrErr = itr.Next(&spriteInfo); itrErr == nil; k, itrErr = itr.Next(&spriteInfo) {
		if err := blobstore.Delete(ctx, spriteInfo.CssId); err != nil {
			ctx.Errorf("Error deleting CSS %s %s.", spriteInfo.CssId, err)
		}

		if err := blobstore.Delete(ctx, spriteInfo.ImageId); err != nil {
			ctx.Errorf("Error deleting image %s %s.", spriteInfo.ImageId, err)
		}

		if err := datastore.Delete(ctx, k); err != nil {
			ctx.Errorf("Error deleting sprite %s %s.", k, err)
		}

		cnt++
	}

	ctx.Infof("Cut stoped with result %v. %d sprites deleted", itrErr, cnt)
}
示例#2
0
func Delete(k int64, r *http.Request) (err error) {
	c := appengine.NewContext(r)
	key := datastore.NewKey(c, "Photo", "", k, nil)

	// Get the database record
	var p Photo
	err = datastore.Get(c, key, &p)
	if err != nil {
		return
	}

	// Now we need to clean up the blobstore
	// First we'll drop out the full resolution image
	// then the thumbnail
	err = blobstore.Delete(c, appengine.BlobKey(p.Blob))
	if len(p.Thumb) != 0 {
		err = blobstore.Delete(c, appengine.BlobKey(p.Thumb))
	}

	log.Println(err)
	if err != nil {
		return
	}

	// Delete from the database
	err = datastore.Delete(c, key)
	if err != nil {
		return
	}

	return
}
示例#3
0
func (x RemoveTaskFileRes) Post(c appengine.Context, r *http.Request) (interface{}, error) {
	t := new(Task)
	if err := json.NewDecoder(r.Body).Decode(t); err != nil {
		return nil, err
	}
	PrintInBox(c, "Trying to remove", t.BlobKey)
	if err := blobstore.Delete(c, t.BlobKey); err != nil {
		return nil, err
	}
	return nil, blobstore.Delete(c, t.BlobKey)
}
示例#4
0
// form : title tags html markdown
func updatePage(c appengine.Context, r *http.Request) (Page, error) {
	title := r.FormValue("goblog_title")
	tags := r.FormValue("goblog_tags")
	html := r.FormValue("goblog_html")
	markdown := r.FormValue("goblog_markdown")

	var newPage Page
	newPage.Title = title
	newPage.Tags = strings.Split(tags, ",")
	newPage.Date = time.Now()
	blob, err := newBlob(c, []byte(html))
	if err != nil {
		return newPage, err
	}
	newPage.HTML = blob
	blob, err = newBlob(c, []byte(markdown))
	newPage.Markdown = blob

	// if have the same doc
	key := datastore.NewKey(c, "Page", newPage.Title, 0, nil)
	err = datastore.RunInTransaction(c, func(c appengine.Context) error {
		var savedPage Page
		err := datastore.Get(c, key, &savedPage)
		if nil != err {
			c.Errorf("err no page: %v", err)
		}
		if datastore.ErrNoSuchEntity != err {
			err = blobstore.Delete(c, savedPage.HTML)
			if nil != err {
				c.Errorf("err delete html: %v", err)
				return err
			}
			err = blobstore.Delete(c, savedPage.Markdown)
			if nil != err {
				c.Errorf("err delete markdwon: %v", err)
				return err
			}
		}
		_, err = datastore.Put(c, key, &newPage)
		if nil != err {
			c.Errorf("%v", err)
			return err
		}
		return nil
	}, nil)
	if nil != err {
		return newPage, err
	}
	return newPage, err
}
示例#5
0
文件: tasks.go 项目: huluwa/2016_Gofr
func importOPMLTask(pfc *PFContext) (TaskMessage, error) {
	c := pfc.C

	var blobKey appengine.BlobKey
	if blobKeyString := pfc.R.PostFormValue("opmlBlobKey"); blobKeyString == "" {
		return TaskMessage{}, errors.New("Missing blob key")
	} else {
		blobKey = appengine.BlobKey(blobKeyString)
	}

	reader := blobstore.NewReader(c, blobKey)

	opml, err := rss.ParseOPML(reader)
	if err != nil {
		// Remove the blob
		if err := blobstore.Delete(c, blobKey); err != nil {
			c.Warningf("Error deleting blob (key %s): %s", blobKey, err)
		}

		return TaskMessage{}, err
	}

	// Remove the blob
	if err := blobstore.Delete(c, blobKey); err != nil {
		c.Warningf("Error deleting blob (key %s): %s", blobKey, err)
	}

	importStarted := time.Now()

	parentRef := storage.FolderRef{
		UserID: pfc.UserID,
	}

	doneChannel := make(chan *rss.Outline)
	importing := importSubscriptions(pfc, doneChannel, pfc.UserID, parentRef, opml.Outlines())

	for i := 0; i < importing; i++ {
		subscription := <-doneChannel
		c.Infof("Completed %s", subscription.Title)
	}

	c.Infof("All completed in %s", time.Since(importStarted))

	return TaskMessage{
		Message: _l("Subscriptions imported successfully"),
		Refresh: true,
	}, nil
}
示例#6
0
func cleanImage(w http.ResponseWriter, r *http.Request) {
	// Con esta manejador borramos las imagenes que no están asociadas a
	// ningún punto y han quedado huerfanas

	c := appengine.NewContext(r)

	var blobs []blobstore.BlobInfo

	q := datastore.NewQuery("__BlobInfo__")
	keys, _ := q.GetAll(c, &blobs)
	for _, key := range keys {

		var imgk = appengine.BlobKey(key.StringID())

		// Busco algun punto con esa key como imagen
		var points []points.Point
		qp := datastore.NewQuery("points").Filter("ImageKey = ", imgk)
		qp.GetAll(c, &points)
		if len(points) == 0 {
			// borro la imagen
			c.Infof("borro imagen %s", imgk)
			err := blobstore.Delete(c, imgk)
			if err != nil {
				app.ServeError(c, w, err)
				return
			}
		}
	}
}
示例#7
0
func delete(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	var dTile Tile
	//	var now Period
	//	datastore.Get(c, currentSemesterKey(c), &now)
	num, e := strconv.Atoi(r.FormValue("num"))
	sem, e1 := strconv.Atoi(r.FormValue("semester"))
	yr, e2 := strconv.Atoi(r.FormValue("year"))
	if e != nil || e1 != nil || e2 != nil {
		panic("shouldn't happen; semester and year guaranteed to be ints")
	}
	k := datastore.NewKey(c, "Tile", strint(r.FormValue("name"), num), 0, tileRootKey(c, sem, yr))
	datastore.Get(c, k, &dTile)
	if u := user.Current(c); !u.Admin {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	} else {
		log.Println("deleting things now...")
		e1 := blobstore.Delete(c, appengine.BlobKey(dTile.Imgref))
		e2 := datastore.Delete(c, k)
		if e1 != nil {
			log.Println("error with blobstore delete")
		}
		if e2 != nil {
			log.Println("error with datastore delete")
		}
	}
	log.Println("redirecting")
	http.Redirect(w, r, "/", http.StatusFound)
}
示例#8
0
func (photo *Photo) Upload(r *http.Request) (err error) {
	c := appengine.NewContext(r)

	blob, err := blobstore.Create(c, r.Header.Get("X-File-Type"))
	if err != nil {
		return
	}

	defer r.Body.Close()
	//body, err := ioutil.ReadAll(r.Body)
	var buf bytes.Buffer
	io.Copy(&buf, r.Body)
	_, err = blob.Write(buf.Bytes())
	if err != nil {
		return
	}

	_ = blob.Close()
	key, err := blob.Key()
	if err != nil {
		return
	}

	photo.Blob = string(key)

	err = photo.CreateThumb(r, buf)
	if err != nil {
		log.Println(err)
		err = blobstore.Delete(c, key)
		err = errors.New("Failed to upload image")
	}

	return
}
示例#9
0
func updateImage(c appengine.Context, img Image) error {
	key := datastore.NewKey(c, "Image", img.Name, 0, nil)
	err := datastore.RunInTransaction(c, func(c appengine.Context) error {
		newimg := Image{}
		err := datastore.Get(c, key, &newimg)
		if nil != err && datastore.ErrNoSuchEntity != err {
			c.Errorf("%v", err)
			return err
		}
		if datastore.ErrNoSuchEntity != err {
			err = blobstore.Delete(c, newimg.BlobKey)
			if nil != err {
				c.Errorf("%v", err)
				return err
			}
		}
		_, err = datastore.Put(c, key, &img)
		if nil != err {
			c.Errorf("%v", err)
			return err
		}
		return nil
	}, nil)
	if nil != err {
		c.Errorf("%v", err)
		return err
	}
	return nil
}
示例#10
0
func Delete(rw http.ResponseWriter, req *http.Request, r render.Render, params martini.Params) {
	ctx := appengine.NewContext(req)

	b := banner.Banner{}

	intID, err := strconv.Atoi(params["id"])
	if err == nil {
		b.ID = int64(intID)
	}

	if err := b.Get(ctx); err != nil {
		http.Error(rw, "failed to delete banner", http.StatusInternalServerError)
		return
	}

	segs := strings.Split(b.Image, "/")
	blobstore.Delete(ctx, appengine.BlobKey(segs[len(segs)-1]))

	if err := b.Delete(ctx); err != nil {
		http.Error(rw, "failed to delete banner", http.StatusInternalServerError)
		return
	}

	r.Status(200)
	return
}
示例#11
0
func DelOferta(c appengine.Context, id string) error {
	q := datastore.NewQuery("Oferta").Filter("IdOft =", id)
	for i := q.Run(c); ; {
		var e Oferta
		key, err := i.Next(&e)
		if err == datastore.Done {
			break
		}
		if err := blobstore.Delete(c, e.BlobKey); err != nil {
			return err
		}
		if err := DelOfertaSucursales(c, id); err != nil {
			return err
		}
		if err := DelOfertaPalabras(c, id); err != nil {
			return err
		}
		if err := DelOfertaSearchData(c, key); err != nil {
			return err
		}
		if err := datastore.Delete(c, key); err != nil {
			return err
		}
		_ = PutChangeControl(c, e.IdOft, "Oferta", "B")
	}
	return nil
}
示例#12
0
文件: main.go 项目: omairrazam/bapp
func handleUpload(r *http.Request, p *multipart.Part) (fi *FileInfo) {
	fi = &FileInfo{
		Name: p.FileName(),
		Type: p.Header.Get("Content-Type"),
	}
	if !fi.ValidateType() {
		return
	}
	defer func() {
		if rec := recover(); rec != nil {
			log.Println(rec)
			fi.Error = rec.(error).Error()
		}
	}()
	lr := &io.LimitedReader{R: p, N: MAX_FILE_SIZE + 1}
	context := appengine.NewContext(r)
	w, err := blobstore.Create(context, fi.Type)
	defer func() {
		w.Close()
		fi.Size = MAX_FILE_SIZE + 1 - lr.N
		fi.Key, err = w.Key()
		check(err)
		if !fi.ValidateSize() {
			err := blobstore.Delete(context, fi.Key)
			check(err)
			return
		}
		delayedDelete(context, fi)
		fi.CreateUrls(r, context)
	}()
	check(err)
	_, err = io.Copy(w, lr)
	return
}
示例#13
0
func (r *Oferta) DelOferta(c appengine.Context) error {
	if err := blobstore.Delete(c, r.BlobKey); err != nil {
		return err
	}
	if err := datastore.Delete(c, r.Key(c)); err != nil {
		return err
	}
	return nil
}
示例#14
0
文件: utils.go 项目: Ranerg/goread
func loadImage(c appengine.Context, f *Feed) string {
	s := f.Link
	if s == "" {
		s = f.Url
	}
	u, err := url.Parse(s)
	if err != nil {
		return ""
	}
	u.Path = "/favicon.ico"
	u.RawQuery = ""
	u.Fragment = ""

	g := goon.FromContext(c)
	i := &Image{Id: u.String()}
	if err := g.Get(i); err == nil {
		return i.Url
	}
	client := urlfetch.Client(c)
	r, err := client.Get(u.String())
	if err != nil || r.StatusCode != http.StatusOK || r.ContentLength == 0 {
		return ""
	}
	b, err := ioutil.ReadAll(r.Body)
	r.Body.Close()
	if err != nil {
		return ""
	}
	buf := bytes.NewBuffer(b)
	_, t, err := image.DecodeConfig(buf)
	if err != nil {
		t = "application/octet-stream"
	} else {
		t = "image/" + t
	}
	w, err := blobstore.Create(c, t)
	if err != nil {
		return ""
	}
	if _, err := w.Write(b); err != nil {
		return ""
	}
	if w.Close() != nil {
		return ""
	}
	i.Blob, _ = w.Key()
	su, err := aimage.ServingURL(c, i.Blob, &aimage.ServingURLOptions{Size: 16})
	if err != nil {
		if err = blobstore.Delete(c, i.Blob); err != nil {
			c.Errorf("blob delete err: %v", err)
		}
		return ""
	}
	i.Url = su.String()
	g.Put(i)
	return i.Url
}
示例#15
0
文件: json.go 项目: huluwa/2016_Gofr
func importOPML(pfc *PFContext) (interface{}, error) {
	c := pfc.C
	r := pfc.R

	blobs, other, err := blobstore.ParseUpload(r)
	if err != nil {
		return nil, NewReadableError(_l("Error receiving file"), &err)
	} else if len(other["client"]) > 0 {
		if clientID := other["client"][0]; clientID != "" {
			pfc.ChannelID = string(pfc.UserID) + "," + clientID
		}
	}

	var blobKey appengine.BlobKey
	if blobInfos := blobs["opml"]; len(blobInfos) == 0 {
		return nil, NewReadableError(_l("File not uploaded"), nil)
	} else {
		blobKey = blobInfos[0].BlobKey
		reader := blobstore.NewReader(c, blobKey)

		if _, err := rss.ParseOPML(reader); err != nil {
			if err := blobstore.Delete(c, blobKey); err != nil {
				c.Warningf("Error deleting blob (key %s): %s", blobKey, err)
			}

			return nil, NewReadableError(_l("Error reading OPML file"), &err)
		}
	}

	params := taskParams{
		"opmlBlobKey": string(blobKey),
	}
	if err := startTask(pfc, "import", params, importQueue); err != nil {
		// Remove the blob
		if err := blobstore.Delete(c, blobKey); err != nil {
			c.Warningf("Error deleting blob (key %s): %s", blobKey, err)
		}

		return nil, NewReadableError(_l("Cannot import - too busy"), &err)
	}

	return _l("Importing, please wait…"), nil
}
示例#16
0
func (photo Photo) Store(r *http.Request) (err error) {
	c := appengine.NewContext(r)

	photo.Added = time.Now()
	_, err = datastore.Put(c, datastore.NewIncompleteKey(c, "Photo", nil), &photo)

	if err != nil {
		_ = blobstore.Delete(c, appengine.BlobKey(photo.Blob))
	}
	return
}
示例#17
0
func delete(w http.ResponseWriter, r *http.Request) {
	parts := strings.Split(r.URL.Path, "/")
	if len(parts) != 3 {
		return
	}
	if key := parts[1]; key != "" {
		c := appengine.NewContext(r)
		blobstore.Delete(c, appengine.BlobKey(key))
		memcache.Delete(c, key)
	}
}
示例#18
0
func deleteImage(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if err := users.CheckPerm(w, r, users.OP_UPDATE); err != nil {
		return
	}

	key := appengine.BlobKey(r.FormValue("blobKey"))
	err := blobstore.Delete(c, key)
	if err != nil {
		app.ServeError(c, w, err)
		return
	}
}
示例#19
0
func (sto *appengineStorage) ReceiveBlob(br *blobref.BlobRef, in io.Reader) (sb blobref.SizedBlobRef, err os.Error) {
	if sto.ctx == nil {
		err = errNoContext
		return
	}

	var b bytes.Buffer
	hash := br.Hash()
	written, err := io.Copy(io.MultiWriter(hash, &b), in)
	if err != nil {
		return
	}

	if !br.HashMatches(hash) {
		err = blobserver.ErrCorruptBlob
		return
	}
	mimeType := "application/octet-stream"
	bw, err := blobstore.Create(sto.ctx, mimeType)
	if err != nil {
		return
	}
	written, err = io.Copy(bw, &b)
	if err != nil {
		// TODO(bradfitz): try to clean up; close it, see if we can find the key, delete it.
		return
	}
	err = bw.Close()
	if err != nil {
		// TODO(bradfitz): try to clean up; see if we can find the key, delete it.
		return
	}
	bkey, err := bw.Key()
	if err != nil {
		return
	}

	var ent blobEnt
	ent.BlobRefStr = br.String()
	ent.Size = written
	ent.BlobKey = bkey

	dkey := datastore.NewKey(sto.ctx, blobKind, br.String(), 0, nil)
	_, err = datastore.Put(sto.ctx, dkey, &ent)
	if err != nil {
		blobstore.Delete(sto.ctx, bkey) // TODO: insert into task queue on error to try later?
		return
	}

	return blobref.SizedBlobRef{br, written}, nil
}
示例#20
0
//Delete deletes the presentation record from Datastore and
//its data file from Blobstore.
func (p *Presentation) Delete(c appengine.Context) (err error) {
	err = action.DeleteFor(p, c)
	if err != nil {
		return
	}

	err = gaemodel.Delete(c, p)
	if err != nil {
		return
	}

	err = blobstore.Delete(c, p.BlobKey)
	return
}
示例#21
0
func delete(w http.ResponseWriter, r *http.Request) {
	parts := strings.Split(r.URL.Path, "/")
	if len(parts) != 3 {
		return
	}
	if key := parts[1]; key != "" {
		c := appengine.NewContext(r)
		blobKey := appengine.BlobKey(key)
		err := blobstore.Delete(c, blobKey)
		check(err)
		err = image.DeleteServingURL(c, blobKey)
		check(err)
	}
}
示例#22
0
// Delete a file in the blobstore
func deleteFile(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	// Check the CSRF
	if csrf.ValidateToken(r, r.FormValue("CSRFToken")) {
		// Get the file ID
		trimPath := strings.Trim(r.URL.Path, "/admin/files/delete/")
		key := appengine.BlobKey(trimPath)

		// Delete blobstore entry
		blobstore.Delete(c, key)
		// Redirect
		http.Redirect(w, r, r.Referer(), http.StatusFound)
	}
}
示例#23
0
// 画像の物理削除
func handleDeleteImage(w http.ResponseWriter, r *http.Request) {
	if r.Method != "DELETE" {
		http.Error(w, "リクエストエラー", http.StatusBadRequest)
		return
	}
	c := appengine.NewContext(r)
	g := goon.FromContext(c)
	key := r.FormValue("key")
	ibi := ImageBlobInfo{
		BlobKey: key,
	}
	g.Get(&ibi)
	blobstore.Delete(c, appengine.BlobKey(ibi.BlobKey))
}
示例#24
0
func storeImage(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if err := users.CheckPerm(w, r, users.OP_UPDATE); err != nil {
		return
	}

	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		app.ServeError(c, w, err)
		return
	}

	file := blobs["img"]
	if len(file) == 0 {
		app.ServeError(c, w, errors.New(ERR_FILENOTSTORED))
		return
	}

	key := file[0].BlobKey

	info, err := blobstore.Stat(c, key)
	if err != nil {
		app.ServeError(c, w, err)
		return
	}

	if info.Size > MAXSZIMAGE {
		blobstore.Delete(c, key)
		app.ServeError(c, w, errors.New(ERR_FILENOTVALID))
		return
	}

	/*

		key,err=resizeImage(c,key)
		if err != nil {
	                app.ServeError(c, w, errors.New(ERR_FILENOTVALID))
	                return
	        }

	*/

	fmt.Fprintf(w, "%s", string(key))
}
示例#25
0
func handleUpload(r *http.Request, p *multipart.Part) (fi *FileInfo) {
	fi = &FileInfo{
		Name: p.FileName(),
		Type: p.Header.Get("Content-Type"),
	}
	if !fi.ValidateType() {
		return
	}
	defer func() {
		if rec := recover(); rec != nil {
			log.Println(rec)
			fi.Error = rec.(os.Error).String()
		}
	}()
	var b bytes.Buffer
	lr := &io.LimitedReader{p, MAX_FILE_SIZE + 1}
	context := appengine.NewContext(r)
	w, err := blobstore.Create(context, fi.Type)
	defer func() {
		w.Close()
		fi.Size = MAX_FILE_SIZE + 1 - lr.N
		fi.Key, err = w.Key()
		check(err)
		if !fi.ValidateSize() {
			err := blobstore.Delete(context, fi.Key)
			check(err)
			return
		}
		delayedDelete(context, fi)
		if b.Len() > 0 {
			fi.CreateThumbnail(&b, context)
		}
		fi.CreateUrls(r, context)
	}()
	check(err)
	var wr io.Writer = w
	if imageTypes.MatchString(fi.Type) {
		wr = io.MultiWriter(&b, w)
	}
	_, err = io.Copy(wr, lr)
	return
}
示例#26
0
func updatePage(c appengine.Context, blobKey appengine.BlobKey) (Page, error) {
	reader := blobstore.NewReader(c, blobKey)
	buf := new(bytes.Buffer)
	buf.ReadFrom(reader)
	xmlDoc := new(DocumentXML)
	err := xml.Unmarshal(buf.Bytes(), xmlDoc)
	var newPage Page
	if nil != err {
		c.Errorf("%v", err)
		return newPage, err
	}
	newPage.GetDoc(xmlDoc)
	newPage.Date = time.Now()
	newPage.BlobKey = blobKey
	// if have the same doc
	key := datastore.NewKey(c, "Page", newPage.Title, 0, nil)
	err = datastore.RunInTransaction(c, func(c appengine.Context) error {
		var savedPage Page
		err := datastore.Get(c, key, &savedPage)
		if nil != err && datastore.ErrNoSuchEntity != err {
			c.Errorf("%v", err)
			return err
		}
		if datastore.ErrNoSuchEntity != err {
			err = blobstore.Delete(c, savedPage.BlobKey)
			if nil != err {
				c.Errorf("%v", err)
				return err
			}
		}
		_, err = datastore.Put(c, key, &newPage)
		if nil != err {
			c.Errorf("%v", err)
			return err
		}
		return nil
	}, nil)
	if nil != err {
		return newPage, err
	}
	return newPage, err
}
示例#27
0
func handleServe(w http.ResponseWriter, r *http.Request) {
	// Instantiate blobstore reader
	reader := blobstore.NewReader(appengine.NewContext(r),
		appengine.BlobKey(r.FormValue("blobKey")))

	lat, lng, _ := getLatLng(reader)

	blobstore.Delete(appengine.NewContext(r),
		appengine.BlobKey(r.FormValue("blobKey")))

	if lat == "" {
		io.WriteString(w, "Sorry but your photo has no GeoTag information...")
		return
	}

	s := "http://maps.googleapis.com/maps/api/staticmap?zoom=5&size=600x300&maptype=roadmap&amp;center="
	s = s + lat + "," + lng + "&markers=color:blue%7Clabel:I%7C" + lat + "," + lng

	img := "<img src='" + s + "' alt='map' />"
	fmt.Fprint(w, img)

}
示例#28
0
文件: main.go 项目: omairrazam/bapp
func delete(w http.ResponseWriter, r *http.Request) {
	parts := strings.Split(r.URL.Path, "/")
	if len(parts) != 3 {
		return
	}
	result := make(map[string]bool, 1)
	if key := parts[1]; key != "" {
		c := appengine.NewContext(r)
		blobKey := appengine.BlobKey(key)
		err := blobstore.Delete(c, blobKey)
		check(err)
		err = image.DeleteServingURL(c, blobKey)
		check(err)
		result[key] = true
	}
	jsonType := "application/json"
	if strings.Index(r.Header.Get("Accept"), jsonType) != -1 {
		w.Header().Set("Content-Type", jsonType)
	}
	b, err := json.Marshal(result)
	check(err)
	fmt.Fprintln(w, string(b))
}
示例#29
0
func deletePoint(w http.ResponseWriter, r *http.Request) {

	c := appengine.NewContext(r)
	if err := users.CheckPerm(w, r, users.OP_UPDATE); err != nil {
		return
	}

	r.ParseForm()
	if r.Form["id"] == nil {
		app.ServeError(c, w, errors.New("Point not deleted. ID expected"))
		return
	}

	id, err := strconv.ParseInt(r.Form["id"][0], 10, 64)
	if err != nil {
		app.ServeError(c, w, errors.New("Point not deleted. Bad ID"))
		return
	}

	k := datastore.NewKey(c, "points", "", id, nil)

	// Eliminar imagen asociada a el del blobStore
	var p Point
	datastore.Get(c, k, &p)
	if p.ImageKey != "" {
		blobstore.Delete(c, appengine.BlobKey(p.ImageKey))
	}

	// Elimino punto
	err = datastore.Delete(c, k)
	if err != nil {
		app.ServeError(c, w, errors.New("Point not deleted. Entity not found"))
		return
	}

}
示例#30
0
func (sto *appengineStorage) ReceiveBlob(br blob.Ref, in io.Reader) (sb blob.SizedRef, err error) {
	loan := ctxPool.Get()
	defer loan.Return()
	ctx := loan

	var b bytes.Buffer
	written, err := io.Copy(&b, in)
	if err != nil {
		return
	}

	// bkey is non-empty once we've uploaded the blob.
	var bkey appengine.BlobKey

	// uploadBlob uploads the blob, unless it's already been done.
	uploadBlob := func(ctx appengine.Context) error {
		if len(bkey) > 0 {
			return nil // already done in previous transaction attempt
		}
		bw, err := blobstore.Create(ctx, "application/octet-stream")
		if err != nil {
			return err
		}
		_, err = io.Copy(bw, &b)
		if err != nil {
			// TODO(bradfitz): try to clean up; close it, see if we can find the key, delete it.
			ctx.Errorf("blobstore Copy error: %v", err)
			return err
		}
		err = bw.Close()
		if err != nil {
			// TODO(bradfitz): try to clean up; see if we can find the key, delete it.
			ctx.Errorf("blobstore Close error: %v", err)
			return err
		}
		k, err := bw.Key()
		if err == nil {
			bkey = k
		}
		return err
	}

	tryFunc := func(tc appengine.Context) error {
		row, err := fetchEnt(tc, br)
		switch err {
		case datastore.ErrNoSuchEntity:
			if err := uploadBlob(tc); err != nil {
				tc.Errorf("uploadBlob failed: %v", err)
				return err
			}
			row = &blobEnt{
				Size:       written,
				BlobKey:    bkey,
				Namespaces: sto.namespace,
			}
			_, err = datastore.Put(tc, entKey(tc, br), row)
			if err != nil {
				return err
			}
		case nil:
			if row.inNamespace(sto.namespace) {
				// Nothing to do
				return nil
			}
			row.Namespaces = row.Namespaces + "|" + sto.namespace
			_, err = datastore.Put(tc, entKey(tc, br), row)
			if err != nil {
				return err
			}
		default:
			return err
		}

		// Add membership row
		_, err = datastore.Put(tc, sto.memKey(tc, br), &memEnt{
			Size: written,
		})
		return err
	}
	err = datastore.RunInTransaction(ctx, tryFunc, crossGroupTransaction)
	if err != nil {
		if len(bkey) > 0 {
			// If we just created this blob but we
			// ultimately failed, try our best to delete
			// it so it's not orphaned.
			blobstore.Delete(ctx, bkey)
		}
		return
	}
	return blob.SizedRef{br, uint32(written)}, nil
}