Пример #1
0
func HandleCreateIRLMoji(r render.Render, bindErr binding.Errors, im models.IRLMoji, db *models.DB, backchannel Backchannel) {
	if bindErr.Count() > 0 {
		r.JSON(400, JsonErrBinding(bindErr))
		return
	}

	if backchannel.UserId() == "" {
		r.JSON(403, JsonErr("The provided credentials were invalid."))
		return
	}

	user, err := db.GetUserWithId(backchannel.UserId())
	if err != nil {
		r.JSON(403, "Could not find a user with your credentials.")
		return
	}

	// Now let's create that user, shall we?
	insertedIM, err := db.InsertIM(user.Id, im.Emoji, im.Picture)
	if err != nil {
		log.Println("Error creating user:"******"Sorry, an internal server error has occurred."))
		return
	}

	r.JSON(200, map[string]*models.IRLMoji{"irlmoji": insertedIM})
}
Пример #2
0
func HandleRandomJsonTip(r render.Render) {

	db := GetDBInstance()
	tip := models.Tips{}
	api := models.API{}
	total, _ := db.C("tips").Count()
	index := getRandomIndex(total)
	db.C("tips").Find(nil).Skip(index).One(&tip)
	err := db.C("apis").Find(bson.M{"type": "json"}).One(&api)

	api.Count++

	if err != nil {
		db.C("apis").Insert(&models.API{Id: bson.NewObjectId(), Type: "json", Count: 0})
	} else {
		db.C("apis").Update(bson.M{"type": "json"}, bson.M{"type": "json", "count": api.Count})
	}

	data, err := json.Marshal(api)

	if err == nil {
		sendAll(data)
	}

	if db.Session != nil {
		defer db.Session.Close()
	}

	r.JSON(200, tip)
}
func ArticlesIndex(r render.Render) {

	hal := HAL{}

	hal.Links = map[string]Link{
		"self": Link{"/articles", false},
		"show": Link{"/articles/{id}", true},
	}

	//result := []Todo{}
	//
	//rows, err := rethink.Table("todos").Run(session)
	//if err != nil {
	//    log.Println(err)
	//}
	//
	//for rows.Next() {
	//    var t Todo
	//    err := rows.Scan(&t)
	//    if err != nil {
	//        log.Println(err)
	//    }
	//    result = append(result, t)
	//}
	//r.JSON(200, result)

	//r.JSON(200, "hello")

	r.JSON(200, hal)

}
Пример #4
0
// Called on a POST to /events/:id/comments
// Assuming valid comment; Adds the comment under the given id
func AddComment(db *mgo.Database, r render.Render, comment models.Comment, p martini.Params) {
	var eventId bson.ObjectId

	// Create a unique id
	comment.Id = bson.NewObjectId()

	if bson.IsObjectIdHex(p["event_id"]) {
		eventId = bson.ObjectIdHex(p["event_id"])
	} else {
		r.JSON(400, "Bad Request: Invalid Event ID")
		return
	}

	comment.EventId = eventId

	// TODO Should be the user Id
	comment.CreatedBy = bson.NewObjectId()
	comment.CreatedAt = time.Now().UTC()

	err := db.C("comments").Insert(comment)
	if err != nil {
		panic(err)
	}

	r.JSON(201, comment)
}
Пример #5
0
func popularLinks(r render.Render) {
	links, err := store.Popular()

	if err != nil {
		log.WithField("package", "web").Error(err)

		r.JSON(500, map[string]string{
			"error": err.Error(),
		})

		return
	}

	var formattedLinks []map[string]interface{}

	for _, link := range links {
		formattedLinks = append(formattedLinks, map[string]interface{}{
			"id":    link.ID(),
			"title": link.Title,
			"url":   link.URL,
			"score": link.Score,
		})
	}

	r.JSON(200, formattedLinks)
}
Пример #6
0
func removeHero(db HeroDB, parms martini.Params, r render.Render) {
	u := (db).(*heroDB)
	id, _ := strconv.Atoi(parms["id"])

	delete(u.heros, id)

	r.JSON(http.StatusOK, nil)
}
Пример #7
0
func GetPost(params martini.Params, r render.Render) {
	hd := services.GetDb()

	var results []models.Posts
	hd.Where("id", "=", params["id"]).Limit(1).Find(&results)

	r.JSON(200, results)
}
Пример #8
0
func ListPosts(params martini.Params, r render.Render) {
	hd := services.GetDb()

	var results []models.Posts
	hd.Find(&results)

	r.JSON(200, results)
}
func ProjectGet(db gorm.DB, r render.Render, params martini.Params) {
	var project models.Project
	if err := db.First(&project, params["id"]).Error; err != nil {
		r.JSON(http.StatusNotFound, map[string]interface{}{"error": "Project not found"})
		return
	}
	r.JSON(http.StatusOK, project)
}
Пример #10
0
func getDrop(params martini.Params, db *database.Database, r render.Render) {
	d, err := db.GetDrop(params["url"])
	if err != nil {
		r.JSON(500, map[string]interface{}{"error": err.Error()})
	} else {
		r.JSON(200, map[string]interface{}{"drop": d})
	}
}
Пример #11
0
func deleteDrop(params martini.Params, db *database.Database, r render.Render) {
	url := params["url"]
	err := db.DeleteDrop(url)
	if err != nil {
		r.JSON(500, map[string]interface{}{"error": err.Error()})
	} else {
		r.JSON(200, map[string]interface{}{"ok": url})
	}
}
Пример #12
0
func renderTutorial(ren render.Render) {
	var tutorial Tutorial
	file, err := ioutil.ReadFile("neutrino.json")
	if err != nil {
		panic(err)
	}
	json.Unmarshal(file, &tutorial)
	ren.JSON(200, tutorial)
}
Пример #13
0
func allHeros(db HeroDB, parms martini.Params, r render.Render) {
	u := (db).(*heroDB)
	var heros []Hero

	for _, v := range u.heros {
		heros = append(heros, v)
	}
	r.JSON(http.StatusOK, heros)
}
Пример #14
0
func listDrops(db *database.Database, r render.Render) {
	// when there's none it returns a null?
	drops, err := json.Marshal(db.ListDrops())
	fmt.Println(drops)
	if err != nil {
		r.JSON(500, map[string]interface{}{"error": err})
	} else {
		r.JSON(200, map[string]interface{}{"drops": string(drops)})
	}
}
func HomeIndex(r render.Render) {

	hal := HAL{}

	hal.Links = map[string]Link{
		"self":      Link{"/", false},
		"portfolio": Link{"/portfolio", false},
	}

	r.JSON(200, hal)
}
Пример #16
0
// TODO separate view from *model*
func NewLog(log Log, req *http.Request, args martini.Params, r render.Render) {
	ip := strings.Split(req.RemoteAddr, ":")[0]
	log.Ip = ip
	result, err := rethink.Table("exceptions").Insert(log).RunWrite(session)
	if err != nil {
		fmt.Println(err)
	}
	key := result.GeneratedKeys[0]
	b, err := json.Marshal(log)
	broadcastMessage(1, b)
	r.JSON(200, map[string]interface{}{"key": key})
}
Пример #17
0
func GetCreativeById(params martini.Params, r render.Render) {
	var creative Creative
	if err := collection.FindId(params["id"]).One(&creative); err != nil {
		if creative != (Creative{}) {
			r.JSON(200, creative)
		} else {
			r.JSON(404, bson.M{"message": "F**K NO"})
		}
	} else {
		panic(err)
	}
}
Пример #18
0
func (ctrl FoodController) GetOne(r render.Render, params martini.Params, req *http.Request) {

	findName := params["name"]

	if _, ok := foods[findName]; !ok {
		r.JSON(http.StatusNotFound, ErrJson(http.StatusNotFound))
		return
	}

	r.JSON(http.StatusOK, foods[findName])
	return

}
func ProjectUpdate(db gorm.DB, r render.Render, params martini.Params, updatedProject models.Project) {
	var project models.Project
	if err := db.First(&project, params["id"]).Error; err != nil {
		r.JSON(http.StatusNotFound, map[string]interface{}{"error": "Project not found"})
		return
	}

	project.Name = updatedProject.Name
	project.UpdatedAt = time.Now()

	db.Save(&project)
	r.JSON(http.StatusOK, project)
}
Пример #20
0
func findHero(db HeroDB, parms martini.Params, r render.Render) {
	u := (db).(*heroDB)

	id, _ := strconv.Atoi(parms["id"])

	hero, ok := u.heros[id]
	if !ok {
		r.Error(http.StatusNotFound)
		return
	}

	r.JSON(http.StatusOK, hero)
}
Пример #21
0
func HandleGetUserTimeline(r render.Render, limit Limit, params martini.Params, db *models.DB, backchannel Backchannel) {
	user, err := db.GetUserWithUsername(params["username"])
	if err != nil {
		r.JSON(404, JsonErr("Username '"+params["username"]+"' not found."))
		return
	}
	timeline, err := db.GetIMsForUser(user.Id, limit.GetLimit()+uint32(1))
	if err != nil {
		log.Println("Error getting IMs for user", user.Username, err.Error())
		r.JSON(500, JsonErr("Sorry, an internal server error has occurred."))
		return
	}
	for _, im := range timeline {
		err = db.AnnotateHearted(im, backchannel.UserId())
		if err != nil {
			log.Println("Error annotating hearted info:", err.Error())
			r.JSON(500, "Sorry, an internal server error has occurred.")
			return
		}
	}
	hasMore, timeline := hasMoreTimeline(limit, timeline)
	r.JSON(200, map[string]interface{}{
		"timeline": timeline,
		"hasMore":  hasMore,
	})
}
Пример #22
0
func HandleGetIRLMoji(r render.Render, db *models.DB, params martini.Params, backchannel Backchannel, limit Limit) {
	irlmojiId, err := strconv.ParseUint(params["irlmojiId"], 10, 64)
	if err != nil {
		r.JSON(404, JsonErr("Invalid IRLMoji id provided:"+
			params["irlmojiId"]))
	}
	im, err := db.GetIMWithId(irlmojiId)
	if err != nil {
		r.JSON(404, JsonErr("The provided IRLMoji id was invalid:"+
			params["irlmojiId"]))
		return
	}
	hearts, err := db.GetHeartsForIRLMoji(irlmojiId, limit.GetLimit())
	if err == nil {
		im.Hearts = hearts
	} else {
		log.Println("WARNING: Could not get IRLMoji hearts:", err.Error())
	}
	err = db.AnnotateHearted(im, backchannel.UserId())
	if err != nil {
		log.Println("Error annotating hearted info:", err.Error())
		r.JSON(500, "Sorry, an internal server error has occurred.")
		return
	}
	r.JSON(200, map[string]*models.IRLMoji{"irlmoji": im})
}
Пример #23
0
func Root(session *gocql.Session, r render.Render) {
	var first_name, last_name string
	var id gocql.UUID

	iter := session.Query("select user_id, first_name, last_name from user limit 1000").Iter()

	response := make([]result, 0, 1000)

	for iter.Scan(&id, &first_name, &last_name) {
		response = append(response, result{FirstName: first_name, LastName: last_name})
	}
	r.JSON(200, response)

}
Пример #24
0
func cancelAll(res render.Render, req *http.Request, w http.ResponseWriter) {
	qs := req.URL.Query()
	printer := qs.Get("printer")

	cmd := exec.Command("cancel", "-a", "-x", printer)
	var out bytes.Buffer
	cmd.Stdout = &out
	cmd.Run()

	w.Header().Set("Access-Control-Allow-Origin", "*")

	res.JSON(200, map[string]interface{}{
		"success": true,
		"printer": printer,
	})
}
Пример #25
0
// Called on a POST to /events
// Assuming valid event; adds the given event
func AddEvent(db *mgo.Database, r render.Render, event models.Event) {

	// Create a unique id
	event.Id = bson.NewObjectId()

	// TODO Should be the user Id
	event.CreatedBy = bson.NewObjectId()
	event.CreatedAt = time.Now().UTC()

	err := db.C("events").Insert(event)
	if err != nil {
		panic(err)
	}

	r.JSON(201, event)
}
Пример #26
0
func CreatePost(post forms.Post, params martini.Params, formErr binding.Errors, r render.Render) {

	hd := services.GetDb()
	tx := hd.Begin()

	newpost := models.Posts{Title: post.Title, Body: post.Content}
	id, err := tx.Save(&newpost)

	if err != nil {
		panic(err)
	}

	err = tx.Commit()

	r.JSON(200, id)
}
Пример #27
0
func HandleUpload(r render.Render, w http.ResponseWriter, req *http.Request, backchannel Backchannel, db *models.DB) {
	file, header, err := req.FormFile("file")
	defer file.Close()

	if err != nil {
		fmt.Fprintln(w, err)
		return
	}

	data, err := ioutil.ReadAll(file)
	if err != nil {
		fmt.Fprintln(w, err)
		return
	}

	s := s3.New(AWS_AUTH, aws.USEast)
	bucket := s.Bucket(AWS_S3_BUCKET_NAME)
	mimetype := header.Header.Get("Content-Type")
	imageId := uuid.New()
	ext := filepath.Ext(header.Filename)
	if ext == "" {
		fmt.Fprintln(w,
			"Could not determine the file type of the uploaded image.")
		return
	}

	// Upload the original
	path := fmt.Sprintf("uploads/original/%s/%s%s", backchannel.UserId(),
		imageId, ext)
	err = bucket.Put(path, data, mimetype, s3.PublicRead)
	if err != nil {
		fmt.Fprintln(w, err)
		return
	}

	// Now resize and upload those
	pathPrefix := fmt.Sprintf("uploads/resized/%s/%s", backchannel.UserId(),
		imageId)
	err = generateThumbnails(file, backchannel.UserId(), pathPrefix, bucket)
	if err != nil {
		fmt.Fprintln(w, err)
		return
	}

	r.JSON(200, map[string]string{"path": path})
}
Пример #28
0
// Called on a GET to /events
// Returns a list of all events
func GetAllEvents(db *mgo.Database, r render.Render) {

	var events []models.Event

	// Only display events that haven't ended, and sort by end_time
	err := db.C("events").Find(bson.M{
		"end_time": bson.M{
			"$gt": time.Now().UTC(),
		},
	}).Sort("start_time").All(&events)

	if err != nil {
		panic(err)
	}

	r.JSON(200, events)
}
Пример #29
0
func updateHero(db HeroDB, req *http.Request, r render.Render) {
	u := (db).(*heroDB)

	breq := new(BatmanRequest)
	body, _ := ioutil.ReadAll(req.Body)
	req.Body.Close()

	err := json.Unmarshal(body, &breq)
	hero := breq.Hero

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

	u.heros[hero.Id] = hero
	r.JSON(http.StatusOK, hero)
}
Пример #30
0
// Called on a GET to /events/:id/comments
// Returns list of all comments under :id
func GetAllComments(db *mgo.Database, r render.Render, p martini.Params) {
	var eventId bson.ObjectId
	var comments []models.Comment

	if bson.IsObjectIdHex(p["event_id"]) {
		eventId = bson.ObjectIdHex(p["event_id"])
	} else {
		r.JSON(400, "Bad Request: Invalid ObjectId")
		return
	}

	err := db.C("comments").Find(bson.M{"event_id": eventId}).All(&comments)

	if err != nil {
		panic(err)
	}

	r.JSON(200, comments)

}