Example #1
0
func realhostname(req *http.Request, c appengine.Context) (string, error) {
	if req.RequestURI == "" {
		return appengine.DefaultVersionHostname(c), nil
	}
	myurl, err := url.Parse(req.RequestURI)
	if err != nil {
		return "", err
	}
	if !myurl.IsAbs() {
		return appengine.DefaultVersionHostname(c), nil
	}
	return myurl.Host, nil
}
Example #2
0
func realInit(w http.ResponseWriter, r *http.Request) bool {
	ctx := appengine.NewContext(r)

	errf := func(format string, args ...interface{}) bool {
		ctx.Errorf("In init: "+format, args...)
		http.Error(w, fmt.Sprintf(format, args...), 500)
		return false
	}

	config, err := serverconfig.Load("./config.json")
	if err != nil {
		return errf("Could not load server config: %v", err)
	}

	// Update the config to use the URL path derived from the first App Engine request.
	// TODO(bslatkin): Support hostnames that aren't x.appspot.com
	scheme := "http"
	if r.TLS != nil {
		scheme = "https"
	}

	baseURL := fmt.Sprintf("%s://%s/", scheme, appengine.DefaultVersionHostname(ctx))
	ctx.Infof("baseurl = %q", baseURL)

	root.mux = http.NewServeMux()
	_, err = config.InstallHandlers(root.mux, baseURL, r)
	if err != nil {
		return errf("Error installing handlers: %v", err)
	}

	return true
}
Example #3
0
func aboutPage(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	fmt.Fprintf(w, "<h1>%v</h1>", appengine.DefaultVersionHostname(c))

	token, expire, _ := appengine.AccessToken(c, "test")
	fmt.Fprintf(w, "<p>AccessToken: %v %v", token, expire)

	fmt.Fprintf(w, "<p>AppID: %v", appengine.AppID(c))
	fmt.Fprintf(w, "<p>FQAppID: %v", c.FullyQualifiedAppID())
	fmt.Fprintf(w, "<p>Go version: %v", runtime.Version())
	fmt.Fprintf(w, "<p>Datacenter: %v", appengine.Datacenter())
	fmt.Fprintf(w, "<p>InstanceID: %v", appengine.InstanceID())
	fmt.Fprintf(w, "<p>IsDevAppServer: %v", appengine.IsDevAppServer())
	fmt.Fprintf(w, "<p>RequestID: %v", appengine.RequestID(c))
	fmt.Fprintf(w, "<p>ServerSoftware: %v", appengine.ServerSoftware())

	sa, _ := appengine.ServiceAccount(c)
	fmt.Fprintf(w, "<p>ServiceAccount: %v", sa)

	keyname, signed, _ := appengine.SignBytes(c, []byte("test"))
	fmt.Fprintf(w, "<p>SignBytes: %v %v", keyname, signed)
	fmt.Fprintf(w, "<p>VersionID: %v", appengine.VersionID(c))

	fmt.Fprintf(w, "<p>Request: %v", r)
	r2 := c.Request()
	fmt.Fprintf(w, "<p>Context Request type/value: %T %v", r2, r2)
}
Example #4
0
//Presentation handles showing page with details about a presentation.
func Presentation(c util.Context) (err error) {
	pk, err := datastore.DecodeKey(c.Vars["id"])
	if err != nil {
		return
	}

	p, err := presentation.GetByKey(pk, c)
	if err != nil {
		return
	}
	as, err := action.GetFor(p, c)
	if err != nil {
		return
	}

	a := prepareActions(as)

	desc := blackfriday.MarkdownCommon(p.Description)

	acts, err := activation.GetForPresentation(pk, c)
	if err != nil {
		return
	}

	util.RenderLayout("presentation.html", "Info o prezentácií", struct {
		P           *presentation.Presentation
		A           map[string][]time.Time
		Desc        template.HTML
		ZeroTime    time.Time
		Domain      string
		Activations []*activation.Activation
		Tz          *time.Location
	}{p, a, template.HTML(desc), time.Date(0001, 01, 01, 00, 00, 00, 00, utc), appengine.DefaultVersionHostname(c), acts, util.Tz}, c, "/static/js/underscore-min.js", "/static/js/presentation.js")
	return
}
Example #5
0
// send uses the Channel API to send the provided message in JSON-encoded form
// to the client identified by clientID.
//
// Channels created with one version of an app (eg, the default frontend)
// cannot be sent on from another version (eg, a backend). This is a limitation
// of the Channel API that should be fixed at some point.
// The send function creates a task that runs on the frontend (where the
// channel was created). The task handler makes the channel.Send API call.
func send(c appengine.Context, clientID string, m Message) {
	if clientID == "" {
		c.Debugf("no channel; skipping message send")
		return
	}
	switch {
	case m.TilesDone:
		c.Debugf("tiles done")
	case m.ZipDone:
		c.Debugf("zip done")
	default:
		c.Debugf("%d tiles", len(m.IDs))
	}
	b, err := json.Marshal(m)
	if err != nil {
		panic(err)
	}
	task := taskqueue.NewPOSTTask("/send", url.Values{
		"clientID": {clientID},
		"msg":      {string(b)},
	})
	host := appengine.DefaultVersionHostname(c)
	task.Header.Set("Host", host)
	if _, err := taskqueue.Add(c, task, sendQueue); err != nil {
		c.Errorf("add send task failed: %v", err)
	}
}
Example #6
0
func handler(w http.ResponseWriter, r *http.Request) {
	img_url := r.FormValue("me")

	if len(img_url) == 0 {
		http.Redirect(w, r, "/index.html", 307)
		return
	}

	c := appengine.NewContext(r)

	c.Infof("Host: %v", appengine.DefaultVersionHostname(c))

	item, err := getCached(c, img_url, do)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "image/jpeg")
	w.Header().Set("Content-Length", strconv.Itoa(len(item.Value)))
	if _, err := w.Write(item.Value); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Example #7
