Example #1
0
func (c *Controller) DeleteLine(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := mustUserID(ctx)
	convoID := pat.Param(ctx, "conversation")
	lineID := pat.Param(ctx, "line")

	if err := c.repo.DeleteLine(userID, convoID, lineID); err != nil {
		panic(err)
	}

	w.WriteHeader(http.StatusNoContent)
}
Example #2
0
File: say.go Project: metcalf/saypi
func (c *Controller) DeleteLine(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := mustUserID(ctx)
	convoID := pat.Param(ctx, "conversation")
	lineID := pat.Param(ctx, "line")

	if err := c.repo.DeleteLine(userID, convoID, lineID); err == errRecordNotFound {
		respond.NotFound(ctx, w, r)
	} else if err != nil {
		respond.InternalError(ctx, w, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
Example #3
0
func bookByISBN(s *mgo.Session) goji.HandlerFunc {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		session := s.Copy()
		defer session.Close()

		isbn := pat.Param(ctx, "isbn")

		c := session.DB("store").C("books")

		var book Book
		err := c.Find(bson.M{"isbn": isbn}).One(&book)
		if err != nil {
			ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
			log.Println("Failed find book: ", err)
			return
		}

		if book.ISBN == "" {
			ErrorWithJSON(w, "Book not found", http.StatusNotFound)
			return
		}

		respBody, err := json.MarshalIndent(book, "", "  ")
		if err != nil {
			log.Fatal(err)
		}

		ResponseWithJSON(w, respBody, http.StatusOK)
	}
}
Example #4
0
func updateBook(s *mgo.Session) goji.HandlerFunc {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		session := s.Copy()
		defer session.Close()

		isbn := pat.Param(ctx, "isbn")

		var book Book
		decoder := json.NewDecoder(r.Body)
		err := decoder.Decode(&book)
		if err != nil {
			ErrorWithJSON(w, "Incorrect body", http.StatusBadRequest)
			return
		}

		c := session.DB("store").C("books")

		err = c.Update(bson.M{"isbn": isbn}, &book)
		if err != nil {
			switch err {
			default:
				ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
				log.Println("Failed update book: ", err)
				return
			case mgo.ErrNotFound:
				ErrorWithJSON(w, "Book not found", http.StatusNotFound)
				return
			}
		}

		w.WriteHeader(http.StatusNoContent)
	}
}
Example #5
0
func deleteBook(s *mgo.Session) goji.HandlerFunc {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		session := s.Copy()
		defer session.Close()

		isbn := pat.Param(ctx, "isbn")

		c := session.DB("store").C("books")

		err := c.Remove(bson.M{"isbn": isbn})
		if err != nil {
			switch err {
			default:
				ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
				log.Println("Failed delete book: ", err)
				return
			case mgo.ErrNotFound:
				ErrorWithJSON(w, "Book not found", http.StatusNotFound)
				return
			}
		}

		w.WriteHeader(http.StatusNoContent)
	}
}
Example #6
0
func (a *API) HandleCard(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	card, err := a.c.GetCard(ctx, pat.Param(ctx, "id"))
	if err != nil {
		JSON(w, http.StatusNotFound, Errors("Card not found"))
		return
	}
	JSON(w, http.StatusOK, card)
}
Example #7
0
func (a *API) HandleSet(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	card, err := a.c.GetSet(ctx, pat.Param(ctx, "id"))

	if err != nil {
		JSON(w, http.StatusNotFound, Errors("Set not found"))
	} else {
		JSON(w, http.StatusOK, card)
	}
}
Example #8
0
func setReadNotifications(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	id := pat.Param(ctx, "id")
	smt, err := database.Prepare("UPDATE notification SET read=? WHERE id=?")
	checkErr(err, "setReadNotifications")
	defer smt.Close()
	_, err = smt.Exec(true, id)
	checkErr(err, "setReadNotifications")
	writeJson(w, ResponseStatus{Status: "ok"})
}
Example #9
0
func bookByISBN(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	isbn := pat.Param(ctx, "isbn")
	for _, b := range bookStore {
		if b.ISBN == isbn {
			jsonOut, _ := json.Marshal(b)
			fmt.Fprintf(w, string(jsonOut))
			return
		}
	}
	w.WriteHeader(http.StatusNotFound)
}
// GET /resources/:id/(relationships/)<resourceType>s
func (res *Resource) toManyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, storage store.ToMany) {
	id := pat.Param(ctx, "id")

	list, err := storage(ctx, id)
	if err != nil && reflect.ValueOf(err).IsNil() == false {
		SendHandler(ctx, w, r, err)
		return
	}

	SendHandler(ctx, w, r, list)
}
// DELETE /resources/:id
func (res *Resource) deleteHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, storage store.Delete) {
	id := pat.Param(ctx, "id")

	err := storage(ctx, id)
	if err != nil && reflect.ValueOf(err).IsNil() == false {
		SendAndLog(ctx, w, r, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
// All HTTP Methods for /resources/:id/<mutate>
func (res *Resource) actionHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, storage store.Get) {
	id := pat.Param(ctx, "id")

	response, err := storage(ctx, id)
	if err != nil && reflect.ValueOf(err).IsNil() == false {
		SendAndLog(ctx, w, r, err)
		return
	}

	SendAndLog(ctx, w, r, response)
}
Example #13
0
func (c *Controller) GetUser(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	id := pat.Param(ctx, "id")
	if id == "" {
		panic("GetUser called without an `id` URL Var")
	}

	if c.getUser(id) != nil {
		w.WriteHeader(204)
	} else {
		respond.NotFound(ctx, w, r)
	}
}
Example #14
0
func (c *Controller) GetLine(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := mustUserID(ctx)
	convoID := pat.Param(ctx, "conversation")
	lineID := pat.Param(ctx, "line")

	line, err := c.repo.GetLine(userID, convoID, lineID)
	if err != nil {
		panic(err)
	}
	if line == nil {
		respond.NotFound(ctx, w, r)
		return
	}

	line.Output, err = c.renderLine(line)
	if err != nil {
		panic(err)
	}

	respond.Data(ctx, w, http.StatusOK, line)
}
Example #15
0
File: say.go Project: metcalf/saypi
func (c *Controller) SetMood(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := mustUserID(ctx)
	name := pat.Param(ctx, "mood")

	var mood Mood
	r.ParseForm()
	err := decoder.Decode(&mood, r.PostForm)
	if err != nil {
		respond.InternalError(ctx, w, err)
		return
	}

	mood.Eyes = strings.Replace(mood.Eyes, "\x00", "", -1)
	mood.Tongue = strings.Replace(mood.Tongue, "\x00", "", -1)

	var uerr usererrors.InvalidParams
	if !(mood.Eyes == "" || utf8.RuneCountInString(mood.Eyes) == 2) {
		uerr = append(uerr, usererrors.InvalidParamsEntry{
			Params:  []string{"eyes"},
			Message: "must be a string containing two characters",
		})
	}

	if !(mood.Tongue == "" || utf8.RuneCountInString(mood.Tongue) == 2) {
		uerr = append(uerr, usererrors.InvalidParamsEntry{
			Params:  []string{"tongue"},
			Message: "must be a string containing two characters",
		})
	}

	if uerr != nil {
		respond.UserError(ctx, w, http.StatusBadRequest, uerr)
		return
	}

	mood.Name = name
	mood.UserDefined = true

	err = c.repo.SetMood(userID, &mood)
	if err == errBuiltinMood {
		respond.UserError(ctx, w, http.StatusBadRequest, usererrors.ActionNotAllowed{
			Action: fmt.Sprintf("update built-in mood %s", name),
		})
		return
	} else if err != nil {
		respond.InternalError(ctx, w, err)
		return
	}

	respond.Data(ctx, w, http.StatusOK, mood)
}
Example #16
0
func (c *Controller) GetMood(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := mustUserID(ctx)
	name := pat.Param(ctx, "mood")

	res, err := c.repo.GetMood(userID, name)
	if err != nil {
		panic(err)
	}
	if res == nil {
		respond.NotFound(ctx, w, r)
		return
	}

	respond.Data(ctx, w, http.StatusOK, res)
}
Example #17
0
func (c *Controller) DeleteMood(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := mustUserID(ctx)
	name := pat.Param(ctx, "mood")

	if err := c.repo.DeleteMood(userID, name); err == errBuiltinMood {
		respond.Error(ctx, w, http.StatusBadRequest, usererrors.ActionNotAllowed{
			Action: fmt.Sprintf("delete built-in mood %s", name),
		})
		return
	} else if err != nil {
		panic(err)
	}

	w.WriteHeader(http.StatusNoContent)
}
Example #18
0
func deleteUsersInterests(ctx context.Context, w http.ResponseWriter, r *http.Request) {

	session, _ := store.Get(r, "session")
	if session.Values["connected"] != true {
		http.Redirect(w, r, "/", http.StatusNetworkAuthenticationRequired)
		return
	}

	id := pat.Param(ctx, "interestid")

	smt, err := database.Prepare("DELETE FROM userinterest WHERE interestid=? AND userid=?")
	checkErr(err, "deleteUsersInterests")
	defer smt.Close()
	_, err = smt.Exec(id, session.Values["UserInfo"].(UserData).Id)
	checkErr(err, "deleteUsersInterests")
	writeJson(w, ResponseStatus{Status: "ok"})

}
Example #19
0
File: say.go Project: metcalf/saypi
func (c *Controller) DeleteMood(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := mustUserID(ctx)
	name := pat.Param(ctx, "mood")

	if err := c.repo.DeleteMood(userID, name); err == errBuiltinMood {
		respond.UserError(ctx, w, http.StatusBadRequest, usererrors.ActionNotAllowed{
			Action: fmt.Sprintf("delete built-in mood %s", name),
		})
	} else if err == errRecordNotFound {
		respond.NotFound(ctx, w, r)
	} else if conflict, ok := err.(conflictErr); ok {
		respond.UserError(ctx, w, http.StatusBadRequest, usererrors.ActionNotAllowed{
			Action: fmt.Sprintf("delete a mood associated with %d conversation lines", len(conflict.IDs)),
		})
	} else if err != nil {
		respond.InternalError(ctx, w, err)
	} else {
		w.WriteHeader(http.StatusNoContent)
	}
}
// PATCH /resources/:id
func (res *Resource) patchHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, storage store.Update) {
	parsedObject, parseErr := jsh.ParseObject(r)
	if parseErr != nil && reflect.ValueOf(parseErr).IsNil() == false {
		SendHandler(ctx, w, r, parseErr)
		return
	}

	id := pat.Param(ctx, "id")
	if id != parsedObject.ID {
		SendHandler(ctx, w, r, jsh.InputError("Request ID does not match URL's", "id"))
		return
	}

	object, err := storage(ctx, parsedObject)
	if err != nil && reflect.ValueOf(err).IsNil() == false {
		SendHandler(ctx, w, r, err)
		return
	}

	SendHandler(ctx, w, r, object)
}
Example #21
0
func publicProfile(ctx context.Context, w http.ResponseWriter, r *http.Request) {

	var user SimpleUser
	var c bool
	id, _ := strconv.ParseInt(pat.Param(ctx, "id"), 10, 64)

	session, _ := store.Get(r, "session")
	if session.Values["connected"] == true {
		c = true
		session.Options.MaxAge = 20
		session.Save(r, w)
	}

	smt, err := database.Prepare("SELECT user.username, user.birthdate FROM user WHERE id=?")
	checkErr(err, "publicProfile")
	var dob []uint8
	smt.QueryRow(id).Scan(&user.UserName, &dob)
	user.Id = id
	user.Bod = transformAge(dob)
	if c == false {
		renderTemplate(w, "publicProfile", &publicProfileView{
			Header: HeadData{
				Title:      "Profile",
				Stylesheet: []string{"publicProfile.css"}},
			Connection: false,
			Profile:    user})
		visitedProfile("unknown", id)
	} else {
		renderTemplate(w, "publicProfile", &publicProfileView{
			Header: HeadData{
				Title:      "Profile",
				Stylesheet: []string{"publicProfile.css"}},
			Connection: true,
			User:       session.Values["UserInfo"].(UserData),
			Profile:    user})
		visitedProfile(session.Values["UserInfo"].(UserData).UserName, id)
	}

}
Example #22
0
// GetPerson accepts a request to retrieve information about a particular person.
//
//     GET /people/:person
//
func GetPerson(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	var (
		idStr = pat.Param(ctx, "person")
	)

	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	person, err := datastore.GetPerson(ctx, id)
	if err != nil {
		log.Printf("error: error getting person err=%q", err)
		w.WriteHeader(http.StatusNotFound)
		return
	}

	renderTemplate(ctx, w, "person_show.tmpl", M{
		"Person": person,
	})
}
Example #23
0
func (c *Controller) GetConversation(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := mustUserID(ctx)
	convoID := pat.Param(ctx, "conversation")

	convo, err := c.repo.GetConversation(userID, convoID)
	if err != nil {
		panic(err)
	}
	if convo == nil {
		respond.NotFound(ctx, w, r)
		return
	}

	for i, Line := range convo.Lines {
		convo.Lines[i].Output, err = c.renderLine(&Line)
		if err != nil {
			panic(err)
		}
	}

	respond.Data(ctx, w, http.StatusOK, convo)
}
Example #24
0
// BuildGetHandler displays build information for a specific build
func BuildGetHandler(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
	dataRenderer := data.FromContext(ctx)

	toRender := map[string]interface{}{}

	id := to.Uint64(pat.Param(ctx, "id"))

	var pkg models.List
	if err := models.DB.Where("id = ?", id).First(&pkg).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			panic(ErrNotFound)
		} else {
			panic(err)
		}
	}

	toRender["Title"] = "Build " + to.String(id) + ": " + pkg.Name
	toRender["Nav"] = 2
	toRender["ID"] = to.String(id)

	dataRenderer.Data = toRender
	dataRenderer.Template = "builds/build"
}
Example #25
0
func (web *Web) HandleCard(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(pat.Param(ctx, "id"))
	if err != nil {
		http.Error(w, "Invalid ID", http.StatusBadRequest)
		return
	}

	u, _ := url.Parse(fmt.Sprintf("?multiverseid=%d", id))
	s, err, _ := api.ParseSearch(u)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	cards, err := web.r.GetCards(ctx, s)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	if len(cards) == 0 {
		http.Error(w, "No cards found", http.StatusNotFound)
		return
	}

	cp := CardPage{Card: cards[0]}
	for _, e := range cards[0].Editions {
		if e.MultiverseId == id {
			cp.Edition = e
		}
	}

	if err = web.t.Execute(w, cp); err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}
}
Example #26
0
func hello(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	name := pat.Param(ctx, "name")
	d, _ := yaml.Marshal(r.Header)
	fmt.Fprintf(w, "Hello, %s!-  %s\n%s", name, r.RemoteAddr, d)
}
Example #27
0
File: say.go Project: metcalf/saypi
// TODO: use gorilla schema here
func (c *Controller) CreateLine(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	userID := mustUserID(ctx)
	convoID := pat.Param(ctx, "conversation")

	var uerr usererrors.InvalidParams

	var think bool
	switch r.PostFormValue("think") {
	case "", "false":
		think = false
	case "true":
		think = true
	default:
		uerr = append(uerr, usererrors.InvalidParamsEntry{
			Params:  []string{"think"},
			Message: "must be either 'true' or 'false'",
		})
	}

	animal := r.PostFormValue("animal")
	if animal == "" {
		animal = "default"
	}
	if _, ok := c.cows[animal]; !ok {
		uerr = append(uerr, usererrors.InvalidParamsEntry{
			Params:  []string{"animal"},
			Message: fmt.Sprintf("%q does not exist", animal),
		})
	}

	text := strings.Replace(r.PostFormValue("text"), "\x00", "", -1)
	if cnt := utf8.RuneCountInString(text); cnt > maxTextLength {
		respond.UserError(ctx, w, http.StatusBadRequest, usererrors.InvalidParams{{
			Params:  []string{"text"},
			Message: fmt.Sprintf("must be a string of less than %d characters", maxTextLength),
		}})
		return
	}

	moodName := strings.Replace(r.PostFormValue("mood"), "\x00", "", -1)
	if moodName == "" {
		moodName = "default"
	}

	mood, err := c.repo.GetMood(userID, moodName)
	if err != nil {
		respond.InternalError(ctx, w, err)
		return
	}
	if mood == nil {
		uerr = append(uerr, usererrors.InvalidParamsEntry{
			Params:  []string{"mood"},
			Message: fmt.Sprintf("%q does not exist", moodName),
		})
	}

	if uerr != nil {
		respond.UserError(ctx, w, http.StatusBadRequest, uerr)
		return
	}

	line := Line{
		Animal:   animal,
		Think:    think,
		MoodName: moodName,
		Text:     text,
		mood:     mood,
	}

	if err := c.repo.InsertLine(userID, convoID, &line); err == sql.ErrNoRows {
		// The underlying conversation does not exist
		respond.NotFound(ctx, w, r)
	} else if err != nil {
		respond.InternalError(ctx, w, err)
		return
	}

	line.Output, err = c.renderLine(&line)
	if err != nil {
		respond.InternalError(ctx, w, err)
		return
	}

	respond.Data(ctx, w, http.StatusOK, line)
}
Example #28
0
// BuildPostHandler handles post actions that occur to the current active stage.
func BuildPostHandler(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
	// check for authentication
	user := models.FindUser(MustAuthenticate(r))

	// setup
	dataRenderer := data.FromContext(ctx)

	// read parameters
	id := to.Uint64(pat.Param(ctx, "id"))
	target := r.FormValue("target") // either activity or process
	name := r.FormValue("name")     // activity (ignored), process - find process
	action := r.FormValue("action") // activity (ignored), process passed on
	value := r.FormValue("value")   // activity (comment), process passed on

	// find the build list
	var pkg models.List
	if err := models.DB.Where("id = ?", id).First(&pkg).Related(&pkg.Stages, "Stages").Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			panic(ErrNotFound)
		} else {
			panic(err)
		}
	}

	var result interface{}

	// act based on target
	switch target {
	case "activity":
		if value == "" {
			panic(ErrBadRequest)
		}
		pkg.AddActivity(user, value)
		result = map[string]interface{}{
			"success": true,
		}
	case "process":
		// load up the stage & process
		if err := models.DB.Related(&pkg.Stages, "Stages").Error; err != nil {
			panic(err)
		}
		var currentStage *models.ListStage
		for _, v := range pkg.Stages {
			if v.Name == pkg.StageCurrent {
				currentStage = &v
				break
			}
		}

		if currentStage == nil {
			panic(ErrNoCurrentStage)
		}

		if err := models.DB.Related(&currentStage.Processes).Error; err != nil {
			panic(err)
		}

		var selectedProcess *models.ListStageProcess
		for _, v := range currentStage.Processes {
			if v.Name == name {
				selectedProcess = &v
				break
			}
		}

		if selectedProcess == nil {
			panic(ErrBadRequest)
		}

		// initialise the process
		process, err := processes.BuildProcess(selectedProcess)
		if err != nil {
			panic(err)
		}

		r, err := process.APIRequest(user, action, value)
		if err != nil {
			result = map[string]interface{}{
				"error":   true,
				"message": err.Error(),
				"result":  r,
			}
		} else {
			result = r
		}
	default:
		panic(ErrBadRequest)
	}

	dataRenderer.Type = data.DataJSON
	dataRenderer.Data = result

	//http.Redirect(rw, r, r.URL.String(), http.StatusTemporaryRedirect)
}
Example #29
0
// BuildGetJSONHandler displays build information in JSON for a specific build.
func BuildGetJSONHandler(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
	dataRenderer := data.FromContext(ctx)
	id := to.Uint64(pat.Param(ctx, "id"))
	user := models.FindUserNoCreate(Authenticated(r))

	// load the requested build list
	var pkg models.List
	if err := models.DB.Where("id = ?", id).First(&pkg).Related(&pkg.Activity, "Activity").Related(&pkg.Artifacts, "Artifacts").Related(&pkg.Links, "Links").Related(&pkg.Stages, "Stages").Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			panic(ErrNotFound)
		} else {
			panic(err)
		}
	}

	// load stage information
	var stageInfo []buildGetJSONStage

	for _, v := range pkg.Stages {
		if err := models.DB.Related(&v.Processes, "Processes").Error; err != nil && err != gorm.ErrRecordNotFound {
			panic(err)
		}

		// get all process info
		status := map[string]processes.ProcessStatus{}
		metadata := map[string]interface{}{}
		optional := map[string]bool{}

		for _, p := range v.Processes {
			process, err := processes.BuildProcess(&p)
			if err != nil {
				panic(err)
			}

			status[p.Name] = process.Status()
			metadata[p.Name] = process.APIMetadata(user)
			optional[p.Name] = p.Optional
		}

		stageInfo = append(stageInfo, buildGetJSONStage{
			Name:     v.Name,
			Status:   status,
			Metadata: metadata,
			Optional: optional,
		})
	}

	// render the data in a nice way

	dataRenderer.Data = &buildGetJSON{
		ID:       pkg.ID,
		Platform: pkg.Platform,
		Channel:  pkg.Channel,
		Variants: strings.Split(pkg.Variants, ";"),
		Name:     pkg.Name,

		Artifacts: pkg.Artifacts,
		Links:     pkg.Links,
		Activity:  pkg.Activity,
		Changes:   pkg.Changes,

		BuildDate: pkg.BuildDate,
		Updated:   pkg.UpdatedAt,

		PlatformConfig: pkg.PlatformGitConfig,
		Stages:         stageInfo,
		CurrentStage:   pkg.StageCurrent,
		Status:         pkg.StageResult,
		Advisory:       pkg.AdvisoryID,
	}
	dataRenderer.Type = data.DataJSON
}
Example #30
0
func hello(c context.Context, w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %s!", pat.Param(c, "name"))
}