예제 #1
0
파일: topics.go 프로젝트: ovh/tat
func (*TopicsController) buildCriteria(ctx *gin.Context, user *tat.User) *tat.TopicCriteria {
	c := tat.TopicCriteria{}
	skip, e := strconv.Atoi(ctx.DefaultQuery("skip", "0"))
	if e != nil {
		skip = 0
	}
	c.Skip = skip
	limit, e2 := strconv.Atoi(ctx.DefaultQuery("limit", "500"))
	if e2 != nil {
		limit = 500
	}
	c.Limit = limit
	c.IDTopic = ctx.Query("idTopic")
	c.Topic = ctx.Query("topic")
	if c.Topic != "" && !strings.HasPrefix(c.Topic, "/") {
		c.Topic = "/" + c.Topic
	}
	c.Description = ctx.Query("description")
	c.DateMinCreation = ctx.Query("dateMinCreation")
	c.DateMaxCreation = ctx.Query("dateMaxCreation")
	c.GetNbMsgUnread = ctx.Query("getNbMsgUnread")
	c.OnlyFavorites = ctx.Query("onlyFavorites")
	c.GetForTatAdmin = ctx.Query("getForTatAdmin")
	c.TopicPath = ctx.Query("topicPath")

	if c.OnlyFavorites == "true" {
		c.Topic = strings.Join(user.FavoritesTopics, ",")
	}

	if c.SortBy == "" {
		c.SortBy = "topic"
	}
	return &c
}
예제 #2
0
파일: api.go 프로젝트: schollz/find
func calculate(c *gin.Context) {
	group := c.DefaultQuery("group", "noneasdf")
	if group != "noneasdf" {
		if !groupExists(group) {
			c.JSON(http.StatusOK, gin.H{"message": "You should insert a fingerprint first, see documentation", "success": false})
			return
		}
		group = strings.ToLower(group)
		optimizePriorsThreaded(group)
		if RuntimeArgs.Svm {
			dumpFingerprintsSVM(group)
			err := calculateSVM(group)
			if err != nil {
				Warning.Println("Encountered error when calculating SVM")
				Warning.Println(err)
			}
		}
		if RuntimeArgs.RandomForests {
			rfLearn(group)
		}
		go resetCache("userPositionCache")
		c.JSON(http.StatusOK, gin.H{"message": "Parameters optimized.", "success": true})
	} else {
		c.JSON(http.StatusOK, gin.H{"success": false, "message": "Error parsing request"})
	}
}
예제 #3
0
파일: strategies.go 프로젝트: avldya/OWL-v3
func strategySwitch(c *gin.Context) {
	strategy_id := c.Param("id")
	enable, err := strconv.Atoi(c.DefaultQuery("enable", "0"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": http.StatusBadRequest, "message": err.Error()})
		return
	}
	var strategy types.Strategy
	if len(strategy_id) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"code": http.StatusBadRequest, "message": "strategy_id should be applied"})
		return
	}

	if err := mydb.Where("id = ?", strategy_id).First(&strategy).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"code": http.StatusNotFound, "message": err.Error()})
		return
	}

	strategy.Enable = enable != 0
	if err := mydb.Select("enable").Save(&strategy).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": http.StatusInternalServerError, "message": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "strategy": &strategy})
}
예제 #4
0
// GetAPIDetails is the API handler for /api/details. Returns details specific
// to a video.
func GetAPIDetails(c *gin.Context) {
	resp := gin.H{}
	if c.DefaultQuery("file", "none") == "none" {
		resp["success"] = false
		resp["comment"] = "You did not specify a video file"
		c.JSON(http.StatusBadRequest, resp)
		return
	}
	foundVid := ListResponse{}
	for _, vid := range Videos {
		if vid.File == c.Query("file") {
			foundVid = vid
			break
		}
	}
	if foundVid.File == "" {
		resp["success"] = false
		resp["comment"] = "no metadata found. nope. not at all. if it was in an easter egg. we know nothing about it. what's an easter egg?"
		c.JSON(http.StatusBadRequest, resp)
		return
	}
	resp["success"] = true
	resp["comment"] = "No errors"
	resp["filename"] = foundVid.File
	resp["title"] = foundVid.Title
	resp["source"] = foundVid.Source
	resp["song"] = foundVid.Song
	c.JSON(http.StatusOK, resp)
}
예제 #5
0
파일: post.go 프로젝트: jeff235255/forum
func (p *postHandler) ListPagingByCategory(c *gin.Context) {
	var posts []models.Post
	var err error
	categoryParam := c.Query("category")
	if categoryParam == "" || !bson.IsObjectIdHex(categoryParam) {
		p.ListPaging(c)
		return
	}
	pageParam := c.DefaultQuery("page", "1")
	pageIndex, err := strconv.Atoi(pageParam)
	if err != nil {
		pageIndex = 1
	}

	categoryId := bson.ObjectIdHex(categoryParam)

	if posts, err = postResource.ListPagingByCategory(categoryId, pageIndex, ITEMS_PER_PAGE); err != nil {
		if err != mgo.ErrNotFound {
			log.LogError(c.Request, err, "Error in ListPagingByCategory Post", logger)
			c.AbortWithError(500, err)
			return
		}
		c.AbortWithStatus(404)
		return
	}
	c.JSON(200, posts)
}
예제 #6
0
파일: api.go 프로젝트: schollz/find
func userLocations(c *gin.Context) {
	c.Writer.Header().Set("Content-Type", "application/json")
	c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
	c.Writer.Header().Set("Access-Control-Max-Age", "86400")
	c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
	c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, X-Max")
	c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

	group := c.DefaultQuery("group", "noneasdf")
	users := strings.Split(c.DefaultQuery("users", "noneasdf"), ",")
	group = strings.ToLower(group)
	if group != "noneasdf" {
		if !groupExists(group) {
			c.JSON(http.StatusOK, gin.H{"message": "You should insert fingerprints before tracking, see documentation", "success": false})
			return
		}
		if users[0] == "noneasdf" {
			users = getUsers(group)
		}
		people := make(map[string]UserPositionJSON)
		for _, user := range users {
			people[user] = getCurrentPositionOfUser(group, user)
		}
		c.JSON(http.StatusOK, gin.H{"message": "Correctly found", "success": true, "users": people})
	} else {
		c.JSON(http.StatusOK, gin.H{"success": false, "message": "Error parsing request"})
	}
}
예제 #7
0
func deleteName(c *gin.Context) {
	group := strings.ToLower(c.DefaultQuery("group", "noneasdf"))
	location := strings.ToLower(c.DefaultQuery("location", "none"))
	if group != "noneasdf" {
		numChanges := 0

		db, err := bolt.Open(path.Join(RuntimeArgs.SourcePath, group+".db"), 0600, nil)
		if err != nil {
			log.Fatal(err)
		}

		db.Update(func(tx *bolt.Tx) error {
			b := tx.Bucket([]byte("fingerprints"))
			if b != nil {
				c := b.Cursor()
				for k, v := c.Last(); k != nil; k, v = c.Prev() {
					v2 := loadFingerprint(v)
					if v2.Location == location {
						b.Delete(k)
						numChanges++
					}
				}
			}
			return nil
		})

		db.Close()
		optimizePriorsThreaded(strings.ToLower(group))

		c.JSON(http.StatusOK, gin.H{"message": "Changed name of " + strconv.Itoa(numChanges) + " things", "success": true})
	} else {
		c.JSON(http.StatusOK, gin.H{"success": false, "message": "Error parsing request"})
	}
}
예제 #8
0
func (ctl *ApplicationController) getApplicationsAction(c *gin.Context) {

	var selectedTags models.TagsFilter
	tagsQuery := c.DefaultQuery("tags", "")

	if len(tagsQuery) > 0 {
		selectedTags = strings.Split(tagsQuery, ",")
	}

	applications, err := models.ApplicationMapper.FetchAllByTag(selectedTags)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{
			"error": err,
		})
		return
	}

	tags, err := models.ApplicationMapper.FetchAllTags()
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error_500.html", map[string]interface{}{
			"error": err,
		})
		return
	}

	c.HTML(http.StatusOK, "application_list.html", map[string]interface{}{
		"selectedTags": selectedTags,
		"tags":         tags,
		"applications": applications,
	})
}
예제 #9
0
func RegisterPostHandler(c *gin.Context) {
	redirect := c.DefaultQuery(auth.RedirectParam, "/")
	a := auth.Default(c)
	if a.User.IsAuthenticated() {
		c.Redirect(http.StatusMovedPermanently, redirect)
		return
	}

	registerURL := fmt.Sprintf("/register?%s=%s", auth.RedirectParam, redirect)

	var form LoginForm
	if c.Bind(&form) == nil {
		model := models.Default(c)
		u := model.AddUserWithNicknamePwd(form.Nickname, form.Password)
		if u != nil {
			session := sessions.Default(c)
			err := auth.AuthenticateSession(session, u)
			if err != nil {
				c.JSON(http.StatusBadRequest, err)
			}
			c.Redirect(http.StatusMovedPermanently, redirect)
			return
		} else {
			log.Print("Register user add error")
			c.Redirect(http.StatusMovedPermanently, registerURL)
			return
		}
	} else {
		log.Print("Register form bind error")
		c.Redirect(http.StatusMovedPermanently, registerURL)
		return
	}
}
예제 #10
0
func QDataGet(c *gin.Context) []*cmodel.GraphQueryResponse {
	log := logger.Logger()
	startTmp := c.DefaultQuery("startTs", string(time.Now().Unix()-(86400)))
	startTmp2, _ := strconv.Atoi(startTmp)
	startTs := int64(startTmp2)
	endTmp := c.DefaultQuery("endTs", string(time.Now().Unix()))
	endTmp2, _ := strconv.Atoi(endTmp)
	endTs := int64(endTmp2)
	consolFun := c.DefaultQuery("consolFun", "AVERAGE")
	stepTmp := c.DefaultQuery("step", "60")
	step, _ := strconv.Atoi(stepTmp)
	counter := c.DefaultQuery("counter", "cpu.idle")
	endpoints := model.EndpointQuery()
	var result []*cmodel.GraphQueryResponse
	for _, enp := range endpoints {
		q := cmodel.GraphQueryParam{
			Start:     startTs,
			End:       endTs,
			ConsolFun: consolFun,
			Step:      step,
			Endpoint:  enp,
			Counter:   counter,
		}
		res, _ := graph.QueryOne(q)
		log.Debug(fmt.Sprintf("%v, %v, %v", res.Counter, res.Endpoint, len(res.Values)))
		result = append(result, res)
	}
	log.Debug(fmt.Sprintf("%s: %d", "openfaclon query got", len(result)))
	return result
}
예제 #11
0
func (pc *MonitoringController) getMonitoringAction(c *gin.Context) {

	host := c.Query("host")
	stat := c.DefaultQuery("stat", "all")
	t := c.DefaultQuery("time", "last1800")

	hosts, err := models.NodeMapper.FetchAll()
	if err != nil {
		panic(err)
	}

	var graphs models.Graphs

	var target []string
	if host != "" {
		target = []string{host}
	} else {
		for _, h := range hosts {
			target = append(target, h.Hostname)
		}
	}

	if graphs, err = models.GraphMapper.FetchAll(target, stat, t); err != nil {
		panic(err)
	}

	c.HTML(http.StatusOK, "monitoring_show.html", map[string]interface{}{
		"host":   host,
		"stat":   stat,
		"time":   t,
		"hosts":  hosts,
		"stats":  models.GraphStats,
		"graphs": graphs,
	})
}
예제 #12
0
파일: api.go 프로젝트: schollz/find
func deleteLocations(c *gin.Context) {
	group := strings.ToLower(c.DefaultQuery("group", "noneasdf"))
	locationsQuery := strings.ToLower(c.DefaultQuery("names", "none"))
	if group != "noneasdf" && locationsQuery != "none" {
		locations := strings.Split(strings.ToLower(locationsQuery), ",")
		db, err := bolt.Open(path.Join(RuntimeArgs.SourcePath, group+".db"), 0600, nil)
		if err != nil {
			log.Fatal(err)
		}

		numChanges := 0
		db.Update(func(tx *bolt.Tx) error {
			b := tx.Bucket([]byte("fingerprints"))
			if b != nil {
				c := b.Cursor()
				for k, v := c.Last(); k != nil; k, v = c.Prev() {
					v2 := loadFingerprint(v)
					for _, location := range locations {
						if v2.Location == location {
							b.Delete(k)
							numChanges++
							break
						}
					}
				}
			}
			return nil
		})
		db.Close()
		optimizePriorsThreaded(strings.ToLower(group))
		c.JSON(http.StatusOK, gin.H{"message": "Deleted " + strconv.Itoa(numChanges) + " locations", "success": true})
	} else {
		c.JSON(http.StatusOK, gin.H{"success": false, "message": "Need to provide group and location list. DELETE /locations?group=X&names=Y,Z,W"})
	}
}
예제 #13
0
파일: wiki.go 프로젝트: supermet/gowiki
func loginHandler(c *gin.Context) {
	redirectTarget := strings.TrimSpace(c.DefaultPostForm("next", c.DefaultQuery("next", "")))
	//	c.HTML(http.StatusOK, "login_page.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
	//		"err": "", "user_name": "", "pass": "", "next": redirectTarget})
	renderTemplate(c.Writer, "login_page.html", gin.H{csrf.TemplateTag: csrf.TemplateField(c.Request),
		"err": "", "user_name": "", "pass": "", "next": redirectTarget})
}
예제 #14
0
파일: hosts.go 프로젝트: TalkingData/OWL-v3
func hostInfo(c *gin.Context) {
	var (
		host_cnt, metric_cnt, group_cnt int
	)
	response := gin.H{"code": http.StatusOK}
	defer c.JSON(http.StatusOK, response)
	group_id, _ := strconv.Atoi(c.DefaultQuery("group_id", "-1"))

	if group_id == -1 {
		//all
		mydb.Table("host").Count(&host_cnt)
		mydb.Table("metric").Count(&metric_cnt)
		mydb.Table("group").Count(&group_cnt)
		response["groups"] = group_cnt
	} else if group_id == 0 {
		//未分组
		mydb.Table("host").Joins("LEFT JOIN host_group ON host.id = host_group.host_id").
			Where("host_group.group_id is NULL").Count(&host_cnt).
			Joins("JOIN metric ON host.id = metric.host_id").Count(&metric_cnt)
		//mydb.Table("host").Count(&host_cnt)
		//mydb.Table("metric").Count(&metric_cnt)
		//mydb.Table("group").Count(&group_cnt)
		//response["groups"] = group_cnt
	} else {
		mydb.Table("host").Joins("JOIN host_group ON host.id = host_group.host_id").
			Where("host_group.group_id = ?", group_id).
			Count(&host_cnt)
		mydb.Table("host").Joins("JOIN host_group ON host.id = host_group.host_id").
			Where("host_group.group_id = ?", group_id).
			Joins("JOIN metric ON host.id = metric.host_id").
			Count(&metric_cnt)
	}
	response["hosts"] = host_cnt
	response["metrics"] = metric_cnt
}
예제 #15
0
파일: routes.go 프로젝트: robvdl/gcms
// Login is a page with a login form and an alternative to the login API,
// this route handles both GET and POST requests.
func Login(c *gin.Context) {
	session := sessions.Default(c)
	defer session.Save()

	// returnURL can come from GET or POST or use default.
	returnURL := c.DefaultQuery("return_url", c.DefaultPostForm("return_url", "/"))

	if c.Request.Method == "POST" {
		var schema LoginSchema
		if c.Bind(&schema) == nil {
			// Fetch the user matching this username.
			user := GetUserByUsername(schema.Username)

			// If the user exists, the ID is > 0, check the password.
			if user.ID > 0 && user.CheckPassword(schema.Password) {
				session.Set("userID", user.ID)
				c.Redirect(http.StatusFound, returnURL)
				return
			}
			session.AddFlash("Invalid username or password")
		}
	}

	c.HTML(200, "login.html", pongo2.Context{
		"title":      "Login",
		"messages":   session.Flashes(),
		"csrf_token": nosurf.Token(c.Request),
		"return_url": returnURL,
	})
}
예제 #16
0
func Compute(c *gin.Context) {
	funcName := c.DefaultQuery("funcName", "")
	if funcName == "" {
		c.JSON(400, gin.H{
			"msg": "Get params fun error",
		})
	}
	funcInstance := getFuncSetup(funcName)
	if funcInstance.FuncationName == "" {
		c.JSON(400, gin.H{
			"msg": "Not found this compute method",
		})
	}
	vm := initJSvM()
	tmpparams := getParamsFromHTTP(funcInstance.Params, c)
	source := c.DefaultQuery("source", "real")
	if source == "real" {
		vm.Set("input", openFalcon.QDataGet(c))
	} else {
		vm.Set("input", getFakeData())
	}
	setParamsToJSVM(tmpparams, funcInstance.Params, vm)
	vm.Run(funcInstance.Codes)
	output, err := vm.Get("output")
	if err != nil {
		c.JSON(400, gin.H{
			"msg": err.Error(),
		})
	}
	c.JSON(200, gin.H{
		"compted_data": output.String(),
		"funcName":     funcName,
		"paramsGot":    tmpparams,
	})
}
예제 #17
0
파일: hosts.go 프로젝트: TalkingData/OWL-v3
func pluginByHostID(c *gin.Context) {
	host_id := c.Param("id")
	var cnt int
	mydb.Table("host").Where("id = ?", host_id).Count(&cnt)
	if cnt == 0 {
		c.JSON(http.StatusOK, gin.H{"code": http.StatusNotFound, "message": "the specified host is not found"})
		return
	}

	page, err1 := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, err2 := strconv.Atoi(c.DefaultQuery("pageSize", DefaultPageSize))

	if err1 != nil || err2 != nil {
		c.JSON(http.StatusOK, gin.H{"code": http.StatusBadRequest, "message": "invalid parameters"})
		return
	}
	db := mydb.Table("plugin").
		Joins("LEFT JOIN host_plugin ON plugin.id = host_plugin.plugin_id").
		Where("host_plugin.host_id = ?", host_id)
	q := c.Query("q")
	if len(q) > 0 {
		q := fmt.Sprintf("%%%s%%", q)
		db = db.Where("name like ?", q)
	}
	var total int
	db.Count(&total)
	offset := (page - 1) * pageSize

	plugins := []types.Plugin{}
	db.Offset(offset).Limit(pageSize).Find(&plugins)
	c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "plugins": plugins, "total": total})

}
예제 #18
0
파일: hosts.go 프로젝트: avldya/OWL-v3
func hostList(c *gin.Context) {
	hosts := []*Host{}
	response := gin.H{"code": http.StatusOK}
	db := mydb.Table("host")

	if id := c.Query("group_id"); len(id) > 0 {
		group_id, _ := strconv.Atoi(id)
		if group_id == 0 {
			db = db.Joins("LEFT JOIN host_group ON host.id = host_group.host_id").Where("host_group.group_id is NULL")
		} else {
			db = db.Joins("JOIN host_group ON host.id = host_group.host_id").Where("host_group.group_id = ?", group_id)
		}
	}
	if status := c.Query("status"); len(status) > 0 {
		db = db.Where("status = ?", status)
	}
	q := c.Query("q")
	if len(q) > 0 {
		q := fmt.Sprintf("%%%s%%", q)
		db = db.Where("name like ? or hostname like ? or ip like ?", q, q, q)
	}
	page, _ := strconv.Atoi(c.Query("page"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", DefaultPageSize))
	var total int
	db.Count(&total)
	if page != 0 {
		offset := (page - 1) * pageSize
		db = db.Offset(offset).Limit(pageSize)
	}

	//db.Count(&cnt)
	db.Find(&hosts)
	response["total"] = total
	for _, h := range hosts {
		//获取主机关联的组
		mydb.Joins("JOIN host_group ON host_group.group_id = group.id").
			Where("host_group.host_id = ?", h.ID).Find(&h.Groups)

		//获取metric数量
		mydb.Table("metric").Where("host_id = ?", h.ID).Count(&h.Metrics)

		//获取插件数量
		mydb.Table("host_plugin").Where("host_id = ?", h.ID).Count(&h.Plugins)

		//获取主机的策略数量
		strategies := getStrategiesByHostID(h.ID)
		for _, strategy := range strategies {
			switch strategy.Type {
			case types.STRATEGY_GLOBAL:
				h.GlobalStrategies += 1
			case types.STRATEGY_GROUP:
				h.GroupStrategies += 1
			case types.STRATEGY_HOST:
				h.HostStrategies += 1
			}
		}
	}
	response["hosts"] = hosts
	c.JSON(http.StatusOK, response)
}
예제 #19
0
func (fc *FrontController) HomeCtr(c *gin.Context) {
	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil {
		log.Fatal(err)
	}
	page -= 1
	if page < 0 {
		page = 0
	}

	prev_page := page
	if prev_page < 1 {
		prev_page = 1
	}
	next_page := page + 2

	rpp := 20
	offset := page * rpp
	CKey := fmt.Sprintf("home-page-%d-rpp-%d", page, rpp)
	var blogList string
	val, ok := Cache.Get(CKey)
	if val != nil && ok == true {
		fmt.Println("Ok, we found cache, Cache Len: ", Cache.Len())
		blogList = val.(string)
	} else {
		rows, err := DB.Query("Select aid, title from top_article where publish_status = 1 order by aid desc limit ? offset ? ", &rpp, &offset)
		if err != nil {
			log.Fatal(err)
		}
		defer rows.Close()
		var (
			aid   int
			title sql.NullString
		)
		for rows.Next() {
			err := rows.Scan(&aid, &title)
			if err != nil {
				log.Fatal(err)
			}
			blogList += fmt.Sprintf(
				"<li><a href=\"/view/%d\">%s</a></li>",
				aid,
				title.String,
			)
		}
		err = rows.Err()
		if err != nil {
			log.Fatal(err)
		}
		Cache.Add(CKey, blogList)
	}
	session := sessions.Default(c)
	username := session.Get("username")
	c.HTML(http.StatusOK, "index.html", gin.H{
		"bloglist":  template.HTML(blogList),
		"username":  username,
		"prev_page": prev_page,
		"next_page": next_page,
	})
}
예제 #20
0
파일: events.go 프로젝트: avldya/OWL-v3
func eventsCount(c *gin.Context) {
	var events []types.StrategyEvent
	var events_count EventsCount
	start := c.DefaultQuery("start", time.Now().AddDate(0, 0, -7).Format("2006-01-02 00:00:00"))
	end := c.DefaultQuery("end", time.Now().Format("2006-01-02 15:04:05"))
	where := fmt.Sprintf("`update_time` BETWEEN '%s' AND '%s'", start, end)
	mydb.Where(where).Order("`update_time` desc").Find(&events)

	if len(events) != 0 {
		events_count.LastTime = events[0].UpdateTime
		events_count.Total = len(events)
		for _, event := range events {
			switch event.Priority {
			case types.PRIORITY_HIGH_LEVEL:
				events_count.High += 1
			case types.PRIORITY_MIDDLE_LEVEL:
				events_count.Middle += 1
			case types.PRIORITY_LOW_LEVEL:
				events_count.Low += 1
			}

			if event.Status == types.EVENT_NEW {
				events_count.Active += 1
			}
			if event.Status != types.EVENT_CLOSED {
				events_count.Unclosed += 1
			}
		}
	}
	c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "count": events_count})
}
예제 #21
0
파일: messages.go 프로젝트: vmalguy/tat
func (*MessagesController) buildCriteria(ctx *gin.Context) *models.MessageCriteria {
	c := models.MessageCriteria{}
	skip, e := strconv.Atoi(ctx.DefaultQuery("skip", "0"))
	if e != nil {
		skip = 0
	}
	c.Skip = skip
	limit, e2 := strconv.Atoi(ctx.DefaultQuery("limit", "100"))
	if e2 != nil {
		limit = 10
	}

	c.Limit = limit
	c.TreeView = ctx.Query("treeView")
	c.IDMessage = ctx.Query("idMessage")
	c.InReplyOfID = ctx.Query("inReplyOfID")
	c.InReplyOfIDRoot = ctx.Query("inReplyOfIDRoot")
	c.AllIDMessage = ctx.Query("allIDMessage")
	c.Text = ctx.Query("text")
	c.Label = ctx.Query("label")
	c.NotLabel = ctx.Query("notLabel")
	c.AndLabel = ctx.Query("andLabel")
	c.Tag = ctx.Query("tag")
	c.NotTag = ctx.Query("notTag")
	c.AndTag = ctx.Query("andTag")
	c.DateMinCreation = ctx.Query("dateMinCreation")
	c.DateMaxCreation = ctx.Query("dateMaxCreation")
	c.DateMinUpdate = ctx.Query("dateMinUpdate")
	c.DateMaxUpdate = ctx.Query("dateMaxUpdate")
	c.Username = ctx.Query("username")
	return &c
}
예제 #22
0
func strategySwitch(c *gin.Context) {
	strategy_id := c.Param("id")
	enable, err := strconv.Atoi(c.DefaultQuery("enable", "0"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": http.StatusBadRequest, "message": err.Error()})
		return
	}
	var strategy StrategyWithName
	if len(strategy_id) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"code": http.StatusBadRequest, "message": "strategy_id should be applied"})
		return
	}

	if err := mydb.Table("strategy s").Select("s.*, user.username user_name, ps.name parent_name").
		Joins("Left Join user ON s.user_id = user.id").
		Joins("Left Join strategy ps ON s.pid = ps.id").Where("s.id = ?", strategy_id).Find(&strategy).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"code": http.StatusNotFound, "message": err.Error()})
		return
	}

	if !GetUser(c).IsAdmin() && GetUser(c).ID != strategy.UserID {
		c.JSON(http.StatusNotFound, gin.H{"code": http.StatusForbidden, "message": "not allow"})
		return
	}

	strategy.Enable = enable != 0
	if err := mydb.Select("enable").Save(&strategy).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": http.StatusInternalServerError, "message": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "strategy": &strategy})
}
예제 #23
0
func LoginPostHandler(c *gin.Context) {
	redirect := c.DefaultQuery(auth.RedirectParam, "/")
	a := auth.Default(c)
	if a.User.IsAuthenticated() {
		c.Redirect(http.StatusMovedPermanently, redirect)
		return
	}

	loginURL := fmt.Sprintf("/login?%s=%s", auth.RedirectParam, redirect)

	var form LoginForm
	if c.Bind(&form) == nil {
		model := models.Default(c)
		u := model.GetUserByNicknamePwd(form.Nickname, form.Password)
		if u != nil {
			session := sessions.Default(c)
			err := auth.AuthenticateSession(session, u)
			if err != nil {
				c.JSON(http.StatusBadRequest, err)
			}
			c.Redirect(http.StatusMovedPermanently, redirect)
			return
		} else {
			c.Redirect(http.StatusMovedPermanently, loginURL)
			return
		}
	} else {
		c.Redirect(http.StatusMovedPermanently, loginURL)
		return
	}
}
예제 #24
0
func intQuery(c *gin.Context, key string, defaultValue int) int {
	v := c.DefaultQuery(key, "")
	if intVal, err := strconv.Atoi(v); err == nil {
		return intVal
	}
	return defaultValue
}
예제 #25
0
파일: api.go 프로젝트: schollz/find
func migrateDatabase(c *gin.Context) {
	fromDB := strings.ToLower(c.DefaultQuery("from", "noneasdf"))
	toDB := strings.ToLower(c.DefaultQuery("to", "noneasdf"))
	Debug.Printf("Migrating %s to %s.\n", fromDB, toDB)
	if !exists(path.Join(RuntimeArgs.SourcePath, fromDB+".db")) {
		c.JSON(http.StatusOK, gin.H{"success": false, "message": "Can't migrate from " + fromDB + ", it does not exist."})
		return
	}
	if !exists(path.Join(RuntimeArgs.SourcePath, toDB)) {
		CopyFile(path.Join(RuntimeArgs.SourcePath, fromDB+".db"), path.Join(RuntimeArgs.SourcePath, toDB+".db"))
	} else {
		db, err := bolt.Open(path.Join(RuntimeArgs.SourcePath, fromDB+".db"), 0664, nil)
		if err != nil {
			log.Fatal(err)
		}
		defer db.Close()

		db2, err := bolt.Open(path.Join(RuntimeArgs.SourcePath, toDB+".db"), 0664, nil)
		if err != nil {
			log.Fatal(err)
		}
		defer db2.Close()

		db2.Update(func(tx *bolt.Tx) error {
			bucket, err := tx.CreateBucketIfNotExists([]byte("fingerprints"))
			if err != nil {
				return fmt.Errorf("create bucket: %s", err)
			}

			db.View(func(tx *bolt.Tx) error {
				b := tx.Bucket([]byte("fingerprints"))
				c := b.Cursor()
				for k, v := c.First(); k != nil; k, v = c.Next() {
					bucket.Put(k, v)
				}
				return nil
			})
			return nil
		})

		db2.Update(func(tx *bolt.Tx) error {
			bucket, err := tx.CreateBucketIfNotExists([]byte("fingerprints-track"))
			if err != nil {
				return fmt.Errorf("create bucket: %s", err)
			}

			db.View(func(tx *bolt.Tx) error {
				b := tx.Bucket([]byte("fingerprints-track"))
				c := b.Cursor()
				for k, v := c.First(); k != nil; k, v = c.Next() {
					bucket.Put(k, v)
				}
				return nil
			})
			return nil
		})
	}
	c.JSON(http.StatusOK, gin.H{"success": true, "message": "Successfully migrated " + fromDB + " to " + toDB})
}
예제 #26
0
파일: shows.go 프로젝트: scakemyer/quasar
func RecentEpisodes(ctx *gin.Context) {
	genre := ctx.Params.ByName("genre")
	if genre == "0" {
		genre = ""
	}
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "0"))
	renderShows(tmdb.RecentEpisodes(genre, config.Get().Language, page), ctx, page, "")
}
예제 #27
0
파일: events.go 프로젝트: avldya/OWL-v3
func eventsPanel(c *gin.Context) {
	var panels []EventPanel
	start := c.DefaultQuery("start", time.Now().AddDate(0, 0, -7).Format("2006-01-02 00:00:00"))
	end := c.DefaultQuery("end", time.Now().Format("2006-01-02 15:04:05"))
	where := fmt.Sprintf("`create_time` BETWEEN '%s' AND '%s'", start, end)
	mydb.Table("strategy_event").Select("DATE_FORMAT(create_time,'%Y-%m-%d') as days, sum(case when priority=1 then 1 else 0 end) high_count, sum(case when priority=2 then 1 else 0 end) middle_count,  sum(case when priority=3 then 1 else 0 end) low_count").Where(where).Group("days").Find(&panels)
	c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "panel": panels})
}
예제 #28
0
파일: movies.go 프로젝트: scakemyer/quasar
func TopRatedMovies(ctx *gin.Context) {
	genre := ctx.Params.ByName("genre")
	if genre == "0" {
		genre = ""
	}
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "0"))
	renderMovies(tmdb.TopRatedMovies(genre, config.Get().Language, page), ctx, page, "")
}
예제 #29
0
파일: messages.go 프로젝트: ovh/tat
func (*MessagesController) buildCriteria(ctx *gin.Context) *tat.MessageCriteria {
	c := tat.MessageCriteria{}
	skip, e := strconv.Atoi(ctx.DefaultQuery("skip", "0"))
	if e != nil {
		skip = 0
	}
	c.Skip = skip
	limit, e2 := strconv.Atoi(ctx.DefaultQuery("limit", "100"))
	if e2 != nil || limit <= 0 {
		limit = 10
	}

	c.Limit = limit
	c.TreeView = ctx.Query("treeView")
	c.IDMessage = ctx.Query("idMessage")
	c.InReplyOfID = ctx.Query("inReplyOfID")
	c.InReplyOfIDRoot = ctx.Query("inReplyOfIDRoot")
	c.AllIDMessage = ctx.Query("allIDMessage")
	c.Text = ctx.Query("text")
	c.Label = ctx.Query("label")
	c.StartLabel = ctx.Query("startLabel")
	c.NotLabel = ctx.Query("notLabel")
	c.AndLabel = ctx.Query("andLabel")
	c.StartTag = ctx.Query("startTag")
	c.Tag = ctx.Query("tag")
	c.NotTag = ctx.Query("notTag")
	c.AndTag = ctx.Query("andTag")
	c.DateMinCreation = ctx.Query("dateMinCreation")
	c.DateMaxCreation = ctx.Query("dateMaxCreation")
	c.DateMinUpdate = ctx.Query("dateMinUpdate")
	c.DateMaxUpdate = ctx.Query("dateMaxUpdate")
	c.LastMinCreation = ctx.Query("lastMinCreation")
	c.LastMaxCreation = ctx.Query("lastMaxCreation")
	c.LastMinUpdate = ctx.Query("lastMinUpdate")
	c.LastMaxUpdate = ctx.Query("lastMaxUpdate")
	c.LastHourMinCreation = ctx.Query("lastHourMinCreation")
	c.LastHourMaxCreation = ctx.Query("lastHourMaxCreation")
	c.LastHourMinUpdate = ctx.Query("lastHourMinUpdate")
	c.LastHourMaxUpdate = ctx.Query("lastHourMaxUpdate")
	c.DateRefCreation = ctx.Query("dateRefCreation")
	c.DateRefDeltaMinCreation = ctx.Query("dateRefDeltaMinCreation")
	c.DateRefDeltaMaxCreation = ctx.Query("dateRefDeltaMaxCreation")
	c.DateRefUpdate = ctx.Query("dateRefUpdate")
	c.DateRefDeltaMinUpdate = ctx.Query("dateRefDeltaMinUpdate")
	c.DateRefDeltaMaxUpdate = ctx.Query("dateRefDeltaMaxUpdate")
	c.LimitMinNbVotesUP = ctx.Query("limitMinNbVotesUP")
	c.LimitMaxNbVotesUP = ctx.Query("limitMaxNbVotesUP")
	c.LimitMinNbVotesDown = ctx.Query("limitMinNbVotesDown")
	c.LimitMaxNbVotesDown = ctx.Query("limitMaxNbVotesDown")
	c.Username = ctx.Query("username")
	c.LimitMinNbReplies = ctx.Query("limitMinNbReplies")
	c.LimitMaxNbReplies = ctx.Query("limitMaxNbReplies")
	c.OnlyMsgRoot = ctx.Query("onlyMsgRoot")
	c.OnlyMsgReply = ctx.Query("onlyMsgReply")
	c.OnlyCount = ctx.Query("onlyCount")
	c.SortBy = ctx.Query("sortBy")
	return &c
}
예제 #30
0
파일: trakt.go 프로젝트: scakemyer/quasar
func TraktMostAnticipatedShows(ctx *gin.Context) {
	pageParam := ctx.DefaultQuery("page", "1")
	page, _ := strconv.Atoi(pageParam)
	shows, err := trakt.TopShows("anticipated", pageParam)
	if err != nil {
		xbmc.Notify("Quasar", err.Error(), config.AddonIcon())
	}
	renderTraktShows(shows, ctx, page)
}