Exemplo n.º 1
0
func ShowOfDetalle(w http.ResponseWriter, r *http.Request) {
	now := time.Now().Add(time.Duration(model.GMTADJ) * time.Second)
	var timetolive = 3600 //seconds
	c := appengine.NewContext(r)
	var b []byte
	var d detalle
	var cachename = "d_" + r.FormValue("id")
	c.Infof("cachename %s", cachename)
	if item, err := memcache.Get(c, cachename); err == memcache.ErrCacheMiss {
		oferta, _ := model.GetOferta(c, r.FormValue("id"))
		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
			if oferta.Promocion != "" {
				d.EmpLogo = oferta.Promocion
			} else {
				d.EmpLogo = "http://www.elbuenfin.org/imgs/imageDefault.png"
			}
			d.Enlinea = oferta.Enlinea
			d.Url = oferta.Url
			d.BlobKey = oferta.BlobKey
			d.SrvUrl = oferta.Codigo

			b, _ = json.Marshal(d)
			item := &memcache.Item{
				Key:        "d_" + r.FormValue("id"),
				Value:      b,
				Expiration: time.Duration(timetolive) * time.Second,
			}
			if err := memcache.Set(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 d_idoft : %v", r.FormValue("id"))
		b = item.Value
	}
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Write(b)
}
Exemplo n.º 2
0
func OfShow(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
		oferta, _ := model.GetOferta(c, r.FormValue("IdOft"))
		var id string
		if oferta.IdEmp != "none" {
			id = oferta.IdEmp
		} else {
			id = r.FormValue("IdEmp")
		}
		fd := ofToForm(*oferta)
		empresa, err := u.GetEmpresa(c, id)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		tc["Empresa"] = empresa
		fd.IdEmp = empresa.IdEmp
		oferta.Empresa = empresa.Nombre
		fd.Categorias = model.ListCat(c, oferta.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)
	}
}
Exemplo n.º 3
0
/*
	Se remueve una palabra de la oferta sólamente
*/
func DelWord(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	var out Word
	out.Token = strings.ToLower(r.FormValue("token"))
	out.Id = r.FormValue("id")
	oferta, _ := model.GetOferta(c, out.Id)
	if oferta.IdEmp != "none" {
		err := model.DelOfertaPalabra(c, out.Id, out.Token)
		if err != nil {
			out.Status = "writeErr"
		} else {
			out.Status = "ok"
		}
		out.Id = "none"
	} else {
		out.Status = "notFound"
	}

	w.Header().Set("Content-Type", "application/json")
	b, _ := json.Marshal(out)
	w.Write(b)
}
Exemplo n.º 4
0
func AddWord(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	var out Word
	out.Token = r.FormValue("token")
	out.Id = r.FormValue("id")
	if model.ValidSimpleText.MatchString(out.Token) {
		tokens := strings.Fields(r.FormValue("token"))
		oferta, _ := model.GetOferta(c, out.Id)
		if len(tokens) > 0 {
			for _, v := range tokens {
				if oferta.IdEmp != "none" {
					var palabra model.OfertaPalabra
					palabra.IdOft = out.Id
					palabra.IdEmp = oferta.IdEmp
					palabra.Palabra = strings.ToLower(v)
					palabra.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)
					err := oferta.PutOfertaPalabra(c, &palabra)
					if err != nil {
						out.Status = "writeErr"
					} else {
						out.Status = "ok"
					}
				} else {
					out.Status = "notFound"
				}
			}
		} else {
			out.Status = "invalidText"
		}
	} else {
		out.Status = "invalidText"
	}

	w.Header().Set("Content-Type", "application/json")
	b, _ := json.Marshal(out)
	w.Write(b)
}
Exemplo n.º 5
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
}
Exemplo n.º 6
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
	}
}
Exemplo n.º 7
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)
				}
			*/
		}
	}
}
Exemplo n.º 8
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)
}