Exemple #1
0
func micrositio(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)
		emp, err := u.GetEmpresa(c, r.FormValue("IdEmp"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		} else {
			img := model.GetLogo(c, r.FormValue("IdEmp"))
			if img == nil {
				img = new(model.Image)
				img.IdEmp = emp.IdEmp
			}
			fd := imgToForm(*img)
			tc := make(map[string]interface{})
			tc["Sess"] = s
			tc["Empresa"] = emp
			tc["FormData"] = fd
			micrositioTpl.Execute(w, tc)
		}
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Exemple #2
0
func modData(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)
		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")
		name := r.FormValue("Name")
		desc := r.FormValue("Desc")
		url := r.FormValue("Url")
		sp1 := r.FormValue("Sp1")
		sp2 := r.FormValue("Sp2")

		//	key := datastore.NewKey(c, "EmpLogo", r.FormValue("id"), 0, nil)
		//	im := new(model.Image)
		// Save the image under a unique key, a hash of the image.
		imgo = &model.Image{
			Data: imgo.Data, IdEmp: idemp, IdImg: imgo.IdImg,
			Kind: "EmpLogo", Name: name, Desc: desc,
			Sizepx: 0, Sizepy: 0, Url: url, Type: "",
			Sp1: sp1, Sp2: sp2, Sp3: imgo.Sp3, Sp4: imgo.Sp4,
			Np1: 0, Np2: 0, Np3: 0, Np4: 0,
		}
		_, err = model.PutLogo(c, imgo)
		if err != nil {
			tc["Error"] = struct{ Cantsave string }{"cantsave"}
			micrositioTpl.Execute(w, tc)
			return
		}

		micrositio(w, r)
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
func ShowMicrositio(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	var timetolive = 7200 //seconds
	c := appengine.NewContext(r)
	var b []byte
	var m micrositio
	cachename := "m_" + r.FormValue("id")
	if item, err := memcache.Get(c, cachename); err == memcache.ErrCacheMiss {
		if e := model.GetEmpresa(c, r.FormValue("id")); e != nil {
			m.IdEmp = e.IdEmp
			m.Name = e.Nombre
			if imgo := model.GetLogo(c, r.FormValue("id")); imgo != nil {
				m.IdImg = imgo.IdImg
				m.Url = imgo.Url
				m.Sp1 = imgo.Sp1
				m.Sp2 = imgo.Sp2
				m.Sp4 = imgo.Sp4
				m.Desc = imgo.Desc
			}
		}

		b, _ = json.Marshal(m)
		item := &memcache.Item{
			Key:        cachename,
			Value:      b,
			Expiration: time.Duration(timetolive) * 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)
			}
		} else {
			c.Infof("memcached %v", cachename)
		}
	} else {
		//c.Infof("memcache retrieve m_idoft : %v", r.FormValue("id"))
		b = item.Value
	}
	w.Write(b)
}
Exemple #4
0
func UpdateServingUrlLogo(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	const batch = 200
	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
		}

		//Oferta.Promocion es URL s180
		//Oferta.Descuento es URL s70
		e.Promocion = ""
		e.Descuento = ""
		emplogo := model.GetLogo(c, e.IdEmp)
		if emplogo != nil {
			// Tenga lo que tenga, se pasa Sp4 a Oferta.Promocion
			if emplogo.Sp4 != "" {
				e.Promocion = emplogo.Sp4
				e.Descuento = strings.Replace(emplogo.Sp4, "s180", "s70", 1)
			}
			//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("PutOferta(); Error al intentar actualizar oferta : %v", e.IdOft)
			}
		}

	}
	c.Infof("UpdateServingLogo() Pagina: %d, actualizados: %d, del %d al %d", page, n, offset, offset+n)
	return
}
Exemple #5
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
	}
}
Exemple #6
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)
	}
}
Exemple #7
0
// Resize only if picture from EmpLogo is more than 80 pix width
// If resize, save image to entity king ShortLogo and stream
// If no resize is necesary, save to entity ShortLogo and stream
func rslogo(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if r.Method == "GET" {
		sf, _ := strconv.Atoi(r.FormValue("s"))
		force, _ := strconv.Atoi(r.FormValue("force"))
		// Check for shortlogo
		var simg model.Image
		simg.Kind = "ShortLogo"
		if r.FormValue("IdEmp") != "" {
			simg.IdEmp = r.FormValue("IdEmp")
		} else {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		if force != 1 {
			shortlogo, _ := model.GetShortLogo(c, r.FormValue("IdEmp"))

			// Stream short logo if already exists
			if shortlogo != nil {
				w.Header().Set("Content-type", "image/jpeg")
				w.Write(shortlogo.Data)

				/*
					m, _, err := image.Decode(bytes.NewBuffer(shortlogo.Data))
					model.Check(err)
					w.Header().Set("Content-type", "image/jpeg")
					jpeg.Encode(w, m, nil)
				*/

				return
			}
		}

		// Process biglogo if shortlogo doesn't exists
		// Save and Stream new shortlogo
		biglogo := model.GetLogo(c, r.FormValue("IdEmp"))
		if biglogo == nil {
			// No such imageb
			w.WriteHeader(http.StatusNotFound)
			return
		}

		i, _, err := image.Decode(bytes.NewBuffer(biglogo.Data))
		if err != nil {
			// ERR_BADFORMAT
			w.WriteHeader(http.StatusNotFound)
			return
		}

		const max = 70
		if sf == 0 {
			// 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)
			} else {
				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)
			}
		} else {
			// We aim for a resize by ratio.
			b := i.Bounds()
			h := b.Dy()
			w := b.Dx()
			if sf > 0 && sf <= 2 {
				h = h * sf
				w = w * sf
			} else if sf < 0 && sf > -1 {
				sf = (sf * 2) + sf
				h = h * (1 / sf)
				w = w * (1 / sf)
			}
			i = resize.Resize(i, i.Bounds(), w, h)
		}

		// Encode as a new JPEG image.
		var buf bytes.Buffer
		err = jpeg.Encode(&buf, i, nil)
		if err != nil {
			// ERR_FAIL_ENCODE
			w.WriteHeader(http.StatusNotFound)
			return
		}

		// Save the image under a unique key, a hash of the image.
		simg.IdImg = model.RandId(20)
		simg.Data = buf.Bytes()
		simg.Name = biglogo.Name
		simg.Desc = biglogo.Desc
		simg.Sizepx = max
		simg.Sizepy = 0
		simg.Url = biglogo.Url
		simg.Type = "jpeg"
		simg.Sp1 = biglogo.Sp1
		simg.Sp2 = biglogo.Sp2
		simg.Sp3 = biglogo.Sp3
		simg.Sp4 = biglogo.Sp4
		simg.Np1 = biglogo.Np1
		simg.Np2 = biglogo.Np2
		simg.Np3 = biglogo.Np3
		simg.Np4 = biglogo.Np4

		_, err = model.PutLogo(c, &simg)
		if err != nil {
			// ERR_DATASTORE
			// Don't return, stream image either way
		}
		w.Header().Set("Content-type", "image/jpeg")
		w.Write(simg.Data)
		/*
			m, _, err := image.Decode(bytes.NewBuffer(simg.Data))
			model.Check(err)
			w.Header().Set("Content-type", "image/jpeg")
			jpeg.Encode(w, m, nil)
		*/
	}
}
Exemple #8
0
func slogores(c appengine.Context, id string, max int, sf int) int {
	var simg model.Image
	// Process biglogo if shortlogo doesn't exists
	// Save and Stream new shortlogo
	biglogo := model.GetLogo(c, id)
	if biglogo == nil {
		// No such imageb
		return -1
	}

	i, _, err := image.Decode(bytes.NewBuffer(biglogo.Data))
	if err != nil {
		// ERR_BADFORMAT
		return -1
	}

	if sf == 0 {
		// We aim for less than 80 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)
		} else {
			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)
		}
	} else {
		// We aim for a resize by ratio.
		b := i.Bounds()
		h := b.Dy()
		w := b.Dx()
		if sf > 0 && sf <= 2 {
			h = h * sf
			w = w * sf
		} else if sf < 0 && sf > -1 {
			sf = (sf * 2) + sf
			h = h * (1 / sf)
			w = w * (1 / sf)
		}
		i = resize.Resize(i, i.Bounds(), w, h)
	}

	// Encode as a new JPEG image.
	var buf bytes.Buffer
	err = jpeg.Encode(&buf, i, nil)
	if err != nil {
		// ERR_FAIL_ENCODE
		return -1
	}

	// Save the image under a unique key, a hash of the image.
	shortlogo, _ := model.GetShortLogo(c, id)
	simg.Kind = "ShortLogo"
	if shortlogo != nil {
		simg.IdImg = shortlogo.IdImg
	} else {
		simg.IdImg = model.RandId(20)
	}
	simg.IdEmp = id
	simg.Data = buf.Bytes()
	simg.Name = biglogo.Name
	simg.Desc = biglogo.Desc
	simg.Sizepx = max
	simg.Sizepy = 0
	simg.Url = biglogo.Url
	simg.Type = "jpeg"
	simg.Sp1 = biglogo.Sp1
	simg.Sp2 = biglogo.Sp2
	simg.Sp3 = biglogo.Sp3
	simg.Sp4 = biglogo.Sp4
	simg.Np1 = biglogo.Np1
	simg.Np2 = biglogo.Np2
	simg.Np3 = biglogo.Np3
	simg.Np4 = biglogo.Np4

	_, err = model.PutLogo(c, &simg)
	if err != nil {
		return -1
	}
	return 0
}
Exemple #9
0
/*
 * La idea es hacer 60 cachés al azar con un tiempo de vida de 30 min
 * Cada que se muere un memcache se genera otro carrousel al azar de logos
 */
