Пример #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)
	}
}
Пример #2
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)
		*/
	}
}
Пример #3
0
func Registrar(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	s, ok := sess.IsSess(w, r, c)
	if ok {
		http.Redirect(w, r, "/r/cta", http.StatusFound)
		return
	}
	fd, valid := ctaForm(w, r, s, true, registroTpl)
	if valid {
		u, err := model.GetCta(c, fd.Email)
		ctaFill(r, u)
		if err != nil {
			// No hay Cuenta registrada
			u.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)
			u.Status = false

			// Generar código de confirmación distindo cada vez. Md5 del email + fecha-hora
			h := md5.New()
			io.WriteString(h, fmt.Sprintf("%s%s%s%s", time.Now().Add(time.Duration(model.GMTADJ)*time.Second), u.Email, u.Pass, model.RandId(12)))
			u.CodigoCfm = fmt.Sprintf("%x", h.Sum(nil))
		}

		//Si hay estatus es que ya existe
		if u.Status == false {

			// Se agrega la cuenta sin activar para realizar el proceso de código de confirmación
			if u, err = model.PutCta(c, u); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			/* No se ha activado, por tanto se inicia el proceso de código de verificación */
			m := urlCfm{
				Md5:       u.CodigoCfm,
				Nombre:    u.Nombre,
				Email:     u.Email,
				FechaHora: time.Now().Add(time.Duration(model.GMTADJ) * time.Second),
				Llave:     u.Key(c).Encode(),
				AppId:     appengine.AppID(c),
			}
			var hbody bytes.Buffer
			var sender string
			if appengine.AppID(c) == "ebfmxorg" {
				sender = "El Buen Fin <*****@*****.**>"
			} else {
				sender = "El Buen Fin <*****@*****.**>"
			}
			// Envia código activación
			if err := mailActivationCodeTpl.Execute(&hbody, m); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
			if MailServer == "gmail" {
				msg := &mail.Message{
					Sender:   sender,
					To:       []string{m.Email},
					Subject:  "Codigo de Activación de Registro / El Buen Fin en línea",
					HTMLBody: hbody.String(),
				}
				if err := mail.Send(c, msg); err != nil {
					/* Problemas para enviar el correo NOK */
					http.Error(w, err.Error(), http.StatusInternalServerError)
					http.Redirect(w, r, "/", http.StatusFound)
				} else {
					if err := activationMessageTpl.ExecuteTemplate(w, "codesend", m); err != nil {
						http.Error(w, err.Error(), http.StatusInternalServerError)
					}
				}
				// ************************************************************
				// Si el hay usuario admin se despliega el código de activación
				// ************************************************************
				if gu := user.Current(c); gu != nil {
					if err := mailActivationCodeTpl.Execute(w, m); err != nil {
						http.Error(w, err.Error(), http.StatusInternalServerError)
					}
				}
			} else {
				client := urlfetch.Client(c)
				url := fmt.Sprintf("http://envia-m.mekate.com.mx/?Sender=%s&Tipo=Codigo&Md5=%s&Llave=%s&Email=%s&Nombre=%s&AppId=ebfmxorg",
					"*****@*****.**",
					m.Md5,
					url.QueryEscape(m.Llave),
					m.Email,
					url.QueryEscape(m.Nombre))
				r1, err := client.Get(url)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				//fmt.Fprintf(w, "HTTP GET returned status %v", r.Status)

				if r1.StatusCode != 200 {
					http.Error(w, "Error de Transporte de Mail", http.StatusInternalServerError)
					return
				} else {
					if err := activationMessageTpl.ExecuteTemplate(w, "codesend", m); err != nil {
						http.Error(w, err.Error(), http.StatusInternalServerError)
					}
				}
				defer r1.Body.Close()
			}
		} else {
			if err := registroErrorTpl.Execute(w, nil); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
		}
	}
}
Пример #4
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
}
Пример #5
0
func pendienteVerifica(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	s, ok := sess.IsSess(w, r, c)
	if ok {
		http.Redirect(w, r, "/r/cta", http.StatusFound)
		return
	}
	fd, valid := ctaForm(w, r, s, true, registroTpl)
	if valid {
		u, err := model.GetCta(c, fd.Email)
		ctaFill(r, u)
		if err != nil {
			// No hay Cuenta registrada
			u.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)
			u.Status = false
			u.CodigoCfm = "Verificar"

			// Generar código de confirmación distindo cada vez. Md5 del email + fecha-hora
			h := md5.New()
			io.WriteString(h, fmt.Sprintf("%s%s%s%s", time.Now().Add(time.Duration(model.GMTADJ)*time.Second), u.Email, u.Pass, model.RandId(12)))
			u.CodigoCfm = fmt.Sprintf("%x", h.Sum(nil))
		}

		u.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)
		u.Status = true
		u.CodigoCfm = "Verificar"
		// Se agrega la cuenta sin activar para realizar el proceso de código de confirmación
		if u, err = model.PutCta(c, u); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		/* Prende la sesion */
		_, _, err = sess.SetSess(w, c, u.Key(c), u.Email, u.Nombre)

		// avisa del éxito independientemente del correo
		if err := activationMessageTpl.ExecuteTemplate(w, "verify", u); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	} else {
		if err := activationMessageTpl.ExecuteTemplate(w, "codeerr", nil); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}