Example #1
0
func ProviderGetEpisode(ctx *gin.Context) {
	provider := ctx.Params.ByName("provider")
	showId := ctx.Params.ByName("showId")
	seasonNumber, _ := strconv.Atoi(ctx.Params.ByName("season"))
	episodeNumber, _ := strconv.Atoi(ctx.Params.ByName("episode"))

	log.Println("Searching links for TVDB Id:", showId)

	show, err := tvdb.NewShowCached(showId, "en")
	if err != nil {
		ctx.Error(err)
		return
	}
	episode := show.Seasons[seasonNumber].Episodes[episodeNumber-1]

	log.Printf("Resolved %s to %s", showId, show.SeriesName)

	searcher := providers.NewAddonSearcher(provider)
	torrents := searcher.SearchEpisodeLinks(show, episode)
	if ctx.Request.URL.Query().Get("resolve") == "true" {
		for _, torrent := range torrents {
			torrent.Resolve()
		}
	}
	data, err := json.MarshalIndent(providerDebugResponse{
		Payload: searcher.GetEpisodeSearchObject(show, episode),
		Results: torrents,
	}, "", "    ")
	if err != nil {
		xbmc.AddonFailure(provider)
		ctx.Error(err)
	}
	ctx.Data(200, "application/json", data)
}
Example #2
0
func HandleQuery(query string, c *gin.Context) {
	rawQuery, err := base64.StdEncoding.DecodeString(query)
	if err == nil {
		query = string(rawQuery)
	}

	result, err := DB(c).Query(query)
	if err != nil {
		c.JSON(400, NewError(err))
		return
	}

	format := getQueryParam(c, "format")
	filename := getQueryParam(c, "filename")

	if filename == "" {
		filename = fmt.Sprintf("pgweb-%v.%v", time.Now().Unix(), format)
	}

	if format != "" {
		c.Writer.Header().Set("Content-disposition", "attachment;filename="+filename)
	}

	switch format {
	case "csv":
		c.Data(200, "text/csv", result.CSV())
	case "json":
		c.Data(200, "applicaiton/json", result.JSON())
	case "xml":
		c.XML(200, result)
	default:
		c.JSON(200, result)
	}
}
Example #3
0
func Count(context *gin.Context) {
	appenginecontext := appengine.NewContext(context.Request)
	image := context.Param("image")
	imageId, err := strconv.Atoi(image)
	if err != nil {
		context.AbortWithError(http.StatusInternalServerError, err)
		appenginecontext.Debugf("%s", err)
		return
	}

	var counter Counter
	key := datastore.NewKey(appenginecontext, "counters", "", int64(imageId), nil)
	if err := datastore.Get(appenginecontext, key, &counter); err != nil {
		context.AbortWithError(http.StatusInternalServerError, err)
		appenginecontext.Debugf("%s", err)
		return
	}

	counter.Hits = counter.Hits + 1
	counter.Last = time.Now()

	_, err = datastore.Put(appenginecontext, key, &counter)
	if err != nil {
		context.AbortWithError(http.StatusInternalServerError, err)
		appenginecontext.Debugf("%s", err)
		return
	}

	output, _ := base64.StdEncoding.DecodeString("R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==")
	context.Data(200, "image/gif", output)
}
Example #4
0
// FriendshipShow takes a given ID from gin.Context
// @returns a specific friendship JSON object
func FriendshipShow(c *gin.Context) {
	friendship := models.Friendship{}

	if database.DBCon.First(&friendship, c.Param("id")).RecordNotFound() {
		c.AbortWithError(http.StatusNotFound, appError.RecordNotFound).
			SetMeta(appError.RecordNotFound)
		return
	}

	var fd models.FriendshipData

	database.DBCon.First(&friendship.User, friendship.UserID)
	database.DBCon.First(&friendship.Friend, friendship.FriendID)
	database.DBCon.First(&fd, friendship.FriendshipDataID)

	if friendship.UserID == fd.PositiveUserID {
		friendship.Balance = fd.Balance
	} else {
		friendship.Balance = -fd.Balance
	}

	data, err := jsonapi.Marshal(friendship)

	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err).
			SetMeta(appError.JSONParseFailure)
		return
	}

	c.Data(http.StatusOK, "application/vnd.api+json", data)
}
Example #5
0
func rpcEndpoint(c *gin.Context) {
	op := c.MustGet("nuget.op").(string)
	query := c.MustGet("nuget.search").(*NuGetQuery)

	oplog := log.WithFields(log.Fields{
		"op":    op,
		"query": query,
	})

	switch op {
	case "$metadata":
		c.Data(200, XmlMimeType, []byte(NuGetMetadata))
		break
	case "Packages":
		data := c.MustGet("nuget.op.data").(*PackagesCommand)
		Packages(c, data, query, oplog.WithField("data", data))
	case "FindPackagesById":
		data := c.MustGet("nuget.op.data").(*FindPackagesByIdCommand)
		FindPackagesById(c, data, query, oplog.WithField("data", data))
	case "Search":
		data := c.MustGet("nuget.op.data").(*SearchCommand)
		Search(c, data, query, oplog.WithField("data", data))
	case "GetUpdates":
		data := c.MustGet("nuget.op.data").(*GetUpdatesCommand)
		GetUpdates(c, data, query, oplog.WithField("data", data))
	default:
		c.Status(400)
	}
}
Example #6
0
// FriendshipIndex takes in query params through
// gin.Context and is restricted to the currentUser
// @returns an array of friendship JSON objects
func FriendshipIndex(c *gin.Context) {
	friendships := []models.Friendship{}
	var curUser models.User
	database.DBCon.First(&curUser, c.Keys["CurrentUserID"])

	database.DBCon.Model(&curUser).Related(&friendships, "Friendships")

	// Get user and friend and friendshipData
	// TODO: n + 1 query problem here, so we'll figure this out later
	for i := range friendships {
		var fd models.FriendshipData
		database.DBCon.First(&friendships[i].Friend, friendships[i].FriendID)
		database.DBCon.First(&fd, friendships[i].FriendshipDataID)

		if curUser.ID == fd.PositiveUserID {
			friendships[i].Balance = fd.Balance
		} else {
			friendships[i].Balance = -fd.Balance
		}

		friendships[i].User = curUser
	}

	data, err := jsonapi.Marshal(friendships)

	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err).
			SetMeta(appError.JSONParseFailure)
		return
	}

	c.Data(http.StatusOK, "application/vnd.api+json", data)
}
Example #7
0
func (s *Server) getTagsFile(c *gin.Context) {
	id := c.Param("id")
	content_path := c.Param("path")[1:] // '/' を消す
	tag, err := TagFileFromFile(s.tagFilepath(id))
	if err != nil {
		c.AbortWithError(500, err)
		return
	}

	bucket, err := tag.Bucket(s)
	if err != nil {
		c.AbortWithError(500, err)
		return
	}

	content, found := bucket.Contents[content_path]
	if !found {
		c.AbortWithError(500, fmt.Errorf("content %s not found", content_path))
		return
	}

	content_body, err := ioutil.ReadFile(s.hashFilepath(content.Hash))
	if err != nil {
		c.AbortWithError(500, err)
		return
	}

	content_body, err = decode(content_body, tag.EncryptKey, tag.EncryptIv, content.Attr)
	if err != nil {
		c.AbortWithError(500, err)
		return
	}

	c.Data(200, "text/plain", content_body)
}
Example #8
0
File: api.go Project: niiyz/pgweb
func HandleQuery(query string, c *gin.Context) {
	rawQuery, err := base64.StdEncoding.DecodeString(query)
	if err == nil {
		query = string(rawQuery)
	}

	result, err := DbClient.Query(query)
	if err != nil {
		c.JSON(400, NewError(err))
		return
	}

	q := c.Request.URL.Query()

	if len(q["format"]) > 0 && q["format"][0] == "csv" {
		filename := fmt.Sprintf("pgweb-%v.csv", time.Now().Unix())
		if len(q["filename"]) > 0 && q["filename"][0] != "" {
			filename = q["filename"][0]
		}

		c.Writer.Header().Set("Content-disposition", "attachment;filename="+filename)
		c.Data(200, "text/csv", result.CSV())
		return
	}

	c.JSON(200, result)
}
Example #9
0
func DataStoreGet(r *gin.Context) {
	var patient, module, id string
	patient = r.Param("patient")
	if patient == "" {
		log.Print("DataStoreGet(): No patient provided")
		r.JSON(http.StatusInternalServerError, false)
		return
	}
	module = r.Param("module")
	if module == "" {
		log.Print("DataStoreGet(): No module provided")
		r.JSON(http.StatusInternalServerError, false)
		return
	}
	id = r.Param("id")
	if id == "" {
		log.Print("DataStoreGet(): No id provided")
		r.JSON(http.StatusInternalServerError, false)
		return
	}

	var content []byte
	err := model.DbMap.SelectOne(&content, "SELECT contents FROM pds WHERE patient = ? AND module = LOWER(?) AND id = ?", patient, module, id)
	if err != nil {
		log.Print(err.Error())
		r.JSON(http.StatusInternalServerError, false)
		return
	}

	// TODO: FIXME: Need to properly determine mimetype
	r.Data(http.StatusOK, "application/x-binary", content)
	return
}
Example #10
0
func FindPackagesById(c *gin.Context, d *FindPackagesByIdCommand, q *NuGetQuery, logger *log.Entry) {
	logger.Info("FindPackagesById")

	var match *rekt.Entry
	for _, pkg := range registry.Packages {
		if pkg.Title == d.Id && (q.Filter != "IsLatestVersion" || pkg.IsLatestVersion) {
			match = pkg
		}
	}

	feed := &rekt.Feed{
		Id:      "https://www.example.com/api/v2/FindPackagesById",
		Title:   "FindPackagesById",
		Updated: time.Now(),
		Entries: []*rekt.Entry{match},
	}

	atom, err := feed.ToAtom()
	if err != nil {
		c.Status(500)
		return
	}

	c.Data(200, AtomMimeType, atom)
	return
}
Example #11
0
// this is when we return raw data back to the client
// for fetching files from a workspace
func Fetch(c *gin.Context) {
	// this is the workspace ID
	workspaceId := c.Param("id")
	// this is the relative path of the resource
	resource := c.Param("path")

	// if the resource is empty, then
	// we will render a workspace response
	// see `Workspace`
	if resource == "/" || resource == "" {
		Workspace(c)
		return
	}

	log.Printf("id=\"%s\", resource=\"%s\"", workspaceId, resource)

	// slurp up the entire file, and return it
	// as mime content-type data
	content, err := ioutil.ReadFile(Resolve(workspaceId, resource))
	if err != nil {
		panic(err.Error())
	}

	// use `mime.TypeByExtension` to guess the content-type
	mimetype := mime.TypeByExtension(path.Ext(resource))

	// again gin API is really nice and simple
	c.Data(http.StatusOK, mimetype, content)
}
Example #12
0
// JSONTest is a testing page only, it will be removed when no longer needed.
func JSONTest(c *gin.Context) {
	// user := auth.AuthenticatedUser(c)
	user := auth.User{
		ID:        345,
		Username:  "test.user",
		Email:     "test.user@gmail.com",
		Active:    true,
		Superuser: false,
		Groups: []auth.Group{
			{
				ID:   1,
				Name: "Group 1",
				Permissions: []auth.Permission{
					{ID: 1, Name: "user-create", Description: "Can create users"},
					{ID: 2, Name: "user-update", Description: "Can update users"},
					{ID: 3, Name: "user-delete", Description: "Can delete users"},
					{ID: 4, Name: "user-read", Description: "Can read users"},
				},
			},
			{
				ID:   2,
				Name: "Group 2",
				Permissions: []auth.Permission{
					{ID: 4, Name: "user-read", Description: "Can read users"},
				},
			},
		},
	}
	json, _ := jsonapi.MarshalToJSON(user)

	c.Data(200, "application/vnd.api+json", json)
}
Example #13
0
// ProfilingInfoJSONHandler is a HTTP Handler to return JSON of the Heap memory statistics and any extra info the server wants to tell us about
func ProfilingInfoJSONHandler(c *gin.Context) {
	log.Println("ProfilingInfoJSONHandler")
	// struct for output
	type outputStruct struct {
		HeapInfo         []HeapMemStat
		ExtraServiceInfo map[string]interface{}
	}
	response := outputStruct{}

	// Fetch the most recent memory statistics
	responseChannel := make(chan []TimedMemStats)
	proxyStatsRequestChannel <- responseChannel
	response.HeapInfo = timedMemStatsToHeapMemStats(<-responseChannel)

	// fetch the extra service info, if available
	extraServiceInfoRetrieverMutex.RLock()
	defer extraServiceInfoRetrieverMutex.RUnlock()
	if extraServiceInfoRetriever != nil {
		response.ExtraServiceInfo = extraServiceInfoRetriever()
	}

	// convert to JSON and write to the client
	js, err := json.Marshal(response)
	if err != nil {
		c.Error(err)
		return
	}
	//w.Write(js)
	c.Data(http.StatusOK, "application/json", js)
}
Example #14
0
File: api.go Project: P0rtk3y/api
func HandleRun(c *gin.Context) {
	req, err := ParseRequest(c.Request)
	if err != nil {
		errorResponse(400, err, c)
		return
	}

	config, exists := c.Get("config")
	if !exists {
		errorResponse(400, fmt.Errorf("Cant get config"), c)
		return
	}

	client, exists := c.Get("client")
	if !exists {
		errorResponse(400, fmt.Errorf("Cant get client"), c)
		return
	}

	run := NewRun(config.(*Config), client.(*docker.Client), req)
	defer run.Destroy()

	result, err := performRun(run)
	if err != nil {
		errorResponse(400, err, c)
		return
	}

	c.Header("X-Run-Command", req.Command)
	c.Header("X-Run-ExitCode", strconv.Itoa(result.ExitCode))
	c.Header("X-Run-Duration", result.Duration)

	c.Data(200, req.Format, result.Output)
}
Example #15
0
func serveStaticFile(c *gin.Context, option string) {
	staticFile, err := ioutil.ReadFile(path.Join(RuntimeArgs.SourcePath, "static") + option)
	if err != nil {
		c.AbortWithStatus(404)
	} else {
		c.Data(200, contentType(option), []byte(staticFile))
	}
}
Example #16
0
File: incr.go Project: zserge/incr
func incr(c *gin.Context, s Store, gif bool) {
	s.Incr(c.Param("ns"), strings.TrimSuffix(c.Param("counter"), ".gif"))
	if gif {
		c.Data(200, "image/gif", minimalGIF)
	} else {
		c.AbortWithStatus(200)
	}
}
Example #17
0
func serveStaticAsset(path string, ctx *gin.Context) {
	data, err := Asset("static/dist" + path)
	if err != nil {
		ctx.String(400, err.Error())
		return
	}

	ctx.Data(200, assetContentType(path), data)
}
Example #18
0
func serveStaticAsset(path string, c *gin.Context) {
	data, err := data.Asset("static" + path)
	if err != nil {
		c.String(400, err.Error())
		return
	}

	c.Data(200, assetContentType(path), data)
}
Example #19
0
// Favicon represents the favicon.
func Favicon(c *gin.Context) {
	c.Data(
		http.StatusOK,
		"image/x-icon",
		assets.MustAsset(
			"images/favicon.ico",
		),
	)
}
func DepartmentsDelete(c *gin.Context) {
	d_id := c.Params.ByName("id")

	var department models.Department
	models.DB.Find(&department, d_id)

	models.DB.Delete(&department)
	c.Data(204, gin.MIMEHTML, nil)
}
Example #21
0
func putFile(c *gin.Context) {
	if isIPBanned(c.ClientIP()) {
		c.Data(200, "text/plain", []byte("You are rate limited to 20 requests/hour."))
		return
	}
	filename := c.Param("title")
	if len(filename) == 0 {
		filename = randomAlliterateCombo()
	}
	contentLength := c.Request.ContentLength
	var reader io.Reader
	reader = c.Request.Body
	if contentLength == -1 {
		// queue file to disk, because s3 needs content length
		var err error
		var f io.Reader

		f = reader

		var b bytes.Buffer

		n, err := io.CopyN(&b, f, _24K+1)
		if err != nil && err != io.EOF {
			log.Printf("%s", err.Error())
		}

		if n > _24K {
			file, err := ioutil.TempFile("./", "transfer-")
			if err != nil {
				log.Printf("%s", err.Error())
			}

			defer file.Close()

			n, err = io.Copy(file, io.MultiReader(&b, f))
			if err != nil {
				os.Remove(file.Name())
				log.Printf("%s", err.Error())
			}

			reader, err = os.Open(file.Name())
		} else {
			reader = bytes.NewReader(b.Bytes())
		}

		contentLength = n
	}
	buf := new(bytes.Buffer)
	buf.ReadFrom(reader)
	// p := WikiData{filename, "", []string{}, []string{}, false, ""}
	// p.save(buf.String())
	var p WikiData
	p.load(strings.ToLower(filename))
	p.save(buf.String())
	c.Data(200, "text/plain", []byte("File uploaded to http://"+RuntimeArgs.ExternalIP+"/"+filename))
}
Example #22
0
//APIHome load home page
func APIHome(c *gin.Context) {
	data, err := Asset("static/index.html")

	if err != nil {
		c.String(400, err.Error())
		return
	}

	c.Data(200, "text/html; charset=utf-8", data)
}
Example #23
0
func serveAsset(path string, c *gin.Context) {
	buff, err := server.Asset(path)

	if err != nil {
		c.String(400, err.Error())
		return
	}

	c.Data(200, assetContentType(path), buff)
}
func WorkersDelete(c *gin.Context) {
	w_id := c.Params.ByName("id")

	var worker models.Worker
	models.DB.Find(&worker, w_id)

	models.DB.Delete(&worker)

	c.Data(204, gin.MIMEHTML, nil)
}
func ChildsDelete(c *gin.Context) {
	c_id := c.Params.ByName("id")

	var child models.Child
	models.DB.Find(&child, c_id)

	models.DB.Delete(&child)

	c.Data(204, gin.MIMEHTML, nil)
}
Example #26
0
func GinReturnJson(c *gin.Context, resp *JsonResponse) {
	raw, err := json.MarshalIndent(resp, "", "  ")
	if err != nil {
		log.Fatalf("Internal Error: marshalling of %#v", resp)
	}
	c.Data(resp.StatusCode, ContentTypeJSON, raw)

	// If things get worse, try this:
	//    c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
	//    c.Writer.Header().Set("Content-Length", str(len(raw))
}
Example #27
0
// Delete a todo by id
func (h *TodoHandlers) DeleteTodo(c *gin.Context) {
	id := c.Params.ByName("id")

	if err := h.Client.DeleteTodo(id); err != nil {
		log.Print(err)
		c.JSON(500, "problem decoding body")
		return
	}

	c.Data(204, "application/json", make([]byte, 0))
}
Example #28
0
func staticHandler(c *gin.Context) {
	path := c.Request.URL.Path[1:]
	if path == "" {
		path = "index.html"
	}
	if buf, err := Asset(path); err == nil {
		mimeType := mime.TypeByExtension(filepath.Ext(path))
		c.Data(200, mimeType, buf)
	} else {
		c.Next()
	}
}
Example #29
0
// UserShow is used to show one specific user
// @returns a user struct
func UserShow(c *gin.Context) {
	var user models.User
	database.DBCon.First(&user, c.Param("id"))

	data, err := jsonapi.Marshal(jsonapi.MarshalIncludedRelations(user))

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "couldn't marshal to json"})
	}

	c.Data(http.StatusOK, "application/vnd.api+json", data)
}
Example #30
0
// UserIndex is used when the user's index is routed to
// this handler will run. Generally, it will
// come with some query parameters like limit and offset
// @returns an array of users
func UserIndex(c *gin.Context) {
	var users []models.User
	number, err := strconv.Atoi(c.Param("limit"))
	database.DBCon.Limit(number).Find(&users)

	data, err := jsonapi.Marshal(users)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "couldn't marshal to json"})
	}

	c.Data(http.StatusOK, "application/vnd.api+json", data)
}