Ejemplo n.º 1
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)
	}
}
Ejemplo n.º 2
0
// Modifica si hay, Crea si no hay
// Requiere IdEmp. IdOft es opcional, si no hay lo crea, si hay modifica
func OfMod(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		tc := make(map[string]interface{})
		tc["Sess"] = s
		var fd FormDataOf
		var valid bool
		var ofertamod model.Oferta

		if r.FormValue("IdOft") == "new" {
			if empresa, err := u.GetEmpresa(c, r.FormValue("IdEmp")); err != nil {
				http.Redirect(w, r, "/r/le?d=o", http.StatusFound)
			} else {
				tc["Empresa"] = empresa
				fd.IdEmp = empresa.IdEmp
				fd.Empresa = empresa.Nombre
				ofertamod.IdEmp = empresa.IdEmp
				ofertamod.Oferta = "Nueva oferta"
				ofertamod.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)    // 5 horas menos
				ofertamod.FechaHoraPub = time.Now().Add(time.Duration(model.GMTADJ) * time.Second) // 5 horas menos
				ofertamod.Empresa = strings.ToUpper(empresa.Nombre)
				ofertamod.BlobKey = "none"
				o, err := model.NewOferta(c, &ofertamod)
				model.Check(err)
				fd = ofToForm(*o)
				fd.Ackn = "Ok"
			}
		} else {
			/*
			 * Se pide un id oferta que en teoría existe, se consulta y se cambia
			 * Se valida y si no existe se informa un error
			 */
			fd, valid = ofForm(w, r, true)

			ofertamod.IdOft = fd.IdOft
			ofertamod.IdEmp = fd.IdEmp
			ofertamod.IdCat = fd.IdCat
			ofertamod.Oferta = fd.Oferta
			ofertamod.Descripcion = fd.Descripcion
			ofertamod.Enlinea = fd.Enlinea
			ofertamod.Url = fd.Url
			ofertamod.FechaHoraPub = fd.FechaHoraPub
			ofertamod.StatusPub = fd.StatusPub
			//ofertamod.BlobKey = fd.BlobKey
			ofertamod.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)

			oferta, keyOferta := model.GetOferta(c, ofertamod.IdOft)
			if oferta.IdOft != "none" {
				ofertamod.BlobKey = oferta.BlobKey
				ofertamod.Codigo = oferta.Codigo
				empresa, err := u.GetEmpresa(c, ofertamod.IdEmp)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				tc["Empresa"] = empresa
				fd.IdEmp = empresa.IdEmp
				fd.Empresa = empresa.Nombre
				ofertamod.Empresa = strings.ToUpper(empresa.Nombre)
				emplogo := model.GetLogo(c, empresa.IdEmp)
				if emplogo != nil {
					// Tenga lo que tenga, se pasa Sp4 a Oferta.Promocion
					if emplogo.Sp4 != "" {
						ofertamod.Promocion = emplogo.Sp4
						ofertamod.Descuento = strings.Replace(emplogo.Sp4, "s180", "s70", 1)
					}
				}
				// TODO
				// es preferible poner un regreso avisando que no existe la empresa
				if valid {
					// Ya existe
					err := model.PutOferta(c, &ofertamod)
					model.Check(err)

					// Se borran las relaciones oferta-sucursal
					err = model.DelOfertaSucursales(c, oferta.IdOft)
					model.Check(err)

					// Se crea un mapa de Estados para agregar a OfertaEstado
					edomap := make(map[string]string, 32)

					// Se reconstruyen las Relaciones oferta-sucursal con las solicitadas
					idsucs := strings.Fields(r.FormValue("schain"))

					for _, idsuc := range idsucs {
						suc := model.GetSuc(c, u, idsuc, ofertamod.IdEmp)

						lat, _ := strconv.ParseFloat(suc.Geo1, 64)
						lng, _ := strconv.ParseFloat(suc.Geo2, 64)

						var ofsuc model.OfertaSucursal
						ofsuc.IdOft = ofertamod.IdOft
						ofsuc.IdSuc = idsuc
						ofsuc.IdEmp = ofertamod.IdEmp
						ofsuc.Sucursal = suc.Nombre
						ofsuc.Lat = lat
						ofsuc.Lng = lng
						ofsuc.Empresa = ofertamod.Empresa
						ofsuc.Oferta = ofertamod.Oferta
						ofsuc.Descripcion = ofertamod.Descripcion
						ofsuc.Promocion = ofertamod.Promocion
						ofsuc.Descuento = ofertamod.Descuento
						ofsuc.Url = ofertamod.Url
						ofsuc.StatusPub = ofertamod.StatusPub
						ofsuc.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)

						// Se añade el estado de la sucursal al mapa de estados
						edomap[suc.DirEnt] = oferta.IdOft

						errOs := ofertamod.PutOfertaSucursal(c, &ofsuc)
						model.Check(errOs)

					}
					// Se limpia la relación OfertaEstado
					_ = ofertamod.DelOfertaEstado(c)

					// Se guarda la relación OfertaEstado
					errOe := ofertamod.PutOfertaEstado(c, edomap)
					model.Check(errOe)

					var tituloOf string
					tituloOf = ""
					if strings.ToLower(strings.TrimSpace(ofertamod.Oferta)) != "nueva oferta" {
						tituloOf = ofertamod.Oferta
					}
					putSearchData(c, ofertamod.Empresa+" "+tituloOf+" "+ofertamod.Descripcion+" "+r.FormValue("pchain"), keyOferta, oferta.IdOft, ofertamod.IdCat, ofertamod.Enlinea)

					// Se despacha la generación de diccionario de palabras
					// Se agrega pcves a la descripción
					//fmt.Fprintf(w,"http://movil.%s.appspot.com/backend/generatesearch?kind=Oferta&field=Descripcion&id=%s&value=%s&categoria=%s",
					//appengine.AppID(c), keyOferta.Encode(), ofertamod.Descripcion+" "+r.FormValue("pchain"), strconv.Itoa(ofertamod.IdCat))
					//_ = generatesearch(c, keyOferta, ofertamod.Descripcion+" "+r.FormValue("pchain"), ofertamod.IdCat)

					fd = ofToForm(ofertamod)
					fd.Ackn = "Ok"
				}
			} else {
				// no existe la oferta
			}
		}

		fd.Categorias = model.ListCat(c, ofertamod.IdCat)

		/*
		 * Se crea el form para el upload del blob
		 */
		blobOpts := blobstore.UploadURLOptions{
			MaxUploadBytesPerBlob: 1048576,
		}
		uploadURL, err := blobstore.UploadURL(c, "/r/ofimgup", &blobOpts)
		if err != nil {
			serveError(c, w, err)
			return
		}
		fd.UploadURL = strings.Replace(uploadURL.String(), "http", "https", 1)
		//fd.UploadURL = uploadURL
		tc["FormDataOf"] = fd

		ofadmTpl.ExecuteTemplate(w, "oferta", tc)
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}

	/*
	 * FETCH PARA MVBLOB/GENERATE
	 */
	cronsecs := 3600
	cachename := "mvblob_cron"
	if _, err := memcache.Get(c, cachename); err == memcache.ErrCacheMiss {
		slot := strconv.Itoa(cronsecs)
		item := &memcache.Item{
			Key:        cachename,
			Value:      []byte(slot),
			Expiration: time.Duration(cronsecs) * time.Second,
		}
		if err := memcache.Add(c, item); err == memcache.ErrNotStored {
			//c.Errorf("memcache.Add %v : %v", cachename, err)
			if err := memcache.Set(c, item); err == memcache.ErrNotStored {
				c.Errorf("Memcache.Set %v : %v", cachename, err)
			} else {
				c.Infof("memcached %v", cachename)
				mvblobFetch(c)
			}
		} else {
			c.Infof("memcached %v", cachename)
			mvblobFetch(c)
		}
	} else {
		// DO NOTHING
	}
}
Ejemplo n.º 3
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)
}