Example #1
0
func (api *Api) GetPacker(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	packer := PackerModule{}
	has, err := api.DB.Where("id=?", id).Get(&packer)
	if err != nil {
		rest.NotFound(w, r)
		return
	}
	if !has {
		rest.NotFound(w, r)
		return
	}
	w.WriteJson(&packer)
}
Example #2
0
func getDevice(w rest.ResponseWriter, r *rest.Request) {
	devId := r.PathParam("devid")

	r.ParseForm()
	token := r.FormValue("token")
	if token == "" {
		rest.Error(w, "Missing \"token\"", http.StatusBadRequest)
		return
	}

	if !checkAuthz(token, devId) {
		log.Warnf("Auth failed. token: %s, device_id: %s", token, devId)
		rest.Error(w, "Authorization failed", http.StatusForbidden)
		return
	}

	stats.QueryDeviceInfo()

	if serverName, err := storage.Instance.CheckDevice(devId); err == nil && serverName != "" {
		resp := cloud.ApiResponse{}
		resp.ErrNo = cloud.ERR_NOERROR
		resp.Data = devInfo{
			Id: devId,
		}
		w.WriteJson(resp)
	} else {
		rest.NotFound(w, r)
		return
	}
}
Example #3
0
// PutDocument Route
// @route Put /api/documents/:id
func PutDocument(w rest.ResponseWriter, r *rest.Request) {
	email := fmt.Sprintf("%v", r.Env["REMOTE_USER"])

	id := r.PathParam("id")
	document := Document{}
	if DB.Where("email = ?", email).First(&document, id).Error != nil {
		rest.NotFound(w, r)
		return
	}

	updated := Document{}
	if err := r.DecodeJsonPayload(&updated); err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	document.Body = updated.Body
	document.Name, document.Description = splitBody(document.Body)

	if err := DB.Save(&document).Error; err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteJson(&document)
}
Example #4
0
func (i *Impl) PutOverlay(w rest.ResponseWriter, r *rest.Request) {

	id := r.PathParam("id")
	overlay := Overlay{}
	if i.DB.First(&overlay, id).Error != nil {
		rest.NotFound(w, r)
		return
	}

	updated := Overlay{}
	if err := r.DecodeJsonPayload(&updated); err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// TODO create the mapping for the PUT replacements
	// this is an example of the field mapping. I need a more complex mapping to
	// handle put... for field in fields: overlay.<field> = updated.<field>
	// overlay.Description = updated.Description

	if err := i.DB.Save(&overlay).Error; err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteJson(&overlay)
}
Example #5
0
func controlDevice(w rest.ResponseWriter, r *rest.Request) {
	type ControlParam struct {
		Token   string `json:"token"`
		Service string `json:"service"`
		Cmd     string `json:"cmd"`
	}

	devId := r.PathParam("devid")
	body := r.Env["body"]
	if body == nil {
		rest.Error(w, "Empty body", http.StatusBadRequest)
		return
	}
	b := body.([]byte)
	param := ControlParam{}
	if err := json.Unmarshal(b, &param); err != nil {
		log.Warnf("Error decode body: %s", err.Error())
		rest.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if !checkAuthz(param.Token, devId) {
		log.Warnf("Auth failed. token: %s, device_id: %s", param.Token, devId)
		rest.Error(w, "Authorization failed", http.StatusForbidden)
		return
	}

	stats.Cmd(param.Service)
	resp := cloud.ApiResponse{}
	result, err := rpcClient.Control(devId, param.Service, param.Cmd)
	if err != nil {
		if _, ok := err.(*mq.NoDeviceError); ok {
			stats.CmdOffline(param.Service)
			rest.NotFound(w, r)
			return
		} else if _, ok := err.(*mq.TimeoutError); ok {
			stats.CmdTimeout(param.Service)
			resp.ErrNo = cloud.ERR_CMD_TIMEOUT
			resp.ErrMsg = fmt.Sprintf("recv response timeout [%s]", devId)
		} else if _, ok := err.(*mq.InvalidServiceError); ok {
			stats.CmdInvalidService(param.Service)
			resp.ErrNo = cloud.ERR_CMD_INVALID_SERVICE
			resp.ErrMsg = fmt.Sprintf("Device [%s] has no service [%s]", devId, param.Service)
		} else if _, ok := err.(*mq.SdkError); ok {
			stats.CmdOtherError(param.Service)
			resp.ErrNo = cloud.ERR_CMD_SDK_ERROR
			resp.ErrMsg = fmt.Sprintf("Error when calling service [%s] on [%s]", param.Service, devId)
		} else {
			stats.CmdOtherError(param.Service)
			resp.ErrNo = cloud.ERR_CMD_OTHER
			resp.ErrMsg = err.Error()
		}
	} else {
		stats.CmdSuccess(param.Service)
		resp.ErrNo = cloud.ERR_NOERROR
		resp.Data = result
	}

	w.WriteJson(resp)
}
func (api *Api) GetEntry(w rest.ResponseWriter, r *rest.Request) {
	idParam := r.PathParam("id")
	entries := &PlaylistEntry{}

	rows, err := api.DB.Query("SELECT ROWID, " + COLNAME1 + ", " + COLNAME2 + " FROM " + TABLENAME + " WHERE ROWID = " + idParam)
	if err != nil {
		log.Fatal(err)
	}

	if rows.Next() {
		var id int
		var url string
		var played int
		if err := rows.Scan(&id, &url, &played); err != nil {
			log.Fatal(err)
		}
		entries = &PlaylistEntry{Id: id, Url: url, Played: played}
	} else {
		rest.NotFound(w, r)
		return
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}

	w.WriteJson(&entries)
}
func (api *Api) GetUser(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	user := &User{}

	rows, err := api.DB.Query("SELECT * FROM " + TABLENAME + " WHERE ID = " + id)
	if err != nil {
		log.Fatal(err)
	}

	if rows.Next() {
		var id int
		var name string
		if err := rows.Scan(&id, &name); err != nil {
			log.Fatal(err)
		}
		user = &User{Id: id, Name: name}
	} else {
		rest.NotFound(w, r)
		return
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}

	w.WriteJson(&user)
}
func (api *Api) GetOriginator(w rest.ResponseWriter, r *rest.Request) {
	_, err := api.validateAuthHeader(r.Request)

	if err != nil {
		rest.Error(w, "Authorization invalid", http.StatusUnauthorized)
		return
	}

	_id := r.PathParam("id")
	id, err := strconv.ParseInt(_id, 10, 64)

	onion := db.Onion{}
	if api.First(&onion, id).Error != nil {
		rest.NotFound(w, r)
		return
	}

	contactId, err := api.fetchContact(onion.Id)
	if err != nil {
	}

	w.WriteJson(
		&GetOriginatorWrapper{
			Onion: db.EmberOnion{
				Id:        onion.Id,
				Onion:     onion.Onion,
				ContactId: contactId,
			},
		},
	)
}
func (api *Api) DeleteCircle(w rest.ResponseWriter, r *rest.Request) {
	_, err := api.validateAuthHeader(r.Request)

	if err != nil {
		rest.Error(w, "Authorization invalid", http.StatusUnauthorized)
		return
	}

	_id := r.PathParam("id")
	id, err := strconv.ParseInt(_id, 10, 64)

	circle := db.Circle{Id: id}

	if err = api.Find(&circle, circle).Error; err != nil {
		if err == gorm.RecordNotFound {
			rest.NotFound(w, r)
			return
		} else {
			log.Println(gormLoadError("circle"), err)
			rest.Error(w, INTERNALERROR, http.StatusInternalServerError)
		}
	}

	api.Model(&circle).Association("Contacts").Clear()
	api.Model(&circle).Association("Posts").Clear()
	api.Delete(&circle)

	w.WriteHeader(http.StatusOK)
}
func (api *Api) DeletePost(w rest.ResponseWriter, r *rest.Request) {
	_, err := api.validateAuthHeader(r.Request)
	if err != nil {
		rest.Error(w, "Authorization invalid", http.StatusUnauthorized)
		return
	}

	_id := r.PathParam("id")
	id, err := strconv.ParseInt(_id, 10, 64)

	post := db.Post{}

	if err = api.First(&post, id).Error; err != nil {
		if err == gorm.RecordNotFound {
			rest.NotFound(w, r)
			return
		} else {
			log.Println(gormLoadError("post"), err)
			rest.Error(w, INTERNALERROR, http.StatusInternalServerError)
			return
		}
	}

	if err := api.Delete(&post).Error; err != nil {
		log.Println(gormDeleteError("post"), err)
		rest.Error(w, INTERNALERROR, http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
}
Example #11
0
// GetQueues ...
func GetQueues(w rest.ResponseWriter, r *rest.Request) {
	accountID, applicationName, _, err := queueParams(r)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	b := GetBase(r)
	lp := parseListQuery(r)
	var queues []*models.Queue
	lr := &models.ListResult{
		List: &queues,
	}

	if err := b.GetQueues(accountID, applicationName, lp, lr); err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if lr.Count == 0 {
		rest.NotFound(w, r)
		return
	}
	rt := make([]*Queue, len(queues))
	for idx, queue := range queues {
		rt[idx] = NewQueueFromModel(queue)
	}
	w.WriteJson(models.ListResult{
		List:    rt,
		HasMore: lr.HasMore,
		Total:   lr.Total,
		Count:   lr.Count,
		Page:    lr.Page,
		Pages:   lr.Pages,
	})
}
Example #12
0
// GetAccounts ...
func GetAccounts(w rest.ResponseWriter, r *rest.Request) {
	b := GetBase(r)
	lp := parseListQuery(r)
	var accounts []*models.Account
	lr := &models.ListResult{
		List: &accounts,
	}

	if err := b.GetAccounts(lp, lr); err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if lr.Count == 0 {
		rest.NotFound(w, r)
		return
	}
	rt := make([]*Account, len(accounts))
	for idx, account := range accounts {
		rt[idx] = NewAccountFromModel(account)
	}
	w.WriteJson(models.ListResult{
		List:    rt,
		HasMore: lr.HasMore,
		Total:   lr.Total,
		Count:   lr.Count,
		Page:    lr.Page,
		Pages:   lr.Pages,
	})
}
Example #13
0
//UpdateTripPlaces update trip places
func (t *Trips) UpdateTripPlaces(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	res, err := rethink.Table(tableName).Get(id).Run(t.Conn)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if res.IsNil() {
		rest.NotFound(w, r)
		return
	}
	var trip *Trip
	res.One(&trip)

	tripPlaces := []TripPlace{}
	err = r.DecodeJsonPayload(&tripPlaces)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	trip.Updated = time.Now()
	trip.Places = tripPlaces
	trip.TotalPlaces = len(tripPlaces)

	_, err = rethink.Table(tableName).Get(id).Update(trip).RunWrite(t.Conn)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteJson(&trip)
}
Example #14
0
// GetAttempts ...
func GetAttempts(w rest.ResponseWriter, r *rest.Request) {
	accountID, applicationName, taskName, err := taskParams(r)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	b := GetBase(r)
	lp := parseListQuery(r)
	var attempts []*models.Attempt
	lr := &models.ListResult{
		List: &attempts,
	}

	if err := b.GetAttempts(accountID, applicationName, taskName, lp, lr); err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if lr.Count == 0 {
		rest.NotFound(w, r)
		return
	}
	rt := make([]*Attempt, len(attempts))
	for idx, attempt := range attempts {
		rt[idx] = NewAttemptFromModel(attempt)
	}
	w.WriteJson(models.ListResult{
		List:    rt,
		HasMore: lr.HasMore,
		Total:   lr.Total,
		Count:   lr.Count,
		Page:    lr.Page,
		Pages:   lr.Pages,
	})
}
Example #15
0
func UpdateTask(w rest.ResponseWriter, r *rest.Request) {
	newtask := Task{}
	err := r.DecodeJsonPayload(&newtask)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	Id, _ := strconv.ParseInt(r.PathParam("id"), 0, 64)
	oldtask := store[Id]
	if oldtask == nil {
		rest.NotFound(w, r)
		return
	}
	if newtask.Desc != "" {
		oldtask.Desc = newtask.Desc
	}
	if newtask.Due != "" {
		oldtask.Due = newtask.Due
	}
	if newtask.Completed == true || newtask.Completed == false {
		oldtask.Completed = newtask.Completed
	}
	store[Id] = oldtask
	w.WriteJson(&oldtask)
}
func (api *Api) GetContact(w rest.ResponseWriter, r *rest.Request) {
	_, err := api.validateAuthHeader(r.Request)

	if err != nil {
		rest.Error(w, "Authorization invalid", http.StatusUnauthorized)
		return
	}

	_id := r.PathParam("id")
	id, err := strconv.ParseInt(_id, 10, 64)

	contact := db.Contact{}
	if api.First(&contact, id).Error != nil {
		rest.NotFound(w, r)
		return
	}

	emberContact := db.EmberContactResponse{}
	emberContact.Contact = contact
	emberContact.ProfilePictureId = api.GetProfilePictureId(contact.OnionId)
	api.Model(&contact).Related(&contact.Circles, "Circles")
	emberContact.EmberCircles = make([]int64, len(contact.Circles))
	for i, circ := range contact.Circles {
		emberContact.EmberCircles[i] = circ.Id
	}

	w.WriteJson(
		&GetContactWrapper{
			Contact: emberContact,
		},
	)
}
func (api *Api) PostUser(w rest.ResponseWriter, r *rest.Request) {
	user := User{}

	err := r.DecodeJsonPayload(&user)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	lastInsertId, err := api.DB.Query("INSERT INTO " + TABLENAME + "(" + COLNAME + ") OUTPUT Inserted.ID VALUES('" + user.Name + "')")
	if err != nil {
		fmt.Println(err)
		return
	}

	if lastInsertId.Next() {
		var id int
		if err := lastInsertId.Scan(&id); err != nil {
			log.Fatal(err)
		}
		user.Id = id
	} else {
		rest.NotFound(w, r)
		return
	}
	if err := lastInsertId.Err(); err != nil {
		log.Fatal(err)
	}

	w.WriteJson(&user)
}
Example #18
0
func (api *ChessApi) GetGameInfo(res rest.ResponseWriter, req *rest.Request) {
	u := getUser(req)

	id := req.PathParam("id")
	intId, err := strconv.Atoi(id)
	gameId := game.Id(intId)
	if err != nil {
		log.Debug("Recieved an invalid gameid, it was not an int: %s", id)
		rest.NotFound(res, req)
		return
	}

	gameInfo, found := api.Queries.GameInformation(gameId)
	if !found {
		log.Debug("Recieved an invalid gameid, it was not an int: %s", id)
		rest.NotFound(res, req)
		return
	}

	type Response struct {
		GameInfo        queries.GameInformation `json:",inline"`
		UserColor       game.Color              `json:",omitempty"`
		UserActive      bool
		DrawOfferToUser bool
	}

	response := new(Response)
	response.GameInfo = gameInfo

	if u.Uuid == gameInfo.White.Uuid {
		response.UserColor = game.White
		response.UserActive = gameInfo.ActiveColor == game.White

		if gameInfo.OutstandingDrawOffer && gameInfo.DrawOfferer == game.Black {
			response.DrawOfferToUser = true
		}
	} else if u.Uuid == gameInfo.Black.Uuid {
		response.UserColor = game.Black
		response.UserActive = gameInfo.ActiveColor == game.Black

		if gameInfo.OutstandingDrawOffer && gameInfo.DrawOfferer == game.White {
			response.DrawOfferToUser = true
		}
	}

	res.WriteJson(response)
}
Example #19
0
func (api *ChessApi) GetGameValidMoves(res rest.ResponseWriter, req *rest.Request) {
	id := req.PathParam("id")
	intId, err := strconv.Atoi(id)
	gameId := game.Id(intId)
	if err != nil {
		log.Debug("Recieved an invalid gameid, it was not an int: %s", id)
		rest.NotFound(res, req)
	}

	validMoves, found := api.Queries.ValidMoves(gameId)
	if !found {
		rest.NotFound(res, req)
		return
	}

	res.WriteJson(validMoves)
}
Example #20
0
// UpdateContact add new contact
func (a *Api) UpdateContact(w rest.ResponseWriter, r *rest.Request) {
	name := r.PathParam("name")
	log.Println("POST")

	// contact := Contact{}

	var contacts []Contact
	err := a.Db.Where("name", "=", name).OrderBy("name").Limit(1).Find(&contacts)
	if err != nil {
		log.Println(err)
		rest.NotFound(w, r)
		return
	}

	err = r.DecodeJsonPayload(&contacts[0])
	if err != nil {
		log.Println(err)
		rest.Error(w, "Data error", http.StatusInternalServerError)
		return
	}

	if len(contacts) == 1 {
		// Start a transaction
		tx := a.Db.Begin()
		_, err = tx.Save(&contacts[0])
		if err != nil {
			log.Println(err)
			rest.Error(w, "Failed", http.StatusInternalServerError)
			return
		}

		// Commit changes
		err = tx.Commit()
		if err != nil {
			log.Println(err)
			rest.Error(w, "Failed", http.StatusInternalServerError)
			return
		}
	} else {
		log.Println(err)
		rest.NotFound(w, r)
		return
	}

	w.WriteJson(&contacts[0])
}
Example #21
0
// GetTag confirm tag existence
func (a *Api) GetTag(w rest.ResponseWriter, r *rest.Request) {
	name := r.PathParam("name")

	var tags []Tag
	err := a.Db.Where("name", "=", name).OrderBy("weight").OrderBy("name").Limit(1).Find(&tags)
	if err != nil {
		log.Println(err)
		rest.NotFound(w, r)
		return
	}
	if len(tags) == 0 {
		rest.NotFound(w, r)
		return
	}

	w.WriteJson(tags[0])
}
func (api *Api) GetModule(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	module := Module{}
	if api.DB.Where("id = ?", id).First(&module).Error != nil {
		rest.NotFound(w, r)
		return
	}
	w.WriteJson(&module)
}
Example #23
0
func (self *Users) GetUser(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	user := self.Store[id]
	if user == nil {
		rest.NotFound(w, r)
		return
	}
	w.WriteJson(&user)
}
Example #24
0
func GetTask(w rest.ResponseWriter, r *rest.Request) {
	taskdesc := r.PathParam("taskdesc")
	task := store[taskdesc]
	if task == nil {
		rest.NotFound(w, r)
		return
	}
	w.WriteJson(&task)
}
Example #25
0
func (i *Impl) GetOverlay(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	overlay := Overlay{}
	if i.DB.First(&overlay, id).Error != nil {
		rest.NotFound(w, r)
		return
	}
	w.WriteJson(&overlay)
}
Example #26
0
func GetCountry(w rest.ResponseWriter, r *rest.Request) {
	code := r.PathParam("code")
	country := store[code]
	if country == nil {
		rest.NotFound(w, r)
		return
	}
	w.WriteJson(&country)
}
Example #27
0
func (i *Impl) GetService(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	service := Service{}
	if i.DB.First(&service, id).Error != nil {
		rest.NotFound(w, r)
		return
	}
	w.WriteJson(&ServiceWrapper{Service: service})
}
Example #28
0
func (api *Api) GetReminder(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	reminder := Reminder{}
	if api.DB.First(&reminder, id).Error != nil {
		rest.NotFound(w, r)
		return
	}
	w.WriteJson(&reminder)
}
Example #29
0
func ReadTask(w rest.ResponseWriter, r *rest.Request) {
	Id, _ := strconv.ParseInt(r.PathParam("id"), 0, 64)
	task := store[Id]
	if task == nil {
		rest.NotFound(w, r)
		return
	}
	w.WriteJson(&task)
}
Example #30
0
// GET /feeds/:id
// Returns a feed
func (a *RestAdapterImplementation) GetFeed(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	feed, err := a.db.GetFeed(id)
	if err != nil {
		rest.NotFound(w, r)
		return
	}
	w.WriteJson(&feed)
}