// POST /api/repos func apiReposCreate(c *gin.Context) { var b struct { Name string `binding:"required"` Comment string DefaultDistribution string DefaultComponent string } if !c.Bind(&b) { return } repo := deb.NewLocalRepo(b.Name, b.Comment) repo.DefaultComponent = b.DefaultComponent repo.DefaultDistribution = b.DefaultDistribution collection := context.CollectionFactory().LocalRepoCollection() collection.Lock() defer collection.Unlock() err := context.CollectionFactory().LocalRepoCollection().Add(repo) if err != nil { c.Fail(400, err) return } c.JSON(201, repo) }
//PUT /api/repos/:name func editRepo(c *gin.Context) { var b struct { Comment string DefaultDistribution string DefaultComponent string } if !c.Bind(&b) { return } repo, err := api.RepoEdit(c.Params.ByName("name"), func(r *deb.LocalRepo) { if b.Comment != "" { r.Comment = b.Comment } if b.DefaultDistribution != "" { r.DefaultDistribution = b.DefaultDistribution } if b.DefaultComponent != "" { r.DefaultComponent = b.DefaultComponent } }) if err != nil { c.Fail(500, err) return } c.JSON(200, repo) }
// Creates a datafile func (e EndpointContext) CreateDataFileEndpoint(c *gin.Context) { user := c.MustGet(MIDDLEWARE_KEY_USER).(User) db := c.MustGet(MIDDLEWARE_KEY_DB).(couch.Database) datafile := NewDatafile(e.Configuration) datafile.UserID = user.DocId() // bind the Datafile to the JSON request, which will bind the // url field or throw an error. if ok := c.Bind(&datafile); !ok { errMsg := fmt.Sprintf("Invalid datafile") c.Fail(400, errors.New(errMsg)) return } logg.LogTo("REST", "datafile: %+v", datafile) // create a new Datafile object in db datafile, err := datafile.Save(db) if err != nil { errMsg := fmt.Sprintf("Error creating new datafile: %v", err) c.Fail(500, errors.New(errMsg)) return } c.JSON(201, gin.H{"id": datafile.Id}) }
// GET /publish func apiPublishList(c *gin.Context) { localCollection := context.CollectionFactory().LocalRepoCollection() localCollection.RLock() defer localCollection.RUnlock() snapshotCollection := context.CollectionFactory().SnapshotCollection() snapshotCollection.RLock() defer snapshotCollection.RUnlock() collection := context.CollectionFactory().PublishedRepoCollection() collection.RLock() defer collection.RUnlock() result := make([]*deb.PublishedRepo, 0, collection.Len()) err := collection.ForEach(func(repo *deb.PublishedRepo) error { err := collection.LoadComplete(repo, context.CollectionFactory()) if err != nil { return err } result = append(result, repo) return nil }) if err != nil { c.Fail(500, err) return } c.JSON(200, result) }
func publishRepoOrSnapshot(c *gin.Context) { prefix := c.Params.ByName("prefix") var b struct { SourceKind string Sources []data_api.PublishSource Distribution string Label string Origin string ForceOverwrite bool Architectures []string Signing data_api.SigningOptions } if !c.Bind(&b) { return } //prefix, distribution, label, origin string, sourceKind string, sources []PublishSource, // forceOverwrite bool, architectures []string, signingOptions SigningOptions repo, err := api.PublishRepoOrSnapshot(prefix, b.Distribution, b.Label, b.Origin, b.SourceKind, b.Sources, b.ForceOverwrite, b.Architectures, b.Signing) if err != nil { c.Fail(400, err) return } c.JSON(200, repo) }
// GET /files/:dir func apiFilesListFiles(c *gin.Context) { if !verifyDir(c) { return } list := []string{} root := filepath.Join(context.UploadPath(), c.Params.ByName("dir")) err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if path == root { return nil } list = append(list, filepath.Base(path)) return nil }) if err != nil { if os.IsNotExist(err) { c.Fail(404, err) } else { c.Fail(500, err) } return } c.JSON(200, list) }
// DELETE /publish/:prefix/:distribution func apiPublishDrop(c *gin.Context) { force := c.Request.URL.Query().Get("force") == "1" param := parseEscapedPath(c.Params.ByName("prefix")) storage, prefix := deb.ParsePrefix(param) distribution := c.Params.ByName("distribution") // published.LoadComplete would touch local repo collection localRepoCollection := context.CollectionFactory().LocalRepoCollection() localRepoCollection.RLock() defer localRepoCollection.RUnlock() collection := context.CollectionFactory().PublishedRepoCollection() collection.Lock() defer collection.Unlock() err := collection.Remove(context, storage, prefix, distribution, context.CollectionFactory(), context.Progress(), force) if err != nil { c.Fail(500, fmt.Errorf("unable to drop: %s", err)) return } c.JSON(200, gin.H{}) }
func SignUpload(c *gin.Context) { user, err := GetUserFromContext(c) if err != nil { c.Fail(500, err) } var json UploadJSON c.Bind(&json) key := `attachments/` + user.Id + `/` + uuid.NewUUID().String() + extensions[json.ContentType] f := &Form{ Key: key, ACL: "public-read", AWSAccessKeyId: os.Getenv("AWS_ACCESS_KEY_ID"), CacheControl: "max-age=31557600", ContentType: json.ContentType, } f.build() href := "https://s3.amazonaws.com/" + os.Getenv("S3_BUCKET") + "/" + key c.JSON(200, gin.H{"form": f, "href": href}) }
func mirrorEdit(c *gin.Context) { var b struct { Filter string FilterWithDeps bool Architectures []string WithSources bool WithUdebs bool } if !c.Bind(&b) { return } mirror, err := api.MirrorEdit(c.Params.ByName("name"), func(m *deb.RemoteRepo) error { m.Filter = b.Filter m.FilterWithDeps = b.FilterWithDeps m.DownloadSources = b.WithSources m.DownloadUdebs = b.WithUdebs m.Architectures = b.Architectures return nil }) if err != nil { c.Fail(400, err) return } c.JSON(200, mirror) }
//POST /api/mirrors func mirrorCreate(c *gin.Context) { var b struct { Name string `binding:"required"` ArchiveUrl string `binding:"required"` Distribution string `binding:"required"` Components []string `binding:"required"` Filter string FilterWithDeps bool WithSources bool WithUdebs bool ForceComponents bool } if !c.Bind(&b) { return } //name, url, filter, distribution string, components []string, withSources, withUdebs, filterWithDeps, forceComponents bool repo, err := api.MirrorCreate(b.Name, b.ArchiveUrl, b.Filter, b.Distribution, b.Components, b.WithSources, b.WithUdebs, b.FilterWithDeps, b.ForceComponents) if err != nil { c.Fail(400, err) return } c.JSON(200, repo) }
// GET /files func apiFilesListDirs(c *gin.Context) { list := []string{} err := filepath.Walk(context.UploadPath(), func(path string, info os.FileInfo, err error) error { if err != nil { return err } if path == context.UploadPath() { return nil } if info.IsDir() { list = append(list, filepath.Base(path)) return filepath.SkipDir } return nil }) if err != nil && !os.IsNotExist(err) { c.Fail(400, err) return } c.JSON(200, list) }
// POST /api/mirrors/:name/snapshots/ func apiSnapshotsCreateFromMirror(c *gin.Context) { var ( err error repo *deb.RemoteRepo snapshot *deb.Snapshot ) var b struct { Name string `binding:"required"` Description string } if !c.Bind(&b) { return } collection := context.CollectionFactory().RemoteRepoCollection() collection.RLock() defer collection.RUnlock() snapshotCollection := context.CollectionFactory().SnapshotCollection() snapshotCollection.Lock() defer snapshotCollection.Unlock() repo, err = collection.ByName(c.Params.ByName("name")) if err != nil { c.Fail(404, err) return } err = repo.CheckLock() if err != nil { c.Fail(409, err) return } err = collection.LoadComplete(repo) if err != nil { c.Fail(500, err) return } snapshot, err = deb.NewSnapshotFromRepository(b.Name, repo) if err != nil { c.Fail(400, err) return } if b.Description != "" { snapshot.Description = b.Description } err = snapshotCollection.Add(snapshot) if err != nil { c.Fail(400, err) return } c.JSON(201, snapshot) }
// Create Training Job func (e EndpointContext) CreateTrainingJob(c *gin.Context) { // bind to json user := c.MustGet(MIDDLEWARE_KEY_USER).(User) db := c.MustGet(MIDDLEWARE_KEY_DB).(couch.Database) trainingJob := NewTrainingJob(e.Configuration) trainingJob.UserID = user.Id // bind the input struct to the JSON request if ok := c.Bind(trainingJob); !ok { errMsg := fmt.Sprintf("Invalid input") c.Fail(400, errors.New(errMsg)) return } logg.LogTo("REST", "Create new TrainingJob: %+v", trainingJob) // save training job in db trainingJob, err := trainingJob.Insert(db) if err != nil { c.Fail(500, err) return } // job will get kicked off by changes listener // return solver object c.JSON(201, *trainingJob) }
//GET /api/repos/:name func showRepo(c *gin.Context) { repo, err := api.RepoShow(c.Params.ByName("name")) if err != nil { c.Fail(404, err) return } c.JSON(200, repo) }
/// Test 2: Single database query func db(c *gin.Context) { var world World err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&world.Id, &world.RandomNumber) if err != nil { c.Fail(500, err) } c.JSON(200, &world) }
func mirrorShow(c *gin.Context) { mirror, err := api.MirrorShow(c.Params.ByName("name")) if err != nil { c.Fail(400, err) return } c.JSON(200, mirror) }
func mirrorPackages(c *gin.Context) { packages, err := api.MirrorShowPackages(c.Params.ByName("name")) if err != nil { c.Fail(400, err) return } c.JSON(200, packages) }
func publishList(c *gin.Context) { results, err := api.PublishList() if err != nil { c.Fail(500, err) return } c.JSON(200, results) }
//GET /api/repos/:name/packages func repoShowPackages(c *gin.Context) { packages, err := api.RepoShowPackages(c.Params.ByName("name")) if err != nil { c.Fail(404, err) return } c.JSON(200, packages) }
func snapshotShow(c *gin.Context) { snapshot, err := api.SnapshotShow(c.Params.ByName("name")) if err != nil { c.Fail(400, err) return } c.JSON(200, snapshot) }
func verifyDir(c *gin.Context) bool { if !verifyPath(c.Params.ByName("dir")) { c.Fail(400, fmt.Errorf("wrong dir")) return false } return true }
func snapshotDrop(c *gin.Context) { force := c.Request.URL.Query().Get("force") == "1" err := api.SnapshotDrop(c.Params.ByName("name"), force) if err != nil { c.Fail(400, err) return } c.JSON(200, gin.H{}) }
func snapshotDiff(c *gin.Context) { onlyMatching := c.Request.URL.Query().Get("onlyMatching") == "1" diff, err := api.SnapshotDiff(c.Params.ByName("name"), c.Params.ByName("other"), onlyMatching) if err != nil { c.Fail(400, err) return } c.JSON(200, diff) }
// GET /api/packages/:key func apiPackagesShow(c *gin.Context) { p, err := context.CollectionFactory().PackageCollection().ByKey([]byte(c.Params.ByName("key"))) if err != nil { c.Fail(404, err) return } c.JSON(200, p) }
func (s *Server) AuthCallback(c *gin.Context) { fn := gothic.GetProviderName gothic.GetProviderName = func(req *http.Request) (string, error) { provider := c.Params.ByName("provider") if provider == "" { return fn(req) } return provider, nil } provider, _ := gothic.GetProviderName(c.Request) u, err := gothic.CompleteUserAuth(c.Writer, c.Request) if err != nil { c.String(400, err.Error()) return } ctx, cancel := DefaultTimeoutContext() defer cancel() authinfo := &pb.OAuthUser{ UserId: u.UserID, Name: u.Name, NickName: u.NickName, Email: u.Email, AccessToken: u.AccessToken, AccessTokenSecret: u.AccessTokenSecret, Provider: provider, } profile, err := s.CurrentUser(c) if err != nil { c.Fail(500, err) return } authinfo.Uuid = profile.Uuid profile, err = s.client.PutOAuth(ctx, authinfo) if RequestError(c, err) { return } // Only allow login from google // Twitter only for importing feed if provider == "google" { sess := sessions.Default(c) sess.Set("user_id", u.UserID) sess.Set("uuid", profile.Uuid) sess.Save() } next := extractNextPath(c.Request.URL.Query().Get("state")) if next == "/" && provider == "twitter" { next = "/account/import" } http.Redirect(c.Writer, c.Request, next, http.StatusFound) }
// RoomsTeamIndex simply fetches all of the rooms that have // been created for the given team. func RoomsTeamIndex(c *gin.Context) { teamID := models.FindTeamBySlug(c.Params.ByName("slug")).Id rooms, err := models.FindRooms(teamID) if err != nil { c.Fail(500, err) } c.JSON(200, gin.H{ "rooms": rooms, }) }
/// Test 3: Multiple database queries func dbs(c *gin.Context) { numQueries := parseQueries(c) worlds := make([]World, numQueries) for i := 0; i < numQueries; i++ { err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&worlds[i].Id, &worlds[i].RandomNumber) if err != nil { c.Fail(500, err) } } c.JSON(200, &worlds) }
func publishDrop(c *gin.Context) { prefix := c.Params.ByName("prefix") distribution := c.Params.ByName("distribution") force := c.Request.URL.Query().Get("force") == "1" err := api.PublishDrop(prefix, distribution, force) if err != nil { c.Fail(400, err) return } c.JSON(200, gin.H{}) }
func RoomsDelete(c *gin.Context) { user, err := GetUserFromContext(c) if err != nil { c.Fail(500, err) } err = models.DeleteRoom(c.Params.ByName("room"), user.TeamId) if err != nil { c.Fail(500, err) } c.String(200, "ok") }
// GET /api/repos/:name func apiReposShow(c *gin.Context) { collection := context.CollectionFactory().LocalRepoCollection() collection.RLock() defer collection.RUnlock() repo, err := collection.ByName(c.Params.ByName("name")) if err != nil { c.Fail(404, err) return } c.JSON(200, repo) }