0
func (fi *FileInfo) CreateUrls(r *http.Request, c appengine.Context) {
	u := &url.URL{
		Scheme: r.URL.Scheme,
		Host:   appengine.DefaultVersionHostname(c),
		Path:   "/",
	}
	uString := u.String()
	fi.Url = uString + escape(string(fi.Key)) + "/" +
		escape(string(fi.Name))
	fi.DeleteUrl = fi.Url + "?delete=true"
	fi.DeleteType = "DELETE"
	if imageTypes.MatchString(fi.Type) {
		servingUrl, err := image.ServingURL(
			c,
			fi.Key,
			&image.ServingURLOptions{
				Secure: strings.HasSuffix(u.Scheme, "s"),
				Size:   0,
				Crop:   false,
			},
		)
		check(err)
		fi.ThumbnailUrl = servingUrl.String() + THUMBNAIL_PARAM
	}
}
Example #8
0
func cron(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	q := datastore.NewQuery("asin")

	for t := q.Run(c); ; {
		var x Asin
		_, err := t.Next(&x)
		if err == datastore.Done {
			break
		}
		if err != nil {
			return
		}

		task := taskqueue.NewPOSTTask("/task/fetching", url.Values{
			"asin": {x.Name},
		})

		if !appengine.IsDevAppServer() {
			host := backendName + "." + appengine.DefaultVersionHostname(c)
			task.Header.Set("Host", host)
		}

		if _, err := taskqueue.Add(c, task, ""); err != nil {
			c.Errorf("add fetching task: %v", err)
			http.Error(w, "Error: couldn't schedule fetching task", 500)
			return
		}

		fmt.Fprintf(w, "OK")
	}
}
Example #9
0
func handler(w http.ResponseWriter, r *http.Request) {
	context := appengine.NewContext(r)

	err := parse_chunk_map(context)

	if err != nil {
		log.Fatal("error:", err)
	} else {
		// Determine which file is being requested then construct cached version
		// by collecting the chunks together into one big download.

		w.Header().Set("Content-Type", "application/json")

		var chunkMapWithUrls map[string][]ChunkEntry = make(map[string][]ChunkEntry)

		bigFilename := r.URL.Path

		if len(bigFilename) == 0 {
			log.Fatal(fmt.Sprintf("path \"%s\"", bigFilename))
		} else if bigFilename[0] != '/' {
			log.Fatal(fmt.Sprintf("path \"%s\"", bigFilename))
		} else if strings.Count(bigFilename, "/") != 1 {
			log.Fatal(fmt.Sprintf("path \"%s\"", bigFilename))
		}

		bigFilename = bigFilename[1:]
		chunkArr := chunkMap[bigFilename]

		{
			var chunks []ChunkEntry = make([]ChunkEntry, len(chunkArr))

			for i, chunkEntry := range chunkArr {
				chunks[i] = chunkEntry
				chunks[i].ChunkName = fmt.Sprintf("%s%s/chunk/%s", "http://", appengine.DefaultVersionHostname(context), chunkEntry.ChunkName)
			}

			chunkMapWithUrls[bigFilename] = chunks
		}

		bytes, err := json.MarshalIndent(chunkMapWithUrls, "", "  ")
		if err != nil {
			log.Fatal("error:", err)
		}

		bytes = append(bytes, '\n')

		_, err = w.Write(bytes)
		if err != nil {
			log.Fatal("error:", err)
		}
	}
}
Example #10
0
func (fi *FileInfo) CreateUrls(r *http.Request, c appengine.Context) {
	u := &url.URL{
		Scheme: r.URL.Scheme,
		Host:   appengine.DefaultVersionHostname(c),
		Path:   "/",
	}
	uString := u.String()
	fi.Url = uString + fi.Key
	fi.DeleteUrl = fi.Url
	fi.DeleteType = "DELETE"
	if fi.ThumbnailKey != "" {
		fi.ThumbnailUrl = uString + fi.ThumbnailKey
	}
}
Example #11
0
//Presentations shows listing of presentations in paginated form.
func Presentations(c util.Context) (err error) {
	page, err := strconv.Atoi(c.R.FormValue("p"))
	if err != nil {
		return
	}
	ps, err := presentation.GetListing(page, perPage, c)
	if err != nil {
		return
	}

	type templateData struct {
		P presentation.Presentation
		D template.HTML
	}

	data := make([]templateData, len(ps), len(ps))

	for _, p := range ps {
		data = append(data, templateData{P: *p, D: template.HTML(blackfriday.MarkdownCommon(p.Description))})
	}

	maxPages, err := presentation.PageCount(perPage, c)
	if err != nil {
		return
	}

	c.Infof("Hostname: %v", appengine.DefaultVersionHostname(c))

	util.RenderLayout("index.html", "Zoznam vysielaní", struct {
		Page     int
		MaxPages int
		Data     []templateData
		Domain   string
	}{Page: page, MaxPages: maxPages, Data: data, Domain: appengine.DefaultVersionHostname(c)}, c, "/static/js/index.js")
	return
}
Example #12
0
func getBeardFromUrl(c appengine.Context, key string) (*bytes.Buffer, error) {
	client := urlfetch.Client(c)
	resp, err := client.Get("http://" + appengine.DefaultVersionHostname(c) + "/images/beard.png")

	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	buff := new(bytes.Buffer)
	buff.ReadFrom(resp.Body)

	return buff, nil
}
Example #13
0
func (fi *FileInfo) CreateUrls(r *http.Request, c appengine.Context) {
	u := &url.URL{
		Scheme: r.URL.Scheme,
		Host:   appengine.DefaultVersionHostname(c),
	}
	u.Path = "/" + url.QueryEscape(string(fi.Key)) + "/" +
		url.QueryEscape(string(fi.Name))
	fi.Url = u.String()
	fi.DeleteUrl = fi.Url
	fi.DeleteType = "DELETE"
	if fi.ThumbnailUrl != "" && -1 == strings.Index(
		r.Header.Get("Accept"),
		"application/json",
	) {
		u.Path = "/thumbnails/" + url.QueryEscape(string(fi.Key))
		fi.ThumbnailUrl = u.String()
	}
}
Example #14
0
func handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprintf(w, "<!DOCTYPE html>")
	fmt.Fprintf(w, "<html><head><title>appengineパッケージ</title></head><body>")

	if appengine.IsDevAppServer() {
		// 開発環境
		fmt.Fprintf(w, "開発環境で動作しています。。<br>")
	} else {
		fmt.Fprintf(w, "本番環境で動作しています。<br>")
	}

	c := appengine.NewContext(r)

	fmt.Fprintf(w, "AppID(): %s<br>", appengine.AppID(c))
	fmt.Fprintf(w, "DefaultVersionHostname(): %s<br>", appengine.DefaultVersionHostname(c))

	fmt.Fprintf(w, "VersionID(): %s<br>", appengine.VersionID(c))
	fmt.Fprintf(w, "</body></html>")
}
Example #15
0
func homeHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	data := map[string]string{
		"isDevelopment":   appEngineEnvironment("isDevelopment"),
		"isProduction":    appEngineEnvironment("isProduction"),
		"currentHostname": appengine.DefaultVersionHostname(c),
	}

	tpl, err := ace.Load("base", "inner", &ace.Options{
		BaseDir:       "views",
		DynamicReload: true})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := tpl.Execute(w, data); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
