Esempio n. 1
0
/*
 * Handle uploading images
 */
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		return
	}

	f, fHeader, err := r.FormFile("image")
	checkError(err)
	defer f.Close()

	// check file extension
	fileName := strings.TrimSpace(fHeader.Filename)
	fileType := strings.ToLower(fileName[len(fileName)-3:])
	if fileType != "png" && fileType != "jpg" {
		panic(os.NewError("Invalid file type."))
	}

	t, err := os.Create(UploadDir + fileName)
	checkError(err)
	defer t.Close()

	_, e := io.Copy(t, f)
	checkError(e)

	// JSON response
	jsonResponse, _ := json.MarshalForHTML(&UploadResult{Image: fileName, Error: false, Message: "Image uploaded."})
	fmt.Fprint(w, string(jsonResponse))
}
Esempio n. 2
0
/*
 * Handle uploading errors
 */
func uploadErrorHandler(fn http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if e, ok := recover().(os.Error); ok {
				jsonResponse, _ := json.MarshalForHTML(&UploadResult{Image: "", Error: true, Message: e.String()})
				fmt.Fprint(w, string(jsonResponse))
			}
		}()
		fn(w, r)
	}
}
Esempio n. 3
0
func (j *JsonPOutputWriter) WriteJson(m map[string]string) {
	(*(j.w)).Header().Add("Content-Type", "application/json")
	m["requestId"] = fmt.Sprintf("%d", j.requestId)
	encoded, e := json.MarshalForHTML(m)
	if e != nil {
		(*(j.w)).Write([]byte("An error occurred while marshalling the following JSON:"))
		(*(j.w)).Write([]byte(e.String()))
		return
	}

	//	(*(j.w)).Write([]byte("<script type=\"text/javascript\">" + j.jsonPCallback + "("))
	(*(j.w)).Write(encoded)
	//	(*(j.w)).Write([]byte(");</script>\n"))
}
Esempio n. 4
0
/*
 * Create vector and save to file
 */
func saveVectorHandler(w http.ResponseWriter, r *http.Request) {
	vectorName := r.FormValue("vectorName")
	imageName := r.FormValue("image")
	radius, err := strconv.Atoi(r.FormValue("vectorRadius"))
	checkError(err)
	vectorRings, err := strconv.Atoi(r.FormValue("vectorRings"))
	checkError(err)
	ringSizeInc, err := strconv.Atoi(r.FormValue("ringSizeInc"))
	checkError(err)
	vecX, err := strconv.Atoi(r.FormValue("vecX"))
	checkError(err)
	vecY, err := strconv.Atoi(r.FormValue("vecY"))
	checkError(err)

	// open input file
	inputFile, err := os.OpenFile(UploadDir+imageName, os.O_RDONLY, 0666)
	checkError(err)
	defer inputFile.Close()

	// create output file
	outputFile, err := os.OpenFile(VectorDir+vectorName, os.O_CREATE|os.O_WRONLY, 0666)
	checkError(err)
	defer outputFile.Close()

	// decode png image
	inputImage, _, err := image.Decode(inputFile)
	checkError(err)
	rgbaInput := rgba(inputImage)

	// create vector
	vectorParams := RingVectorParameters{
		Radius:    radius,
		Count:     vectorRings,
		RadiusInc: ringSizeInc}
	ringVector := NewRingVector(vectorParams)
	ringVector.LoadData(rgbaInput, vecX, vecY)

	// save into file
	encoder := gob.NewEncoder(outputFile)
	e := encoder.Encode(ringVector)
	checkError(e)

	jsonResponse, _ := json.MarshalForHTML(&UploadResult{Image: vectorName, Error: false, Message: "Saved."})
	fmt.Fprint(w, string(jsonResponse))
}
Esempio n. 5
0
/*
 * Hub for processing work
 */
