Beispiel #1
0
/**

	TODO:
	- Get email and password from post request
	- Find user

**/
func (a *authController) Login(c *gin.Context) {
	var userLogin models.UserLogin
	if err := c.Bind(&userLogin); err != nil {
		panic(err)
	}
	user, err := authResource.Login(userLogin.Email, userLogin.Password)
	if err != nil {
		c.Error(err)
		return
	}
	token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256"))
	// Set some claims
	token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix()
	// Sign and get the complete encoded token as a string
	apiKey, err := token.SignedString([]byte(config.GetSecret()))
	if err != nil {
		c.Error(apiErrors.ThrowError(apiErrors.ServerError))
		return
	}
	// Remove password
	user.Password = ""

	c.JSON(200, gin.H{
		"user":    user,
		"api-key": apiKey,
	})
}
Beispiel #2
0
// convertByURLHandler is the main v1 API handler for converting a HTML to a PDF
// via a GET request. It can either return a JSON string indicating that the
// output of the conversion has been uploaded or it can return the output of
// the conversion to the client (raw bytes).
func convertByURLHandler(c *gin.Context) {
	s := c.MustGet("statsd").(*statsd.Client)
	r, ravenOk := c.Get("sentry")

	url := c.Query("url")
	if url == "" {
		c.AbortWithError(http.StatusBadRequest, ErrURLInvalid).SetType(gin.ErrorTypePublic)
		s.Increment("invalid_url")
		return
	}

	ext := c.Query("ext")

	source, err := converter.NewConversionSource(url, nil, ext)
	if err != nil {
		s.Increment("conversion_error")
		if ravenOk {
			r.(*raven.Client).CaptureError(err, map[string]string{"url": url})
		}
		c.Error(err)
		return
	}

	conversionHandler(c, *source)
}
Beispiel #3
0
// NewController posts new blogs
func NewController(c *gin.Context) {

	// holds our page metadata from settings
	metadata, err := u.GetMetadata()
	if err != nil {
		c.Error(err).SetMeta("blog.NewController.GetMetadata")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	vals := struct {
		Meta m.Metadata
		Csrf string
		New  bool
		Edit bool
	}{
		Meta: metadata,
		Csrf: c.MustGet("csrf_token").(string),
		New:  true,
		Edit: false,
	}

	c.HTML(http.StatusOK, "blogedit.tmpl", vals)

	return

}
Beispiel #4
0
func install(ctx *gin.Context) {
	owner, name := ctx.Param("owner"), ctx.Param("name")
	u := ghauth.User(ctx)

	hookName := "web"
	hook := &github.Hook{}
	hook.Name = &hookName
	hookPath := randString(20)
	hookSecret := randString(20)
	hook.Config = map[string]interface{}{
		"url":          fmt.Sprintf("%s/hooks/%s", appConfig.UrlBase, hookPath),
		"content_type": "json",
		"secret":       hookSecret,
	}
	hook.Events = []string{"issue_comment", "issues", "pull_request_review_comment", "pull_request", "push", "status"}
	hook, _, err := u.Client().Repositories.CreateHook(owner, name, hook)
	if err != nil {
		ctx.Error(err)
		return
	}
	if err = registerHook(owner, name, hookPath, hookSecret, *hook.ID, u.Token); err != nil {
		ctx.Error(err)
		return
	}
	ctx.Redirect(302, fmt.Sprintf("/repo/%s/%s", owner, name))
}
Beispiel #5
0
func ShowEpisodes(ctx *gin.Context) {
	show, err := tvdb.NewShowCached(ctx.Params.ByName("showId"), config.Get().Language)
	if err != nil {
		ctx.Error(err)
		return
	}

	seasonNumber, _ := strconv.Atoi(ctx.Params.ByName("season"))

	season := show.Seasons[seasonNumber]
	items := season.Episodes.ToListItems(show)
	for _, item := range items {
		item.Path = UrlForXBMC("/show/%d/season/%d/episode/%d/play",
			show.Id,
			season.Season,
			item.Info.Episode,
		)
		item.ContextMenu = [][]string{
			[]string{"LOCALIZE[30202]", fmt.Sprintf("XBMC.PlayMedia(%s)", UrlForXBMC("/show/%d/season/%d/episode/%d/links",
				show.Id,
				season.Season,
				item.Info.Episode,
			))},
			[]string{"LOCALIZE[30203]", "XBMC.Action(Info)"},
		}
		item.IsPlayable = true
	}

	ctx.JSON(200, xbmc.NewView("episodes", items))
}
Beispiel #6
0
func convertByFileHandler(c *gin.Context) {
	s := c.MustGet("statsd").(*statsd.Client)
	r, ravenOk := c.Get("sentry")

	file, header, err := c.Request.FormFile("file")
	if err != nil {
		c.AbortWithError(http.StatusBadRequest, ErrFileInvalid).SetType(gin.ErrorTypePublic)
		s.Increment("invalid_file")
		return
	}

	ext := c.Query("ext")

	source, err := converter.NewConversionSource("", file, ext)
	if err != nil {
		s.Increment("conversion_error")
		if ravenOk {
			r.(*raven.Client).CaptureError(err, map[string]string{"url": header.Filename})
		}
		c.Error(err)
		return
	}

	conversionHandler(c, *source)
}
Beispiel #7
0
func (u *userHandler) Edit(c *gin.Context) {
	var user models.User

	currentUser := utils.MustGetCurrentUser(c)

	if err := c.Bind(&user); err != nil {
		errors := userResource.ParseError(err)
		if len(errors) > 0 {
			c.Error(errors[0])
			return
		}
	}
	userId := c.Param("userId")

	if currentUser.Role != models.Admin {
		user.Role = models.NormalUser
	}
	if currentUser.Role == models.NormalUser {
		user.DeleteAt = nil
	}

	if err := userResource.Edit(userId, &user); err != nil {
		c.AbortWithError(400, err)
		return
	}
	c.JSON(200, user)
}
Beispiel #8
0
func Login(c *gin.Context) {
	loginData := LoginData{}
	err := c.Bind(&loginData)
	if err != nil {
		c.JSON(http.StatusBadRequest, err)
		return
	}

	db := utils.GetDb(c)
	err, user := userdb.GetOne(db, bson.M{
		"username": loginData.Username,
	})

	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(loginData.Password))
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"success": false,
			"message": "The username or password don't match",
		})
		return
	}

	token, err := CreateJwtToken(user.ID.Hex())
	if err != nil {
		c.Error(err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success":  true,
		"id_token": token,
	})
}
Beispiel #9
0
// InputController is the handler for the page where people can enter the gallery password
func InputController(c *gin.Context) {

	comicID, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.Error(err).SetMeta("keys.InputController")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	// holds out page metadata from settings
	metadata, err := u.GetMetadata()
	if err != nil {
		c.Error(err).SetMeta("keys.InputController.GetMetadata")
		c.HTML(http.StatusInternalServerError, "error.tmpl", nil)
		return
	}

	vals := struct {
		Meta m.Metadata
		ID   int
	}{
		Meta: metadata,
		ID:   comicID,
	}

	c.HTML(http.StatusOK, "gallerypassword.tmpl", vals)

	return

}
Beispiel #10
0
func RestError(c *gin.Context, err interface{}) {
	status := http.StatusInternalServerError

	var msg string
	switch t := err.(type) {
	case error:
		msg = t.Error()
	case string:
		msg = t
	}

	if msg == "not found" || msg == "app not found" {
		status = http.StatusNotFound
	} else if msg == "invalid request body" {
		status = http.StatusBadRequest
	} else if msg == "ns not found" {
		//mongo throws this error when a collection does not exist
		//but we call drop
		return
	}

	c.Error(errors.New(msg))

	c.JSON(status, JSON{
		"error": msg,
	})
}
Beispiel #11
0
// Execute command, intercepts stdout and print info
func commandWrapper(c *gin.Context, command string, args []string) {
	old_stdout := os.Stdout // keep backup of the real stdout
	old_stderr := os.Stderr // keep backup of the real stdout
	r, w, _ := os.Pipe()
	os.Stdout = w
	os.Stderr = w

	err := lxclib.RunCommand(config, command, args)
	if err != nil {
		c.String(400, err.Error())
		c.Error(err)
	}

	outC := make(chan string)
	// copy the output in a separate goroutine so printing can't block indefinitely
	go func() {
		var buf bytes.Buffer
		io.Copy(&buf, r)
		outC <- buf.String()
	}()

	// back to normal state
	w.Close()
	os.Stdout = old_stdout // restoring the real stdout
	os.Stderr = old_stderr // restoring the real stdout
	out := <-outC

	c.String(200, out)
}
Beispiel #12
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)
}
Beispiel #13
0
func ShowEpisodeLinks(ctx *gin.Context) {
	seasonNumber, _ := strconv.Atoi(ctx.Params.ByName("season"))
	episodeNumber, _ := strconv.Atoi(ctx.Params.ByName("episode"))
	torrents, err := showEpisodeLinks(ctx.Params.ByName("showId"), seasonNumber, episodeNumber)
	if err != nil {
		ctx.Error(err)
		return
	}

	if len(torrents) == 0 {
		xbmc.Notify("Quasar", "LOCALIZE[30205]", config.AddonIcon())
		return
	}

	choices := make([]string, 0, len(torrents))
	for _, torrent := range torrents {
		label := fmt.Sprintf("S:%d P:%d - %s",
			torrent.Seeds,
			torrent.Peers,
			torrent.Name,
		)
		choices = append(choices, label)
	}

	choice := xbmc.ListDialog("LOCALIZE[30202]", choices...)
	if choice >= 0 {
		rUrl := UrlQuery(UrlForXBMC("/play"), "uri", torrents[choice].Magnet())
		ctx.Redirect(302, rUrl)
	}
}
Beispiel #14
0
func ShowEpisodePlay(ctx *gin.Context) {
	tmdbId := ctx.Params.ByName("showId")
	showId, _ := strconv.Atoi(tmdbId)
	seasonNumber, _ := strconv.Atoi(ctx.Params.ByName("season"))
	episodeNumber, _ := strconv.Atoi(ctx.Params.ByName("episode"))

	show := tmdb.GetShow(showId, "")
	episode := tmdb.GetEpisode(showId, seasonNumber, episodeNumber, "")

	runtime := 45
	if len(show.EpisodeRunTime) > 0 {
		runtime = show.EpisodeRunTime[len(show.EpisodeRunTime)-1]
	}

	torrents, err := showEpisodeLinks(showId, seasonNumber, episodeNumber)
	if err != nil {
		ctx.Error(err)
		return
	}

	if len(torrents) == 0 {
		xbmc.Notify("Quasar", "LOCALIZE[30205]", config.AddonIcon())
		return
	}

	AddToTorrentsMap(strconv.Itoa(episode.Id), torrents[0])

	rUrl := UrlQuery(UrlForXBMC("/play"), "uri", torrents[0].Magnet(),
		"tmdb", strconv.Itoa(episode.Id),
		"type", "episode",
		"runtime", strconv.Itoa(runtime))
	ctx.Redirect(302, rUrl)
}
Beispiel #15
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)
}
Beispiel #16
0
func deployReplicasModify(ginCtx *gin.Context) {
	name := ginCtx.Params.ByName("name")
	num := ginCtx.Params.ByName("num")
	force := ginCtx.Query("force")
	fs := false
	if force == "true" {
		fs = true
	}
	glog.Info("scaling %s to %d instances", name, num)
	replicas, err := strconv.Atoi(num)
	if err != nil {
		glog.Errorf("Could not change instances for %s, caused by %s", name, err)
		ginCtx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		ginCtx.Error(err)
		return
	}
	var beReq = &ScaleRequest{Name: name, Replicas: replicas, Force: fs}

	_, err = se.Backend.Scale(beReq)
	if err != nil {
		glog.Errorf("Could not change instances for %s, caused by: %s", name, err.Error())
		ginCtx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		ginCtx.Error(err)
		return
	}
	ginCtx.JSON(http.StatusOK, gin.H{})
}
Beispiel #17
0
// Edit an event
func Edit(c *gin.Context) {
	db := c.MustGet("db").(*mgo.Database)
	form := FormEvent{
		Channels: []kdb.Channel{
			kdb.Channel{Name: "email", Enabled: false},
			kdb.Channel{Name: "web", Enabled: false},
			kdb.Channel{Name: "push", Enabled: false},
		},
	}
	oID := bson.ObjectIdHex(c.Param("_id"))
	err := db.C(kdb.AvailableTopicCollection).FindId(oID).One(&form.Event)
	if err != nil {
		c.Error(err)
	}

	for i, v := range form.Channels {
		for _, value := range form.Event.Channels {
			if v.Name == value {
				form.Channels[i].Enabled = true
			}
		}
	}

	c.HTML(http.StatusOK, "events/form", gin.H{
		"title": "Edit event",
		"form":  form,
	})
}
Beispiel #18
0
func ApiError(c *gin.Context, statusCode int, clientError error, realError error) {
	c.Error(realError)
	c.Error(clientError)
	c.JSON(statusCode, gin.H{
		"error": clientError.Error(),
	})
	log.Print(realError)
}
Beispiel #19
0
func GetAllSchools(c *gin.Context) {
	schools, err := db.GetAllSchools()
	if log.Error(err) {
		c.Error(errors.NewISE())
		return
	}
	c.JSON(http.StatusOK, schools)
}
Beispiel #20
0
// Delete an event
func Delete(c *gin.Context) {
	db := c.MustGet("db").(*mgo.Database)
	query := bson.M{"_id": bson.ObjectIdHex(c.Param("_id"))}
	err := db.C(kdb.AvailableTopicCollection).Remove(query)
	if err != nil {
		c.Error(err)
	}
	c.Redirect(http.StatusMovedPermanently, "/events")
}
Beispiel #21
0
// Delete an article
func Delete(c *gin.Context) {
	db := c.MustGet("db").(*mgo.Database)
	query := bson.M{"_id": bson.ObjectIdHex(c.Param("_id"))}
	err := db.C(models.CollectionArticle).Remove(query)
	if err != nil {
		c.Error(err)
	}
	c.Redirect(http.StatusMovedPermanently, "/articles")
}
Beispiel #22
0
func sendMeta(name string, c *gin.Context) {
	db := utils.GetDb(c)
	err, res := getData(db, name)
	if err != nil {
		c.Error(err)
		return
	}
	c.JSON(http.StatusOK, res)
}
Beispiel #23
0
func ShowEpisodeLinks(ctx *gin.Context) {
	seasonNumber, _ := strconv.Atoi(ctx.Params.ByName("season"))
	episodeNumber, _ := strconv.Atoi(ctx.Params.ByName("episode"))
	torrents, longName, err := showEpisodeLinks(ctx.Params.ByName("showId"), seasonNumber, episodeNumber)
	if err != nil {
		ctx.Error(err)
		return
	}

	if len(torrents) == 0 {
		xbmc.Notify("Quasar", "LOCALIZE[30205]", config.AddonIcon())
		return
	}

	choices := make([]string, 0, len(torrents))
	for _, torrent := range torrents {
		info := make([]string, 0)
		if torrent.Resolution > 0 {
			info = append(info, bittorrent.Resolutions[torrent.Resolution])
		}
		if torrent.Size != "" {
			info = append(info, fmt.Sprintf("[%s]", torrent.Size))
		}
		if torrent.RipType > 0 {
			info = append(info, bittorrent.Rips[torrent.RipType])
		}
		if torrent.VideoCodec > 0 {
			info = append(info, bittorrent.Codecs[torrent.VideoCodec])
		}
		if torrent.AudioCodec > 0 {
			info = append(info, bittorrent.Codecs[torrent.AudioCodec])
		}
		if torrent.Provider != "" {
			info = append(info, " - "+torrent.Provider)
		}

		torrentName := torrent.Name
		if len(torrentName) > 80 {
			torrentName = torrentName[:80]
		}

		label := fmt.Sprintf("[B](%d / %d) %s[/B]\n%s",
			torrent.Seeds,
			torrent.Peers,
			strings.Join(info, " "),
			torrentName,
		)
		choices = append(choices, label)
	}

	choice := xbmc.ListDialogLarge("LOCALIZE[30228]", longName, choices...)
	if choice >= 0 {
		rUrl := UrlQuery(UrlForXBMC("/play"), "uri", torrents[choice].Magnet())
		ctx.Redirect(302, rUrl)
	}
}
Beispiel #24
0
func GetOne(c *gin.Context) {
	db := utils.GetDb(c)
	id := c.Params.ByName("id")
	err, sub := subdb.GetOne(db, id)
	if err != nil {
		c.Error(err)
		return
	}
	c.JSON(http.StatusOK, sub)
}
Beispiel #25
0
func GetSystem(c *gin.Context) {
	id := c.Params.ByName("id")
	system_id, err := strconv.ParseInt(id, 0, 16)
	if err != nil {
		c.Error(err)
		return
	}
	system := db.Where(&m.System{Id: system_id})
	c.JSON(http.StatusOK, system.Value)
}
Beispiel #26
0
func GetList(c *gin.Context) {
	db := utils.GetDb(c)
	query := BuildQuery(c)
	err, subs := subdb.GetList(db, query)
	if err != nil {
		c.Error(err)
		return
	}
	c.JSON(http.StatusOK, subs)
}
Beispiel #27
0
func GetAddonsXMLChecksum(ctx *gin.Context) {
	user := ctx.Params.ByName("user")
	repository := ctx.Params.ByName("repository")
	addons, err := getAddons(user, repository)
	if err != nil {
		ctx.Error(errors.New("Unable to retrieve the remote's addon.xml file."))
	}
	hasher := md5.New()
	xml.NewEncoder(hasher).Encode(addons)
	ctx.String(200, hex.EncodeToString(hasher.Sum(nil)))
}
Beispiel #28
0
// userById attempts to return a JSON response for the supplied userid
// couchbase errors are handled in the handleError middleware method
func userById(c *gin.Context) {
	myCluster, _ := gocb.Connect("couchbase://localhost")
	myBucket, _ := myCluster.OpenBucket("gamesim-sample", "")
	var value interface{}
	_, err := myBucket.Get(c.Params.ByName("userid"), &value)
	if err != nil {
		c.Error(err).SetType(gin.ErrorTypePublic)
	} else {
		c.JSON(http.StatusOK, &value)
	}
}
Beispiel #29
0
func RenderSoy(c *gin.Context) {
	var testdata = []data.Map{
		{"names": data.List{}},
		{"names": data.List{data.String("Rob")}},
		{"names": data.List{data.String("Rob"), data.String("Joe")}},
	}
	if err := tofu.Render(c.Writer, "soy.examples.simple.helloNames", testdata[2]); err != nil {
		c.Error(err)
		return
	}
}
Beispiel #30
0
func EchoWebsocket(c *gin.Context) {
	conn, err := websocketUpgrader.Upgrade(c.Writer, c.Request, nil)
	if log.Error(err) {
		c.Error(errors.NewISE())
		return
	}
	for {
		typ, frame, _ := conn.ReadMessage()
		conn.WriteMessage(typ, frame)
	}
}