Example #16
0
func requestPay(w http.ResponseWriter, r *http.Request, m map[string]interface{}) {

	lg, b := loghttp.BuffLoggerUniversal(w, r)
	closureOverBuf := func(bUnused *bytes.Buffer) {
		loghttp.Pf(w, r, b.String())
	}
	defer closureOverBuf(b) // the argument is ignored,
	r.Header.Set("X-Custom-Header-Counter", "nocounter")

	protoc := "https://"
	if appengine.IsDevAppServer() {
		protoc = "http://"
	}

	host := appengine.DefaultVersionHostname(appengine.NewContext(r))
	if appengine.IsDevAppServer() {
		host = "not-loclhost"
	}

	confirmURL := fmt.Sprintf("%v%v%v", protoc, host, uriConfirmPayment)
	confirmURL = url.QueryEscape(confirmURL)

	addrURL := fmt.Sprintf("https://%v/api/receive?method=create&address=%v&callback=%v&customsecret=49&api_code=%v",
		blockChainHost, bitCoinAddress, confirmURL, apiKey)

	req, err := http.NewRequest("GET", addrURL, nil)
	lg(err)
	if err != nil {
		return
	}
	bts, inf, err := fetch.UrlGetter(r, fetch.Options{Req: req})
	bts = bytes.Replace(bts, []byte(`","`), []byte(`", "`), -1)

	if err != nil {
		lg(err)
		lg(inf.Msg)
		return
	}

	lg("response body 1:\n")
	lg("%s\n", string(bts))

	lg("response body 2:\n")
	var data1 map[string]interface{}
	err = json.Unmarshal(bts, &data1)
	lg(err)
	lg(stringspb.IndentedDumpBytes(data1))
	// lg("%#v", data1)

	inputAddress, ok := data1["input_address"].(string)
	if !ok {
		lg("input address could not be casted to string; is type %T", data1["input_address"])
		return
	}
	feePercent, ok := data1["fee_percent"].(float64)
	if !ok {
		lg("fee percent could not be casted to float64; is type %T", data1["fee_percent"])
		return
	}

	lg("Input Adress will be %q; fee percent will be %4.2v", inputAddress, feePercent)

}
Example #17
0
func auth(required bool, handler func(*PageRequest) error) http.HandlerFunc {
	// wrap the PageRequest handler in a function to install in the http server
	return func(w http.ResponseWriter, r *http.Request) {
		p := PageRequest{
			id:     requestID(),
			w:      w,
			r:      r,
			c:      appengine.NewContext(r),
			v:      mux.Vars(r),
			m:      make(map[string]interface{}),
			t:      template.New(""),
			render: true,
		}
		// log the request and the working directory
		p.Infof("%s", p.r.URL.Path)
		p.pwd()

		var err error

		// identify the authenticated services of the current user
		p.u = user.Current(p.c)
		p.loginURL, err = user.LoginURL(p.c, r.URL.String())

		if required {
			// direct unauthorized users to login
			if (p.u == nil) && (p.r.URL.Path != "/signin") {
				p.Infof("Redirecting unauthorized user to /")
				http.Redirect(p.w, p.r, "/signin", http.StatusSeeOther)
				return
			}
		}
		// redirect authorized users from "/signin" to "/"
		if (p.u != nil) && (p.r.URL.Path == "/signin") {
			p.Infof("Redirecting authorized user to /")
			http.Redirect(p.w, p.r, "/", http.StatusSeeOther)
			return
		}

		// set some default parameters for the PageRequest
		p.Set("Hostname", appengine.DefaultVersionHostname(p.c))
		p.Set("User", p.u)
		p.Set("LoginURL", p.loginURL)

		// make some functions available to all PageRequests
		funcMap := template.FuncMap{
			"truncate":              templateHelper_truncate,
			"displayDate":           templateHelper_displayDate,
			"markdown":              templateHelper_markdown,
			"DateFormat":            DateFormat,
			"ShortDateFormat":       ShortDateFormat,
			"ScreenNameForUserName": ScreenNameForUserName,
		}
		p.t.Funcs(funcMap)

		// read default layout
		p.t.ParseFiles("templates/page.html", "templates/topbar.html")

		// call the page handler
		p.Infof("Calling request handler")
		err = handler(&p)

		// handle the response
		if err != nil {
			p.Errorf("Error in request handler: %s", err.Error())
			// reuse the template system to display an error page
			p.t = template.New("")
			p.Template("templates/error.html")
			p.Set("Error", err.Error())
			err = p.render_template()
			if err != nil {
				p.Errorf("Error in error handler: %s", err.Error())
				http.Error(p.w, err.Error(), 500)
			}
		} else if p.render {
			p.Infof("Rendering HTML response")
			p.w.Header().Set("Cache-Control", "private, no-cache, no-store, must-revalidate, max-age=0, ") // HTTP 1.1.
			p.w.Header().Set("Pragma", "no-cache")                                                         // HTTP 1.0.
			p.w.Header().Set("Expires", "0")                                                               // Proxies
			err = p.render_template()
			if err != nil {
				p.Errorf("Rendering error: %s", err.Error())
				http.Error(p.w, err.Error(), 500)
			}
		}
		return
	}
}
Example #18
0
func rootURL(c appengine.Context) string {
	return "http://" + appengine.DefaultVersionHostname(c)
}
Example #19
0
func registerHandler(response http.ResponseWriter, request *http.Request) {
	if !(utils.CheckValue(request, KEY_LOGIN, utils.Rule{Min: 3, Max: 100}) &&
		utils.CheckValue(request, KEY_PASSWORD, utils.Rule{Min: 3, Max: 100}) &&
		utils.CheckValue(request, KEY_ALIAS, utils.Rule{Min: 3, Max: 100}) &&
		utils.CheckValue(request, KEY_EMAIL, utils.Rule{Min: 3, Max: 500, Regex: "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$"}) &&
		utils.CheckValue(request, KEY_CAPTCHA_ID, utils.Rule{Min: 1, Max: 100}) &&
		utils.CheckValue(request, KEY_CAPTCHA_VAL, utils.Rule{Min: 1, Max: 100})) {
		http.Error(response, utils.GetLastValidationError().Error(), http.StatusBadRequest)
		return
	}

	context := appengine.NewContext(request)

	query := datastore.NewQuery(model.DB_KIND_USER).
		Filter("Login =", request.FormValue(KEY_LOGIN)).KeysOnly()
	count, err := query.Count(context)
	if count != 0 {
		http.Error(response, ERR_USERNAME_CONFLICT, http.StatusConflict)
		return
	}

	query = datastore.NewQuery(model.DB_KIND_USER).
		Filter("Email =", request.FormValue(KEY_EMAIL)).KeysOnly()
	count, err = query.Count(context)
	if count != 0 {
		http.Error(response, ERR_EMAIL_CONFLICT, http.StatusConflict)
		return
	}

	passed, err := CheckCaptcha(context, request.FormValue(KEY_CAPTCHA_ID), request.FormValue(KEY_CAPTCHA_VAL))
	if !passed {
		if err != nil {
			log.Println(err)
		}
		http.Error(response, ERR_CAPTCHA_NOT_PASS, http.StatusNotAcceptable)
		return
	}

	user := model.User{
		Login:      request.FormValue(KEY_LOGIN),
		Password:   request.FormValue(KEY_PASSWORD),
		Alias:      request.FormValue(KEY_ALIAS),
		Email:      request.FormValue(KEY_EMAIL),
		Verified:   false,
		Registered: time.Now(),
	}
	key, err := datastore.Put(context, datastore.NewIncompleteKey(context, model.DB_KIND_USER, nil), &user)
	if err != nil {
		log.Fatal(err)
		return
	}

	url := "http://" + appengine.DefaultVersionHostname(context) + HANDLER_PATH_CONFIRM + "?" + KEY_USER + "=" + key.Encode()
	msg := &mail.Message{
		Sender:   base.PHLOX_CONNECT_EMAIL,
		To:       []string{request.FormValue(KEY_EMAIL)},
		Subject:  CONFIRM_REGISTRATION,
		HTMLBody: fmt.Sprintf(CONFIRM_MAIL_BODY, url, url),
	}
	err = mail.Send(context, msg)
	if err != nil {
		log.Println(err)
		http.Error(response, fmt.Sprintf(ERR_CANT_SEND_EMAIL, err), http.StatusInternalServerError)
		return
	}

	utils.WriteJsonResponse(response, utils.JSON_RESULT_SUCCESS)
}
Example #20
0
// Default handler
func handler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	// Load db on first request.
	var err error
	err = nil
	startOnce.Do(func() {
		err = start(c)
	})
	if err != nil {
		startOnce = sync.Once{}
		c.Criticalf("unable to load db:" + err.Error())
	}
	if UpdateAt == nil {
		loadWait.Wait()
	}
	if UpdateAt.Before(time.Now()) && !updating {
		updating = true
		update(c)
		updating = false
	}
	var mac string
	var hw *oui.HardwareAddr

	// Prepare the response and queue sending the result.
	res := &Response{}

	defer func() {
		var j []byte
		var err error
		j, err = res.MarshalJSON()
		if err != nil {
			c.Errorf(err.Error())
		}
		w.Write(j)
	}()

	// Set headers
	w.Header().Set("Cache-Control", "public, max-age=86400") // 86400 = 24*60*60
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Expires", UpdateAt.Format(http.TimeFormat))
	w.Header().Set("Last-Modified", db.Generated().Format(http.TimeFormat))

	mac = r.URL.Query().Get("mac")
	if mac == "" {
		mac = strings.Trim(r.URL.Path, "/")
	}
	hw, err = oui.ParseMac(mac)
	if err != nil {
		res.Error = err.Error() + ". Usage 'http://" + appengine.DefaultVersionHostname(c) + "/AB-CD-EF' (dashes can be colons or omitted)."
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	entry, err := db.LookUp(*hw)
	if err != nil {
		if err == oui.ErrNotFound {
			res.Error = "not found in db"
			w.WriteHeader(http.StatusNotFound)
			return
		}
		w.WriteHeader(http.StatusInternalServerError)
		res.Error = err.Error()
		return
	}
	res.Data = entry

}
Example #21
0
func DefaultVersionHostname(ctx netcontext.Context) string {
	return appengine.DefaultVersionHostname(fromContext(ctx))
}
Example #22
0
func AppHostname(c *Context) string {
	if kAppHostname != "" {
		return kAppHostname
	}
	return appengine.DefaultVersionHostname(c.Aec())
}