func hub() {
	for {
		work := <-workChan

		log.Println("Work started.")

		work.conn.Write([]byte("0.01"))

		err := process(work.input, work.conn, work.stopCh)

		var response []byte
		if err == nil {
			response, err = imageToBase64(ResultDir + work.input.Image)
		}
		if err != nil {
			response, _ = json.MarshalForHTML(&UploadResult{Image: "", Error: true, Message: err.String()})
		}

		work.conn.Write(response)
		log.Println("Work finished.")
	}
}
Esempio n. 6
0
// Web interface
func (db *Database) Serve() {
	web.Get("/patches.js", func(w *web.Context) { // TODO: accept arguments to filter
		query := db.query("SELECT rom_address,rom_before,rom_after, cpu_address,value,compare, title,game.name FROM patch,code,effect,game WHERE patch.code_id=code.id AND code.effect_id=effect.id AND effect.game_id=game.id;") // TODO: get effect,game,cart

		w.SetHeader("Content-Type", "text/javascript", false)
		w.WriteString("var PATCHES = [\n")

		for query.Next() {
			var r struct {
				RomAddress int    "romAddress"
				RomBefore  string "romBefore"
				RomAfter   string "romAfter"
				CpuAddress int    "cpuAddress"
				Value      int    "value"
				Compare    *int   "compare"
				Title      string "title"
				GameName   string "gameName"
			}

			r.Compare = new(int)

			err := query.Scan(&r.RomAddress, &r.RomBefore, &r.RomAfter, &r.CpuAddress, &r.Value, &r.Compare, &r.Title, &r.GameName)
			if err != nil {
				panic(fmt.Sprintf("failed to Scan: %s", err))
			}
			// TODO: use JSON module, avoid XSS
			html, err2 := json.MarshalForHTML(r)

			if err2 != nil {
				panic(fmt.Sprintf("failed to marshal: %s", err2))
			}

			w.Write(html)
			w.WriteString(",\n")
		}
		w.WriteString("]\n")
	})

	web.Get("/games.js", func(w *web.Context) {
		w.SetHeader("Content-Type", "text/javascript", false)
		w.WriteString("[\n")

		//query := db.query("SELECT game.id,game.name,game.galoob_name,game.galoob_id, COUNT(effect.id) FROM game,effect WHERE effect.game_id=game.id GROUP BY game.id ORDER BY COUNT(effect.id) DESC;")
		query := db.query("SELECT game.id,game.name,game.galoob_name,game.galoob_id, COUNT(effect.id) FROM game,effect WHERE effect.game_id=game.id GROUP BY game.id ORDER BY game.name;")
		for query.Next() {
			var r struct {
				GameID       int    "id"
				GameName     string "name"
				GameGaloob   string "galoob"
				GameGaloobID string "galoobID"
				EffectCount  int    "effectCount"
			}

			err := query.Scan(&r.GameID, &r.GameName, &r.GameGaloob, &r.GameGaloobID, &r.EffectCount)
			if err != nil {
				panic(fmt.Sprintf("failed to Scan: %s", err))
			}

			html, err2 := json.MarshalForHTML(r)
			if err2 != nil {
				panic(fmt.Sprintf("failed to marshal: %s", err2))
			}
			w.Write(html)
			w.WriteString(",\n")
		}
		w.WriteString("]\n")
	})

	web.Get("/effects/(.*)", func(w *web.Context, gameIDstring string) {
		gameID, err := strconv.Atoi(gameIDstring)
		if err != nil {
			w.WriteString("Invalid game")
			return
		}

		// TODO: get game, all carts, and all codes for all carts
		//query := db.query("SELECT * FROM effect,cart,code WHERE effect.game_id=1 AND cart.game_id=effect.game_id AND code.cart_id=cart.id")

		w.WriteString(fmt.Sprintf("id=%d\n", gameID))
	})

	web.Get("/", func(w *web.Context) {
		root, _ := path.Split(os.Args[0])
		filename := path.Join(root, "..", "genie", "jsdis.html")
		f, err := os.Open(filename, os.O_RDONLY, 0)
		if err != nil {
			panic(fmt.Sprintf("failed to open %s: %s", filename, err))
		}

		io.Copy(w, f)
	})

	web.Get("/favicon.ico", func(w *web.Context) {
		// TODO: real favicon
		w.SetHeader("Content-Type", "image/png", false)
	})

	web.Run("0.0.0.0:9999")
}