예제 #1
0
func ScanOfertaBlob(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	const batch = 300
	page, _ := strconv.Atoi(r.FormValue("pg"))
	if page < 1 {
		page = 1
	}
	offset := batch * (page - 1)
	q := datastore.NewQuery("Oferta").Offset(offset).Order("-FechaHora").Limit(batch)
	n, _ := q.Count(c)
	for i := q.Run(c); ; {
		var e model.Oferta
		key, err := i.Next(&e)
		if err == datastore.Done {
			break
		}

		// Se crea la URL para servir la oferta desde el CDN, si no se puede
		// se deja en blanco
		var imgprops image.ServingURLOptions
		imgprops.Secure = true
		imgprops.Size = 400
		imgprops.Crop = false
		if e.BlobKey != "none" {
			reader := blobstore.NewReader(c, e.BlobKey)
			if _, err := ioutil.ReadAll(reader); err != nil {
				fmt.Fprintf(w, "Error en idoft: %s, idemp: %s, blobkey: %v, Fecha: %v\n", e.IdOft, e.IdEmp, string(e.BlobKey), e.FechaHora)
				e.BlobKey = "none"
				_, err = datastore.Put(c, key, &e)
			}
		}
	}
	fmt.Fprintf(w, "Batch: %d, count: %d, from  %d to %d\n", page, n, offset, offset+n)
	return
}
예제 #2
0
func UpdateServingLogoUrl(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	const batch = 50
	page, _ := strconv.Atoi(r.FormValue("pg"))
	if page < 1 {
		page = 1
	}
	offset := batch * (page - 1)
	q := datastore.NewQuery("EmpLogo").Offset(offset).Order("IdEmp").Limit(batch)
	n, _ := q.Count(c)
	for i := q.Run(c); ; {
		var e model.Image
		key, err := i.Next(&e)
		if err == datastore.Done {
			break
		}

		// Se crea la URL para servir la oferta desde el CDN, si no se puede
		// se deja en blanco
		var imgprops image.ServingURLOptions
		imgprops.Secure = true
		imgprops.Size = 180
		imgprops.Crop = false
		if e.Sp4 == "" && e.IdEmp != "" {
			var blobkey appengine.BlobKey
			blob, err := blobstore.Create(c, "image/jpeg")
			if err != nil {
				c.Errorf("blobstore Create: %v", e.IdEmp)
			}
			_, err = blob.Write(e.Data)
			if err != nil {
				c.Errorf("blobstore Write: %v", e.IdEmp)
			}
			err = blob.Close()
			if err != nil {
				c.Errorf("blobstore Close: %v", e.IdEmp)
			}
			blobkey, err = blob.Key()
			if err != nil {
				c.Errorf("blobstore Key Gen: %v", e.IdEmp)
			}
			if url, err := image.ServingURL(c, blobkey, &imgprops); err != nil {
				c.Errorf("Cannot construct EmpLogo ServingURL : %v", e.IdEmp)
			} else {
				e.Sp3 = string(blobkey)
				e.Sp4 = url.String()
			}
			_, err = datastore.Put(c, key, &e)
			if err != nil {
				c.Errorf("PutEmpLogo(); Error al intentar actualizar Emplogo : %v", e.IdEmp)
			}
		}
	}
	c.Infof("UpdateServingLogoUrl() Pagina: %d, actualizados: %d, del %d al %d", page, n, offset, offset+n)
	return
}
예제 #3
0
func handleServeImg(w http.ResponseWriter, r *http.Request) {
	if r.FormValue("id") != "none" {
		c := appengine.NewContext(r)
		var imgprops image.ServingURLOptions
		imgprops.Secure = true
		imgprops.Size = 400
		imgprops.Crop = false
		url, _ := image.ServingURL(c, appengine.BlobKey(r.FormValue("id")), &imgprops)
		http.Redirect(w, r, url.String(), http.StatusFound)
	}
	return
}
예제 #4
0
func serveThumb(c appengine.Context, w http.ResponseWriter, r *http.Request) {

	// c := appengine.NewContext(r)
	k := appengine.BlobKey(r.FormValue("blobkey"))

	var o image.ServingURLOptions = *new(image.ServingURLOptions)
	o.Size = 200
	o.Crop = true
	url, err := image.ServingURL(c, k, &o)

	util_err.Err_http(w, r, err, false)

	http.Redirect(w, r, url.String(), http.StatusFound)
}
예제 #5
0
func UpdateServingUrl(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	const batch = 300
	page, _ := strconv.Atoi(r.FormValue("pg"))
	if page < 1 {
		page = 1
	}
	offset := batch * (page - 1)
	q := datastore.NewQuery("Oferta").Offset(offset).Order("-FechaHora").Limit(batch)
	n, _ := q.Count(c)
	for i := q.Run(c); ; {
		var e model.Oferta
		key, err := i.Next(&e)
		if err == datastore.Done {
			break
		}

		// Se crea la URL para servir la oferta desde el CDN, si no se puede
		// se deja en blanco
		var imgprops image.ServingURLOptions
		imgprops.Secure = true
		imgprops.Size = 400
		imgprops.Crop = false
		if e.BlobKey != "none" && e.Codigo == "" {
			if url, err := image.ServingURL(c, e.BlobKey, &imgprops); err != nil {
				c.Errorf("Cannot construct ServingURL : %v", e.IdOft)
				e.Codigo = ""
			} else {
				e.Codigo = url.String()
			}

			//c.Errorf("Get Cta Key; Error al intentar leer key.Parent() de Empresa : %v", e.IdEmp)
			_, err = datastore.Put(c, key, &e)
			if err != nil {
				c.Errorf("PutEmpresa(); Error al intentar actualizar empresa : %v", e.IdEmp)
			}
		}
	}
	c.Infof("UpdateServingUrl() Pagina: %d, actualizados: %d, del %d al %d", page, n, offset, offset+n)
	return
}
예제 #6
0
func handleServeImgById(w http.ResponseWriter, r *http.Request) {
	if r.FormValue("id") != "none" {
		c := appengine.NewContext(r)
		oft, _ := model.GetOferta(c, r.FormValue("id"))
		if oft.BlobKey != "none" {
			var imgprops image.ServingURLOptions
			imgprops.Secure = true
			imgprops.Size = 400
			imgprops.Crop = false

			if url, err := image.ServingURL(c, oft.BlobKey, &imgprops); err != nil {
				c.Infof("Cannot construct ServingURL : %v", r.FormValue("id"))
				blobstore.Send(w, oft.BlobKey)
			} else {
				http.Redirect(w, r, url.String(), http.StatusFound)
			}
		} else {
			w.WriteHeader(http.StatusNotFound)
			//w.Header().Set("Content-Type", "text/plain; charset=utf-8")
			//io.WriteString(w, "404 - Not Found")
		}
	}
	return
}
예제 #7
0
// upload is the HTTP handler for uploading images; it handles "/".
func upload(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	var imgprops appimage.ServingURLOptions
	imgprops.Secure = true
	imgprops.Size = 180
	imgprops.Crop = false
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		emp, err := u.GetEmpresa(c, r.FormValue("IdEmp"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		imgo := model.GetLogo(c, r.FormValue("IdEmp"))
		if imgo == nil {
			imgo = new(model.Image)
			imgo.IdEmp = emp.IdEmp
		}
		fd := imgToForm(*imgo)
		tc := make(map[string]interface{})
		tc["Sess"] = s
		tc["Empresa"] = emp
		tc["FormData"] = fd
		if r.Method != "POST" {
			// No upload; show the upload form.
			micrositio(w, r)
			return
		}

		idemp := r.FormValue("IdEmp")
		sp1 := r.FormValue("Sp1")
		sp2 := r.FormValue("Sp2")
		f, _, err := r.FormFile("image")
		model.Check(err)
		defer f.Close()

		// Grab the image data
		var buf bytes.Buffer
		io.Copy(&buf, f)
		i, _, err := image.Decode(&buf)
		if err != nil {
			if r.FormValue("tipo") == "async" {
				//w.Header().Set("Content-Type", "application/json")
				fmt.Fprintf(w, "<p>'%s'</p>", "No se actualizó el logotipo, formato no aceptado")
			} else {
				tc["Error"] = struct{ Badformat string }{"badformat"}
				micrositioTpl.Execute(w, tc)
			}
			return
		}
		const max = 600
		// We aim for less than max pixels in any dimension.
		if b := i.Bounds(); b.Dx() > max || b.Dy() > max {
			// If it's gigantic, it's more efficient to downsample first
			// and then resize; resizing will smooth out the roughness.
			if b.Dx() > 2*max || b.Dy() > 2*max {
				w, h := max*2, max*2
				if b.Dx() > b.Dy() {
					h = b.Dy() * h / b.Dx()
				} else {
					w = b.Dx() * w / b.Dy()
				}
				i = resize.Resample(i, i.Bounds(), w, h)
				b = i.Bounds()
			}
			w, h := max, max
			if b.Dx() > b.Dy() {
				h = b.Dy() * h / b.Dx()
			} else {
				w = b.Dx() * w / b.Dy()
			}
			i = resize.Resize(i, i.Bounds(), w, h)
		}

		// Encode as a new JPEG image.
		buf.Reset()
		err = jpeg.Encode(&buf, i, nil)
		if err != nil {
			if r.FormValue("tipo") == "async" {
				fmt.Fprintf(w, "<p>'%s'</p>", "No se actualizó el logotipo, formato no aceptado")
			} else {
				tc["Error"] = struct{ Badencode string }{"badencode"}
				micrositioTpl.Execute(w, tc)
			}
			return
		}
		var blobkey appengine.BlobKey
		blob, err := blobstore.Create(c, "image/jpeg")
		if err != nil {
			c.Errorf("blobstore Create: %v", idemp)
		}
		_, err = blob.Write(buf.Bytes())
		if err != nil {
			c.Errorf("blobstore Write: %v", idemp)
		}
		err = blob.Close()
		if err != nil {
			c.Errorf("blobstore Close: %v", idemp)
		}
		blobkey, err = blob.Key()
		if err != nil {
			c.Errorf("blobstore Key Gen: %v", idemp)
		}
		if url, err := appimage.ServingURL(c, blobkey, &imgprops); err != nil {
			c.Errorf("Cannot construct EmpLogo ServingURL : %v", idemp)
		} else {
			// Save the image under a unique key, a hash of the image.
			img := &model.Image{
				Data: buf.Bytes(), IdEmp: idemp, IdImg: model.RandId(20),
				Kind: "EmpLogo", Name: imgo.Name, Desc: imgo.Desc,
				Sizepx: 0, Sizepy: 0, Url: imgo.Url, Type: "",
				Sp1: sp1, Sp2: sp2, Sp3: string(blobkey), Sp4: url.String(),
				Np1: 0, Np2: 0, Np3: 0, Np4: 0,
			}

			_, err = model.PutLogo(c, img)
			if err != nil {
				if r.FormValue("tipo") == "async" {
					fmt.Fprintf(w, "<p>'%s'</p>", "No se actualizó el logotipo. Sistema en matenimiento, intente en unos minutos")
				} else {
					tc["Error"] = struct{ Cantsave string }{"cantsave"}
					micrositioTpl.Execute(w, tc)
				}
				return
			}
		}

		/*
			se crea icono
		*/
		val := slogores(c, idemp, 70, 0)
		if val != 0 {
			tc["Error"] = struct{ Cantsave string }{"cantsave"}
			micrositioTpl.Execute(w, tc)
			return
		}

		if r.FormValue("tipo") == "async" {
			fmt.Fprintf(w, "<p></p>")
		} else {
			micrositio(w, r)
		}
		return
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
예제 #8
0
func handleServeImgByIdOrBlob(w http.ResponseWriter, r *http.Request) {
	if r.FormValue("id") != "none" {
		c := appengine.NewContext(r)
		var imgprops image.ServingURLOptions
		imgprops.Secure = true
		imgprops.Size = 400
		imgprops.Crop = false
		if model.ValidID.MatchString(r.FormValue("id")) {
			/* Cuando es un Id normal */
			//c.Infof("Blob : %v", r.FormValue("id"))
			//now := time.Now().Add(time.Duration(model.GMTADJ)*time.Second)
			var timetolive = 900 //seconds
			var b []byte
			var d detalle
			if item, err := memcache.Get(c, "d_"+r.FormValue("id")); err == memcache.ErrCacheMiss {
				oferta, _ := model.GetOferta(c, r.FormValue("id"))
				if oferta.BlobKey != "none" {
					//if now.After(oferta.FechaHoraPub) {
					d.IdEmp = oferta.IdEmp
					d.IdOft = oferta.IdOft
					d.IdCat = oferta.IdCat
					d.Oferta = oferta.Oferta
					d.Empresa = oferta.Empresa
					d.Descripcion = oferta.Descripcion
					d.Enlinea = oferta.Enlinea
					d.Url = oferta.Url
					d.BlobKey = oferta.BlobKey
					//}

					b, _ = json.Marshal(d)
					item := &memcache.Item{
						Key:        "d_" + r.FormValue("id"),
						Value:      b,
						Expiration: time.Duration(timetolive) * time.Second,
					}
					if err := memcache.Add(c, item); err == memcache.ErrNotStored {
						c.Errorf("Memcache.Add d_idoft : %v", err)
					}
				} else {
					w.WriteHeader(http.StatusNotFound)
					return
				}
			} else {
				//c.Infof("memcache retrieve d_idoft : %v", r.FormValue("id"))
				if err := json.Unmarshal(item.Value, &d); err != nil {
					c.Errorf("Unmarshaling ShortLogo item: %v", err)
					http.Error(w, err.Error(), http.StatusInternalServerError)
					w.WriteHeader(http.StatusNotFound)
					return
				}
			}
			blobstore.Send(w, d.BlobKey)
			/*
				if url, err := image.ServingURL(c, d.BlobKey, &imgprops); err != nil {
					c.Errorf("Cannot construct ServingURL : %v", r.FormValue("id"))
					blobstore.Send(w, d.BlobKey)
				} else {
					http.Redirect(w, r, url.String(), http.StatusFound)
				}
			*/
		} else {
			/* Cuando es un BlobKey */
			//c.Infof("Blob : %v", r.FormValue("id"))
			blobstore.Send(w, appengine.BlobKey(r.FormValue("id")))
			/*
				if url, err := image.ServingURL(c, appengine.BlobKey(r.FormValue("id")), &imgprops); err != nil {
					c.Infof("Cannot construct ServingURL : %v", r.FormValue("id"))
					blobstore.Send(w, appengine.BlobKey(r.FormValue("id")))
				} else {
					http.Redirect(w, r, url.String(), http.StatusFound)
				}
			*/
		}
	}
}
예제 #9
0
func handleUpload(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	var out OfImg
	blobOpts := blobstore.UploadURLOptions{
		MaxUploadBytesPerBlob: 1048576,
	}
	out.Status = "invalidId"
	out.IdBlob = ""
	if _, ok := sess.IsSess(w, r, c); ok {
		blobs, form, err := blobstore.ParseUpload(r)
		file := blobs["image"]
		out.IdBlob = string(file[0].BlobKey)
		out.IdOft = form.Get("IdOft")
		if err != nil {
			out.Status = "invalidUpload"
			berr := blobstore.Delete(c, file[0].BlobKey)
			model.Check(berr)
		} else {
			oferta, _ := model.GetOferta(c, out.IdOft)
			if oferta.IdEmp == "none" {
				out.Status = "invalidUpload"
				berr := blobstore.Delete(c, file[0].BlobKey)
				model.Check(berr)
			} else {
				out.Status = "ok"
				if len(file) == 0 {
					out.Status = "invalidUpload"
					berr := blobstore.Delete(c, file[0].BlobKey)
					model.Check(berr)
				} else {
					var oldblobkey = oferta.BlobKey
					oferta.BlobKey = file[0].BlobKey
					out.IdOft = oferta.IdOft

					// Se crea la URL para servir la oferta desde el CDN, si no se puede
					var imgprops image.ServingURLOptions
					imgprops.Secure = true
					imgprops.Size = 400
					imgprops.Crop = false
					if url, err := image.ServingURL(c, oferta.BlobKey, &imgprops); err != nil {
						c.Errorf("Cannot construct ServingURL : %v", oferta.IdOft)
						oferta.Codigo = ""
					} else {
						oferta.Codigo = url.String()
					}

					err = model.PutOferta(c, oferta)
					if err != nil {
						out.Status = "invalidUpload"
						berr := blobstore.Delete(c, file[0].BlobKey)
						model.Check(berr)
					}
					/*
						Se borra el blob anterior, porque siempre crea uno nuevo
						No se necesita revisar el error
						Si es el blobkey = none no se borra por obvias razones
						Se genera una sesion nueva de upload en caso de que quieran
						cambiar la imágen en la misma pantalla. Esto es debido a que
						se utiliza un form estático con ajax
					*/
					if oldblobkey != "none" {
						blobstore.Delete(c, oldblobkey)
						UploadURL, err := blobstore.UploadURL(c, "/r/ofimgup", &blobOpts)
						out.UploadURL = UploadURL.String()
						if err != nil {
							out.Status = "uploadSessionError"
						}
					}
				}
			}
		}
	}
	w.Header().Set("Content-Type", "application/json")
	b, _ := json.Marshal(out)
	w.Write(b)
}