func carrVip(w http.ResponseWriter, r *http.Request) {
	//w.Header().Set("Content-Type", "application/json")
	c := appengine.NewContext(r)
	var timetolive = 21600 //seconds
	var b []byte
	var nn int = 50 // tamaño del carrousel

	IdLogosAncla := []string{
		"afrbeabbsoun", "ajaypemavzqs", "aqdproooubeb", "axmtchkgntqa", "banfudbpxttk", "bbyjbxwllnot",
		"bcpybsfpqkyj", "bcyzkjnscmsa", "bdtnmqyhyfyozomrnzph", "bjrnqvqvanng", "bpskvtygscll", "btolawfglrev",
		"bznstwsghejw", "ckhvjnuhsirb", "clwbsiushkhl", "clwzzrlbzgbg", "cmkbjdkrsfar", "coabzptlaxhi",
		"coobaqzhxdrd", "cosujgucetkx", "cyjjbbqeyyxj", "davxbehjmylj", "ddsxxqlhrocr", "dgskbfuklwwg",
		"dgwhvqitwbrd", "dlqhkxmdteyc", "dpnbolxpcuutajfsawqq", "dqshocyjglpi", "dtfebqedzafe", "dtzlczahgoay",
		"dwraooewawnd", "dxleffzopmgc", "elffrufpqqnk", "eltkpudzdyzv", "eoorbeebakwo", "eoqiiyllvoyy",
		"eqbrrctlmnji", "ereutfijvbdk", "fbipqwghxyqn", "fciaeqiydhmg", "ffcptezgpzuz", "fgdcgoolotfu",
		"fipodgnklfxw", "fjmynhyqzyco", "flvruxapdrvf", "fnlgegkxobct", "fstavhmylxna", "gigjbmtrfgcq",
		"gimpcbbzwpdo", "giwhgatienqg", "gkunxsbitdar", "guwnmehixcio", "gvmnhhxyyvoa", "gzjvxnsoadde",
		"hazclayygxsd", "hiccgfmydknt", "hiqsxpzvvyep", "hitddymdmlbz", "hlhubhoabfts", "hsdmdencybqx",
		"htxzwutwoldy", "hztwbvuqyhhr", "ifawjhvuxmln", "igqublscrfnw", "inicdtrvdbuu",
		"iojrkrqnssmq", "irbuuznbxkyx", "ithlfidnvvdj", "jdulbkmxkbfo", "jnehzkrlwbas", "jpifahhoiito",
		"jvzrhlgmfqdn", "jxdfxhhwlppd", "jxltschjycda", "jzqmgcgwibnm", "jzxydtrpesdo", "kaatvffbmhmw",
		"kajbzibavvem", "katnptaevhcg", "kboinbsianoz", "kfkxltlxsjav", "kigufrjgvprg", "kozamniymubo",
		"kureyuhpuzmh", "kvdsuecjuzpa", "kwcjatzshcnm", "kzatdyhjjaon", "laypeqtkfwqb", "lbwcloputhub",
		"lfxnzkglivdj", "lhbhcpqvpbjg", "lhcmqxlvmlct", "lhcmqxlvmlct", "lvsxoqzuzhioscvnkeqm", "mboiiylxhjfq",
		"mekoydpdebln", "mfdacfcuspbs", "mfetisvbsuqm", "mkrudjzstfvj", "mleqgnabuamf", "mmpmbaizdfwi",
		"mohxswriqvcf", "mviwuqnfkfip", "mxpxsuzdxyys", "ncerycvfbkfy", "nchispndxekk", "nfbtxljjgjpc",
		"nfnwaesakflc", "nimegsoikwnd", "nyekuvgpyifi", "nznfaeusafdq", "oagsuhzmspyg", "ocfaouprrjbj",
		"ogxezjvtxztc", "oqafbqtiykbq", "otvgfxnjkpkn", "ouqthztwmxzp", "oxuwenrqyhmp", "pbivvoktfyrf",
		"phzhbszgqkdh", "pkiebfwndinh", "pmehpruqxthf", "pntfrjobyvrw", "pvtxrqgtacmj", "pwkdwgitftot",
		"qivckizmfrwc", "qpklccwwjweg", "qrtnxlsshxdl", "qstrhlhbyrfq", "qthwgsxmsvyi", "qvesdexkqwlv",
		"qwwkhqzktxne", "qxwscvqlsnqe", "rdaipeoorxnt", "rpdsiutntufn", "rukvnnasffbs", "rwibdtugdqgp",
		"sackvjpqjnct", "sbtaodpaaqbk", "serkxrgdhdtw", "sjgnlwrvavvs", "spvtkggmwlno", "srjdftfhwnqo",
		"suweumxmkvxh", "swekknkrttah", "temtpvqbphan", "teykipsvfvge", "tjyhgtnayckz", "tkjqjydmxqxcohuisoso",
		"tnqclfscvvsl", "tpurwfuamaaq", "trochfcbwcah", "tuchdnwrfgtu", "txwhffbtewxh", "ubqpnedgofvj",
		"uczclvkoruhi", "udjsipdwnxpo", "ujhjyjidvwxo", "ujxgoasxoxvi", "umuapgnspxut", "usmtmmgylukp",
		"utnhohgsconp", "uzemszdmnwqj", "uztaemonqiqh", "vfxflxvansqb", "vodxmryolyvj", "vssywdcopvfm",
		"wcetuytvjutx", "wlvjthqzjotr", "wlwmwfkaggga", "wqattzlwokhr", "wqrhohwwgozv", "wsdazclxzvln",
		"wvbxsssbpboa", "wxojqleuyakb", "wzcnglhfhkmb", "xbgjnhvzjzoc", "xchgjfcxttqx", "xcueqcjrzeiw",
		"xgpmynrbxcwe", "xhjfujaiiexf", "xjovgmvlwbhe", "xjtrjnwgwbno", "xndyfhccdyaj", "xxeonjjgijyq",
		"xzugawmatvnt", "ydnewcrsxedt", "yelkvkwztdzo", "ymbhuifsbybc", "ynayolstydlc", "yndkmpybttwm",
		"yorgmcojckqn", "yqbkghxzqfbx", "yqzmfhqpxmma", "ywtpdkephhyq", "yzqnecpcshsy", "zwmwzvmmhgkb"}

	var logos [50]carrst
	hit := rand.Intn(nn)
	cachename := "carrvip_" + strconv.Itoa(hit)
	if item, err := memcache.Get(c, cachename); err == memcache.ErrCacheMiss {
		n := len(IdLogosAncla)
		offset := 0
		if n > nn {
			offset = rand.Intn(n - nn)
		} else {
			nn = n
		}
		slice := IdLogosAncla[offset : offset+nn]
		var ii int = 0
		for _, idemp := range slice {
			lgo := model.GetLogo(c, idemp)
			if lgo != nil {
				if lgo.IdEmp != "" {
					logos[ii].Name = lgo.Name
					logos[ii].Url = lgo.Sp4
					ii = ii + 1
				}
			}
		}

		nn = len(logos)
		b, _ = json.Marshal(logos)
		item := &memcache.Item{
			Key:        cachename,
			Value:      b,
			Expiration: time.Duration(timetolive) * time.Second,
		}
		if err := memcache.Add(c, item); err == memcache.ErrNotStored {
			//c.Errorf("memcache.Add %v : %v", cachename, err)
			if err := memcache.Add(c, item); err == memcache.ErrNotStored {
				c.Errorf("Memcache.Add %v : %v", cachename, err)
			} else {
				c.Infof("memcached %v", cachename)
			}
		} else {
			c.Infof("memcached %v", cachename)
		}
	} else {
		if err := json.Unmarshal(item.Value, &logos); err != nil {
			c.Errorf("Memcache Unmarshalling %v : %v", cachename, err)
		}
		nn = len(logos)
	}

	tpl, _ := template.New("Carr").Parse(cajaTpl)
	tn := rand.Perm(nn)
	var ti carrst
	for i, _ := range tn {
		ti.Name = logos[tn[i]].Name
		ti.Url = strings.Replace(logos[tn[i]].Url, "s180", "s70", 1)
		if ti.Url != "" {
			//b, _ := json.Marshal(ti)
			//w.Write(b)
			tpl.Execute(w, ti)
		}
		if i >= nn {
			break
		}
	}
}