diff --git a/examples/balances/main.go b/examples/balances/main.go new file mode 100644 index 00000000..54e80a7e --- /dev/null +++ b/examples/balances/main.go @@ -0,0 +1,61 @@ +// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. +// Use of this source code is governed by a MIT license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT + +package main + +import ( + "context" + "log" + "os" + + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1" + client "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/prerecorded" +) + +func main() { + // context + ctx := context.Background() + + //client + dg := client.NewWithDefaults() + mgClient := api.New(dg) + + // list projects + respProject, err := mgClient.ListProjects(ctx) + if err != nil { + log.Printf("ListProjects failed. Err: %v\n", err) + os.Exit(1) + } + + var projectId string + for _, item := range respProject.Projects { + projectId = item.ProjectId + name := item.Name + log.Printf("ListProjects() - Name: %s, ID: %s\n", name, projectId) + break + } + + // list balances + respList, err := mgClient.ListBalances(ctx, projectId) + if err != nil { + log.Printf("ListBalances failed. Err: %v\n", err) + os.Exit(1) + } + + var amount float64 + var id string + for _, item := range respList.Balances { + id = item.BalanceId + amount = item.Amount + log.Printf("ListBalances() - ID: %s, Amount: %f\n", id, amount) + } + + // get first balance + respGet, err := mgClient.GetBalance(ctx, projectId, id) + if err != nil { + log.Printf("GetBalance failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("GetBalance() - ID: %s, Amount: %f\n", id, respGet.Amount) +} diff --git a/examples/invitations/main.go b/examples/invitations/main.go new file mode 100644 index 00000000..acc41d45 --- /dev/null +++ b/examples/invitations/main.go @@ -0,0 +1,106 @@ +// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. +// Use of this source code is governed by a MIT license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT + +package main + +import ( + "context" + "log" + "os" + + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1" + interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1/interfaces" + client "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/prerecorded" +) + +func main() { + // context + ctx := context.Background() + + //client + dg := client.NewWithDefaults() + mgClient := api.New(dg) + + // list projects + respList, err := mgClient.ListProjects(ctx) + if err != nil { + log.Printf("ListProjects failed. Err: %v\n", err) + os.Exit(1) + } + + var projectId string + for _, item := range respList.Projects { + projectId = item.ProjectId + name := item.Name + log.Printf("ListProjects() - Name: %s, ID: %s\n", name, projectId) + break + } + + // list invitations + respGet, err := mgClient.ListInvitations(ctx, projectId) + if err != nil { + log.Printf("ListInvitations failed. Err: %v\n", err) + os.Exit(1) + } + + for _, item := range respGet.Invites { + id := item.Email + scope := item.Scope + log.Printf("ListInvitations() - ID: %s, Scope: %s\n", id, scope) + } + + // send invite + respMessage, err := mgClient.SendInvitation(ctx, projectId, &interfaces.InvitationRequest{ + Email: "spam@spam.com", + Scope: "member", + }) + if err != nil { + log.Printf("SendInvitation failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("SendInvitation() - Name: %s\n", respMessage.Message) + + // list invitations + respGet, err = mgClient.ListInvitations(ctx, projectId) + if err != nil { + log.Printf("ListInvitations failed. Err: %v\n", err) + os.Exit(1) + } + + for _, item := range respGet.Invites { + id := item.Email + scope := item.Scope + log.Printf("ListInvitations() - ID: %s, Scope: %s\n", id, scope) + } + + // delete project + respMessage, err = mgClient.DeleteInvitation(ctx, projectId, "spam@spam.com") + if err != nil { + log.Printf("DeleteInvitation failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("DeleteInvitation() - Name: %s\n", respMessage.Message) + + // list invitations + respGet, err = mgClient.ListInvitations(ctx, projectId) + if err != nil { + log.Printf("ListInvitations failed. Err: %v\n", err) + os.Exit(1) + } + + for _, item := range respGet.Invites { + id := item.Email + scope := item.Scope + log.Printf("ListInvitations() - ID: %s, Scope: %s\n", id, scope) + } + + // TODO: There isnt an API call to add a member to a project. So will leave this commented out as an example + // Leave Project + // respMessage, err = mgClient.LeaveProject(ctx, projectId) + // if err != nil { + // log.Printf("LeaveProject failed. Err: %v\n", err) + // os.Exit(1) + // } + // log.Printf("LeaveProject() - Name: %s\n", respMessage.Message) +} diff --git a/examples/keys/main.go b/examples/keys/main.go new file mode 100644 index 00000000..b56fb68d --- /dev/null +++ b/examples/keys/main.go @@ -0,0 +1,93 @@ +// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. +// Use of this source code is governed by a MIT license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT + +package main + +import ( + "context" + "log" + "os" + + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1" + interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1/interfaces" + client "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/prerecorded" +) + +func main() { + // context + ctx := context.Background() + + //client + dg := client.NewWithDefaults() + mgClient := api.New(dg) + + // list projects + respList, err := mgClient.ListProjects(ctx) + if err != nil { + log.Printf("ListProjects failed. Err: %v\n", err) + os.Exit(1) + } + + var projectId string + for _, item := range respList.Projects { + projectId = item.ProjectId + name := item.Name + log.Printf("ListProjects() - Name: %s, ID: %s\n", name, projectId) + break + } + + // list keys + respGet, err := mgClient.ListKeys(ctx, projectId) + if err != nil { + log.Printf("ListKeys failed. Err: %v\n", err) + os.Exit(1) + } + + for _, item := range respGet.ApiKeys { + id := item.ApiKeyId + comment := item.Comment + log.Printf("ListKeys() - ID: %s, Comment: %s\n", id, comment) + break + } + + // create key + respCreate, err := mgClient.CreateKey(ctx, projectId, &interfaces.KeyCreateRequest{ + Comment: "My Test", + Scopes: []string{"onprem:products"}, + }) + if err != nil { + log.Printf("CreateKey failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("CreateKey() - Name: %s\n", respCreate.Comment) + + // get key + respKey, err := mgClient.GetKey(ctx, projectId, respCreate.ApiKeyId) + if err != nil { + log.Printf("GetKey failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("GetKey() - ID: %s, Comment: %s\n", respKey.Key.ApiKeyId, respKey.Key.Comment) + + // delete project + respMessage, err := mgClient.DeleteKey(ctx, projectId, respKey.Key.ApiKeyId) + if err != nil { + log.Printf("DeleteKey failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("DeleteKey() - Name: %s\n", respMessage.Message) + + // list invitations + respGet, err = mgClient.ListKeys(ctx, projectId) + if err != nil { + log.Printf("ListKeys failed. Err: %v\n", err) + os.Exit(1) + } + + for _, item := range respGet.ApiKeys { + id := item.ApiKeyId + comment := item.Comment + log.Printf("ListKeys() - ID: %s, Comment: %s\n", id, comment) + } +} diff --git a/examples/members/main.go b/examples/members/main.go new file mode 100644 index 00000000..e93a0038 --- /dev/null +++ b/examples/members/main.go @@ -0,0 +1,91 @@ +// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. +// Use of this source code is governed by a MIT license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT + +package main + +import ( + "bufio" + "context" + "fmt" + "log" + "os" + "strings" + + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1" + client "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/prerecorded" +) + +func main() { + fmt.Print("This example requires a member who already exists where \"@spam.com\" is in the email.\n") + fmt.Printf("If that use already exists, press ENTER to continue!\n") + fmt.Printf("Otherwise, Control+C to EXIT!\n\n") + input := bufio.NewScanner(os.Stdin) + input.Scan() + + // context + ctx := context.Background() + + //client + dg := client.NewWithDefaults() + mgClient := api.New(dg) + + // list projects + respList, err := mgClient.ListProjects(ctx) + if err != nil { + log.Printf("ListProjects failed. Err: %v\n", err) + os.Exit(1) + } + + var projectId string + for _, item := range respList.Projects { + projectId = item.ProjectId + name := item.Name + log.Printf("ListProjects() - Name: %s, ID: %s\n", name, projectId) + break + } + + // list invitations + respGet, err := mgClient.ListMembers(ctx, projectId) + if err != nil { + log.Printf("ListMembers failed. Err: %v\n", err) + os.Exit(1) + } + + var delMemberId string + for _, item := range respGet.Members { + memberId := item.MemberId + email := item.Email + log.Printf("ListMembers() - ID: %s, Scope: %s\n", memberId, email) + + if strings.Contains(email, "@spam.com") { + delMemberId = memberId + } + } + + if delMemberId == "" { + fmt.Printf("Unable to find member with email containing \"@spam.com\". Exiting!\n") + os.Exit(0) + } + + // remove member + respMessage, err := mgClient.RemoveMember(ctx, projectId, delMemberId) + if err != nil { + log.Printf("RemoveMember failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("RemoveMember() - Name: %s\n", respMessage.Message) + + // list invitations + respGet, err = mgClient.ListMembers(ctx, projectId) + if err != nil { + log.Printf("ListMembers failed. Err: %v\n", err) + os.Exit(1) + } + + for _, item := range respGet.Members { + memberId := item.MemberId + email := item.Email + log.Printf("ListMembers() - ID: %s, Scope: %s\n", memberId, email) + } +} diff --git a/examples/prerecorded/main.go b/examples/prerecorded/main.go index 23a8487e..2d65208f 100644 --- a/examples/prerecorded/main.go +++ b/examples/prerecorded/main.go @@ -20,25 +20,18 @@ import ( ) func main() { - var deepgramApiKey string - if v := os.Getenv("DEEPGRAM_API_KEY"); v != "" { - log.Println("DEEPGRAM_API_KEY found") - deepgramApiKey = v - } else { - log.Fatal("DEEPGRAM_API_KEY not found") - os.Exit(1) - } - // context ctx := context.Background() - c := client.New(deepgramApiKey) + //client + c := client.NewWithDefaults() dg := prerecorded.New(c) filePath := "https://static.deepgram.com/examples/Bueller-Life-moves-pretty-fast.wav" var res interface{} var err error + // send stream if isURL(filePath) { res, err = dg.FromURL( ctx, diff --git a/examples/projects/main.go b/examples/projects/main.go new file mode 100644 index 00000000..fed88d9a --- /dev/null +++ b/examples/projects/main.go @@ -0,0 +1,110 @@ +// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. +// Use of this source code is governed by a MIT license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT + +package main + +import ( + "bufio" + "context" + "fmt" + "log" + "os" + "strings" + + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1" + interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1/interfaces" + client "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/prerecorded" +) + +func main() { + fmt.Print("This example requires a project who already exists where \"TEST\" is in the name.\n") + fmt.Printf("If that project already exists, press ENTER to continue!\n") + fmt.Printf("Otherwise, Control+C to EXIT!\n\n") + input := bufio.NewScanner(os.Stdin) + input.Scan() + + // context + ctx := context.Background() + + //client + dg := client.NewWithDefaults() + mgClient := api.New(dg) + + // list projects + respList, err := mgClient.ListProjects(ctx) + if err != nil { + log.Printf("ListProjects failed. Err: %v\n", err) + os.Exit(1) + } + + var deleteId string + var deleteName string + for _, item := range respList.Projects { + id := item.ProjectId + name := item.Name + log.Printf("ListProjects() - Name: %s, ID: %s\n", name, id) + + if strings.Contains(name, "TEST") { + deleteId = id + deleteName = name + } + } + + if deleteId == "" { + fmt.Printf("No project found with \"TEST\" in the name. Exiting!\n") + os.Exit(0) + } + + // get first project + respGet, err := mgClient.GetProject(ctx, deleteId) + if err != nil { + log.Printf("GetProject failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("GetProject() - Name: %s\n", respGet.Name) + + // update project + respMessage, err := mgClient.UpdateProject(ctx, deleteId, &interfaces.ProjectUpdateRequest{ + Name: "My TEST RENAME Example", + }) + if err != nil { + log.Printf("UpdateProject failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("UpdateProject() - Name: %s\n", respMessage.Message) + + // get project + respGet, err = mgClient.GetProject(ctx, deleteId) + if err != nil { + log.Printf("GetProject failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("GetProject() - Name: %s\n", respGet.Name) + + // update project + respMessage, err = mgClient.UpdateProject(ctx, deleteId, &interfaces.ProjectUpdateRequest{ + Name: deleteName, + }) + if err != nil { + log.Printf("UpdateProject failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("UpdateProject() - Name: %s\n", respMessage.Message) + + // get project + respGet, err = mgClient.GetProject(ctx, deleteId) + if err != nil { + log.Printf("GetProject failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("GetProject() - Name: %s\n", respGet.Name) + + // delete project + respMessage, err = mgClient.DeleteProject(ctx, deleteId) + if err != nil { + log.Printf("DeleteProject failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("DeleteProject() - Name: %s\n", respMessage.Message) +} diff --git a/examples/scopes/main.go b/examples/scopes/main.go new file mode 100644 index 00000000..e3caead9 --- /dev/null +++ b/examples/scopes/main.go @@ -0,0 +1,138 @@ +// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. +// Use of this source code is governed by a MIT license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT + +package main + +import ( + "bufio" + "context" + "fmt" + "log" + "os" + "strings" + + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1" + interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1/interfaces" + client "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/prerecorded" +) + +func main() { + fmt.Print("This example requires a member who already exists where \"@spam.com\" is in the email.\n") + fmt.Printf("If that use already exists, press ENTER to continue!\n") + fmt.Printf("Otherwise, Control+C to EXIT!\n\n") + input := bufio.NewScanner(os.Stdin) + input.Scan() + + // context + ctx := context.Background() + + //client + dg := client.NewWithDefaults() + mgClient := api.New(dg) + + // list projects + respList, err := mgClient.ListProjects(ctx) + if err != nil { + log.Printf("ListProjects failed. Err: %v\n", err) + os.Exit(1) + } + + var projectId string + for _, item := range respList.Projects { + projectId = item.ProjectId + name := item.Name + log.Printf("ListProjects() - Name: %s, ID: %s\n", name, projectId) + break + } + + // list invitations + respGet, err := mgClient.ListMembers(ctx, projectId) + if err != nil { + log.Printf("ListMembers failed. Err: %v\n", err) + os.Exit(1) + } + + var updateID string + for _, item := range respGet.Members { + memberId := item.MemberId + email := item.Email + log.Printf("ListMembers() - ID: %s, Scope: %s\n", memberId, email) + for _, scope := range item.Scopes { + log.Printf("Scope: %s\n", scope) + } + + if strings.Contains(email, "@spam.com") { + updateID = memberId + } + } + + if updateID == "" { + fmt.Printf("No member found with \"@spam.com\" in the email. Exiting!\n") + os.Exit(0) + } + + // get scope + respScope, err := mgClient.GetMemberScopes(ctx, projectId, updateID) + if err != nil { + log.Printf("GetMemberScopes failed. Err: %v\n", err) + os.Exit(1) + } + + scope := respScope.Scopes + for _, item := range scope { + log.Printf("GetMemberScopes() - Scope: %s\n", item) + } + + // update scope + respMessage, err := mgClient.UpdateMemberScopes(ctx, projectId, updateID, &interfaces.ScopeUpdateRequest{ + Scope: "admin", + }) + if err != nil { + log.Printf("UpdateMemberScopes failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("UpdateMemberScopes() - Name: %s\n", respMessage.Message) + + // list invitations + respGet, err = mgClient.ListMembers(ctx, projectId) + if err != nil { + log.Printf("ListMembers failed. Err: %v\n", err) + os.Exit(1) + } + + for _, item := range respGet.Members { + memberId := item.MemberId + email := item.Email + log.Printf("ListMembers() - ID: %s, Scope: %s\n", memberId, email) + for _, scope := range item.Scopes { + log.Printf("Scope: %s\n", scope) + } + } + + // update scope + respMessage, err = mgClient.UpdateMemberScopes(ctx, projectId, updateID, &interfaces.ScopeUpdateRequest{ + Scope: "member", + }) + if err != nil { + log.Printf("UpdateMemberScopes failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("UpdateMemberScopes() - Name: %s\n", respMessage.Message) + + // list members + respGet, err = mgClient.ListMembers(ctx, projectId) + if err != nil { + log.Printf("ListMembers failed. Err: %v\n", err) + os.Exit(1) + } + + for _, item := range respGet.Members { + memberId := item.MemberId + email := item.Email + log.Printf("ListMembers() - ID: %s, Scope: %s\n", memberId, email) + for _, scope := range item.Scopes { + log.Printf("Scope: %s\n", scope) + } + } +} diff --git a/examples/usage/main.go b/examples/usage/main.go new file mode 100644 index 00000000..cccc731c --- /dev/null +++ b/examples/usage/main.go @@ -0,0 +1,89 @@ +// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. +// Use of this source code is governed by a MIT license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT + +package main + +import ( + "context" + "log" + "os" + + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1" + interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1/interfaces" + client "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/prerecorded" +) + +func main() { + // context + ctx := context.Background() + + //client + dg := client.NewWithDefaults() + mgClient := api.New(dg) + + // list projects + respList, err := mgClient.ListProjects(ctx) + if err != nil { + log.Printf("ListProjects failed. Err: %v\n", err) + os.Exit(1) + } + + var projectId string + for _, item := range respList.Projects { + projectId = item.ProjectId + name := item.Name + log.Printf("ListProjects() - Name: %s, ID: %s\n", name, projectId) + break + } + + // list requests + respRequestGet, err := mgClient.ListRequests(ctx, projectId, &interfaces.UsageListRequest{}) + if err != nil { + log.Printf("ListRequests failed. Err: %v\n", err) + os.Exit(1) + } + + var requestId string + for _, item := range respRequestGet.Requests { + requestId = item.RequestId + path := item.Path + log.Printf("ListRequests() - ID: %s, Path: %s\n", requestId, path) + } + + // get request + respRequest, err := mgClient.GetRequest(ctx, projectId, requestId) + if err != nil { + log.Printf("GetRequest failed. Err: %v\n", err) + os.Exit(1) + } + log.Printf("GetRequest() - ID: %s, Path: %s\n", respRequest.RequestId, respRequest.Path) + + // get fields + respFieldsGet, err := mgClient.GetFields(ctx, projectId, &interfaces.UsageListRequest{}) + if err != nil { + log.Printf("GetFields failed. Err: %v\n", err) + os.Exit(1) + } + + for _, model := range respFieldsGet.Models { + modelId := model.ModelID + name := model.Name + log.Printf("GetFields() - ID: %s, Name: %s\n", modelId, name) + } + for _, method := range respFieldsGet.ProcessingMethods { + log.Printf("GetFields() - method: %s\n", method) + } + + // get usage + respUsageGet, err := mgClient.GetUsage(ctx, projectId, &interfaces.UsageRequest{}) + if err != nil { + log.Printf("GetUsage failed. Err: %v\n", err) + os.Exit(1) + } + + for _, item := range respUsageGet.Results { + numOfRequests := item.Requests + log.Printf("GetRequest() - %d Calls/%s\n", numOfRequests, respUsageGet.Resolution.Units) + } +} diff --git a/pkg/api/manage/v1/balances.go b/pkg/api/manage/v1/balances.go new file mode 100644 index 00000000..cf2b1424 --- /dev/null +++ b/pkg/api/manage/v1/balances.go @@ -0,0 +1,105 @@ +// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. +// Use of this source code is governed by a MIT license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT + +package manage + +import ( + "context" + "log" + "net/http" + + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1/interfaces" + version "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/version" + interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/interfaces" +) + +func (c *ManageClient) ListBalances(ctx context.Context, projectId string) (*api.BalancesResult, error) { + // checks + if ctx == nil { + ctx = context.Background() + } + + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.BalancesURI, nil, projectId) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + log.Printf("Calling %s\n", URI) // TODO + + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // Do it! + var resp api.BalancesResult + err = c.Client.Do(ctx, req, &resp) + + if err != nil { + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil +} + +func (c *ManageClient) GetBalance(ctx context.Context, projectId string, balanceId string) (*api.BalanceResult, error) { + // checks + if ctx == nil { + ctx = context.Background() + } + + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.BalancesByIdURI, nil, projectId, balanceId) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + log.Printf("Calling %s\n", URI) // TODO + + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // Do it! + var resp api.BalanceResult + err = c.Client.Do(ctx, req, &resp) + + if err != nil { + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil +} diff --git a/pkg/api/manage/v1/billing.go b/pkg/api/manage/v1/billing.go deleted file mode 100644 index f26e09d3..00000000 --- a/pkg/api/manage/v1/billing.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. -// Use of this source code is governed by a MIT license that can be found in the LICENSE file. -// SPDX-License-Identifier: MIT - -package manage - -import ( - "fmt" - "io" - "log" - "net/http" - "net/url" -) - -type Balance struct { - Amount float64 `json:"amount"` - BalanceId string `json:"balance_id"` - Units string `json:"units"` - PurchaseOrderId string `json:"purchase_order_id"` -} - -type BalanceList struct { - Balances []Balance `json:"balances"` -} - -func (dg *ManageClient) ListBalances(projectId string) (BalanceList, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s/balances", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - //Handle Error - log.Panic(err) - } - - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, - } - - var result BalanceList - res, err := client.Do(req) - if err != nil { - return result, err - } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) - } - jsonErr := GetJson(res, &result) - - if jsonErr != nil { - fmt.Printf("error getting balances from project %s: %s\n", projectId, jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } -} - -func (dg *ManageClient) GetBalance(projectId string, balanceId string) (Balance, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s/balances/%s", dg.Client.Path, projectId, balanceId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - //Handle Error - log.Panic(err) - } - - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, - } - - var result Balance - res, err := client.Do(req) - if err != nil { - return result, err - } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) - } - jsonErr := GetJson(res, &result) - - if jsonErr != nil { - fmt.Printf("error getting balance %s: %s\n", balanceId, jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } -} diff --git a/pkg/api/manage/v1/constants.go b/pkg/api/manage/v1/constants.go new file mode 100644 index 00000000..d5b51546 --- /dev/null +++ b/pkg/api/manage/v1/constants.go @@ -0,0 +1,14 @@ +// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. +// Use of this source code is governed by a MIT license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT + +package manage + +import ( + "errors" +) + +var ( + // ErrUnexpectedInterface unexpected interface encountered + ErrUnexpectedInterface = errors.New("unexpected interface encountered") +) diff --git a/pkg/api/manage/v1/interfaces/types.go b/pkg/api/manage/v1/interfaces/types.go new file mode 100644 index 00000000..4b3a785a --- /dev/null +++ b/pkg/api/manage/v1/interfaces/types.go @@ -0,0 +1,292 @@ +// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. +// Use of this source code is governed by a MIT license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT + +package interfaces + +import "time" + +// share/common structs +// Balance provides a balance +type Balance struct { + Amount float64 `json:"amount"` + BalanceId string `json:"balance_id"` + Units string `json:"units"` + PurchaseOrderId string `json:"purchase_order_id"` +} + +// BalanceList provides a list of balances +type BalanceList struct { + Balances []Balance `json:"balances"` +} + +// Invitation provides an invitation +type Invitation struct { + Email string `json:"email"` + Scope string `json:"scope"` +} + +// InvitationList provides a list of invitations +type InvitationList struct { + Invites []Invitation `json:"invites"` +} + +// Key provides a key +type Key struct { + ApiKeyId string `json:"api_key_id"` + Key string `json:"key"` + Comment string `json:"comment"` + Created string `json:"created"` + Scopes []string `json:"scopes"` +} + +// KeyList provides a list of keys +type KeyList struct { + ApiKeys []Key `json:"api_key"` +} + +// ScopeList provides a list of scopes +type ScopeList struct { + Scopes []string `json:"scopes"` +} + +// Member provides a member +type Member struct { + Email string `json:"email"` + MemberId string `json:"member_id"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Scopes []string `json:"scopes"` +} + +// MemberList provides a list of members +type MemberList struct { + Members []Member `json:"members"` +} + +// Project provides a project +type Project struct { + ProjectId string `json:"project_id"` + Name string `json:"name,omitempty"` + Company string `json:"company,omitempty"` +} + +// ProjectList provides a list of projects +type ProjectList struct { + Projects []Project `json:"projects"` +} + +// Config provides a config +type Config struct { + Diarize bool `json:"diarize,omitempty"` + Language string `json:"language,omitempty"` + Model string `json:"model,omitempty"` + Punctuate bool `json:"punctuate,omitempty"` + Utterances bool `json:"utterances,omitempty"` +} + +// Details provides details +type Details struct { + Usd float64 `json:"usd,omitempty"` + Duration float64 `json:"duration,omitempty"` + TotalAudio float64 `json:"total_audio,omitempty"` + Channels int `json:"channels,omitempty"` + Streams int `json:"streams,omitempty"` + Models []string `json:"models,omitempty"` + Method string `json:"method,omitempty"` + Tier string `json:"tier,omitempty"` + Tags []string `json:"tags,omitempty"` + Features []string `json:"features,omitempty"` + Config Config `json:"config,omitempty"` +} + +// Response provides a response +type Response struct { + Details Details `json:"details,omitempty"` + Code int `json:"code,omitempty"` + Completed string `json:"completed,omitempty"` +} + +// Models provides a list of models +type Models struct { + Name string `json:"name,omitempty"` + Language string `json:"language,omitempty"` + Version string `json:"version,omitempty"` + ModelID string `json:"model_id,omitempty"` +} + +// Resolution provides a resolution +type Resolution struct { + Units string `json:"units,omitempty"` + Amount int `json:"amount,omitempty"` +} + +// Results provides a list of results +type Results struct { + Start string `json:"start,omitempty"` + End string `json:"end,omitempty"` + Hours float64 `json:"hours,omitempty"` + TotalHours float64 `json:"total_hours,omitempty"` + Requests int `json:"requests,omitempty"` +} + +/*** + Request structs +***/ +// ProjectUpdateRequest provides a project update +type ProjectUpdateRequest struct { + Name string `json:"name,omitempty"` + Company string `json:"company,omitempty"` +} + +// InvitationRequest provides an invitation request +type InvitationRequest struct { + Email string `json:"email"` + Scope string `json:"scope"` +} + +// KeyCreateRequest provides a key create request +type KeyCreateRequest struct { + Comment string `json:"comment"` + Scopes []string `json:"scopes"` + ExpirationDate time.Time `json:"expiration_date"` + TimeToLive int `json:"time_to_live,omitempty"` + Tags []string `json:"tags"` +} + +// ScopeUpdateRequest provides a scope update request +type ScopeUpdateRequest struct { + Scope string `json:"scope"` +} + +// UsageListRequest provides a usage request +type UsageListRequest struct { + Start string `json:"start" url:"start,omitempty"` + End string `json:"end" url:"end,omitempty"` + Page int `json:"page" url:"page,omitempty"` + Limit int `json:"limit" url:"limit,omitempty"` + Status string `json:"status" url:"status,omitempty"` +} + +// UsageRequest provides a usage request +type UsageRequest struct { + Accessor string `json:"accessor" url:"accessor,omitempty"` + Alternatives bool `json:"alternatives" url:"alternatives,omitempty"` + AnalyzeSentiment bool `json:"analyze_sentiment" url:"analyze_sentiment,omitempty"` + DetectEntities bool `json:"detect_entities" url:"detect_entities,omitempty"` + DetectLanguage bool `json:"detect_language" url:"detect_language,omitempty"` + DetectTopics bool `json:"detect_topics" url:"detect_topics,omitempty"` + Diarize bool `json:"diarize" url:"diarize,omitempty"` + End string `json:"end" url:"end,omitempty"` + InterimResults bool `json:"interim_results" url:"interim_results,omitempty"` + Keywords bool `json:"keywords" url:"keywords,omitempty"` + Method string `json:"method" url:"method,omitempty"` // Must be one of "sync" | "async" | "streaming" + Model string `json:"model" url:"model,omitempty"` + Multichannel bool `json:"multichannel" url:"multichannel,omitempty"` + Ner bool `json:"ner" url:"ner,omitempty"` + Numbers bool `json:"numbers" url:"numbers,omitempty"` + Numerals bool `json:"numerals" url:"numerals,omitempty"` + Paragraphs bool `json:"paragraphs" url:"paragraphs,omitempty"` + ProfanityFilter bool `json:"profanity_filter" url:"profanity_filter,omitempty"` + Punctuate bool `json:"punctuate" url:"punctuate,omitempty"` + Redact bool `json:"redact" url:"redact,omitempty"` + Replace bool `json:"replace" url:"replace,omitempty"` + Search bool `json:"search" url:"search,omitempty"` + Sentiment bool `json:"sentiment" url:"sentiment,omitempty"` + SentimentThreshold float64 `json:"sentiment_threshold" url:"sentiment_threshold,omitempty"` + SmartFormat bool `json:"smart_format" url:"smart_format,omitempty"` + Start string `json:"start" url:"start,omitempty"` + Summarize bool `json:"summarize" url:"summarize,omitempty"` + Tag []string `json:"tag" url:"tag,omitempty"` + Translate bool `json:"translate" url:"translate,omitempty"` + Utterances bool `json:"utterances" url:"utterances,omitempty"` + UttSplit bool `json:"utt_split" url:"utt_split,omitempty"` +} + +/*** + Response structs +***/ +// BookmarksResult provides a generic message results +type MessageResult struct { + Message string `json:"message"` +} + +// BalanceResult provides a result with a list of balances +type BalancesResult struct { + BalanceList +} + +// BalanceResult provides a result with a single balance +type BalanceResult struct { + Balance +} + +// InvitationResult provides a result with a single invitation +type InvitationsResult struct { + InvitationList +} + +// InvitationResult provides a result with a single invitation +type KeysResult struct { + KeyList +} + +// KeyResult provides a result with a single key +type KeyResult struct { + Member Member `json:"member"` + Key Key `json:"api_key"` +} + +// MembersResult provides a result with a list of members +type MembersResult struct { + MemberList +} + +// ProjectsResult provides a result with a list of projects +type ProjectsResult struct { + ProjectList +} + +// ProjectResult provides a result with a single project +type ProjectResult struct { + Project +} + +type ScopeResult struct { + ScopeList +} + +// UsageResult provides a result with a list of usage +type UsageListResult struct { + Page int `json:"page" url:"page,omitempty"` + Limit int `json:"limit" url:"limit,omitempty"` + Requests []UsageRequestResult `json:"requests" url:"requests,omitempty"` + // Requests interface{} `json:"requests" url:"requests,omitempty"` +} + +// UsageRequestResult provides a result with a single usage request +type UsageRequestResult struct { + RequestId string `json:"request_id" url:"request_id,omitempty"` + Created string `json:"created" url:"created,omitempty"` + Path string `json:"path" url:"path,omitempty"` + Accessor string `json:"accessor" url:"accessor,omitempty"` + APIKeyID string `json:"api_key_id,omitempty"` + Response Response `json:"response,omitempty"` + Callback interface{} `json:"callback" url:"callback,omitempty"` +} + +// UsageFieldResult provides a result with a list of fields +type UsageFieldResult struct { + Tags []string `json:"tags,omitempty"` + Models []Models `json:"models,omitempty"` + ProcessingMethods []string `json:"processing_methods,omitempty"` + Features []string `json:"features,omitempty"` +} + +// UsageSummary provides a result with a list of usage +type UsageResult struct { + Start string `json:"start,omitempty"` + End string `json:"end,omitempty"` + Resolution Resolution `json:"resolution,omitempty"` + Results []Results `json:"results,omitempty"` +} diff --git a/pkg/api/manage/v1/invitations.go b/pkg/api/manage/v1/invitations.go index f767aad2..27f75a82 100644 --- a/pkg/api/manage/v1/invitations.go +++ b/pkg/api/manage/v1/invitations.go @@ -6,112 +6,199 @@ package manage import ( "bytes" + "context" "encoding/json" - "fmt" "log" "net/http" - "net/url" + + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1/interfaces" + version "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/version" + interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/interfaces" ) -func (dg *ManageClient) ListInvitations(projectId string) (InvitationList, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s/invites", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} +func (c *ManageClient) ListInvitations(ctx context.Context, projectId string) (*api.InvitationsResult, error) { + // checks + if ctx == nil { + ctx = context.Background() + } - req, err := http.NewRequest("GET", u.String(), nil) + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.InvitationsURI, nil, projectId) if err != nil { - //Handle Error - log.Panic(err) + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } + log.Printf("Calling %s\n", URI) // TODO - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - var result InvitationList - res, err := client.Do(req) + // Do it! + var resp api.InvitationsResult + err = c.Client.Do(ctx, req, &resp) + if err != nil { - return result, err - } - jsonErr := GetJson(res, &result) - if jsonErr != nil { - fmt.Printf("error getting invitation list: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil } -func (dg *ManageClient) SendInvitation(projectId string, options InvitationOptions) (Message, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s/invites", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - jsonStr, err := json.Marshal(options) - if err != nil { - log.Panic(err) - return Message{}, err +func (c *ManageClient) SendInvitation(ctx context.Context, projectId string, invite *api.InvitationRequest) (*api.MessageResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } - req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(jsonStr)) + + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.InvitationsURI, nil, projectId) if err != nil { - //Handle Error - log.Panic(err) + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } + log.Printf("Calling %s\n", URI) // TODO - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, + jsonStr, err := json.Marshal(invite) + if err != nil { + // klog.V(1).Infof("json.Marshal failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - var result Message - res, err := client.Do(req) + req, err := http.NewRequestWithContext(ctx, "POST", URI, bytes.NewBuffer(jsonStr)) if err != nil { - return result, err + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - jsonErr := GetJson(res, &result) - if jsonErr != nil { - fmt.Printf("error sending invitation: %s\n", jsonErr.Error()) - if e, ok := err.(*json.SyntaxError); ok { - log.Printf("syntax error at byte offset %d", e.Offset) + + // Do it! + var resp api.MessageResult + err = c.Client.Do(ctx, req, &resp) + + if err != nil { + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } } - return result, jsonErr - } else { - return result, nil + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil } -func (dg *ManageClient) DeleteInvitation(projectId string, email string) (Message, error) { - client := new(http.Client) - // url := fmt.Sprintf("%s%s/%s/invites/%s", dg.Client.Host, dg.Client.Path, projectId, email) - path := fmt.Sprintf("%s/%s/invites/%s", dg.Client.Path, projectId, email) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("DELETE", u.String(), nil) +func (c *ManageClient) DeleteInvitation(ctx context.Context, projectId string, email string) (*api.MessageResult, error) { + // checks + if ctx == nil { + ctx = context.Background() + } + + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.InvitationsByIdURI, nil, projectId, email) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + log.Printf("Calling %s\n", URI) // TODO + + req, err := http.NewRequestWithContext(ctx, "DELETE", URI, nil) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // Do it! + var resp api.MessageResult + err = c.Client.Do(ctx, req, &resp) + if err != nil { - //Handle Error - log.Panic(err) + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil +} + +func (c *ManageClient) LeaveProject(ctx context.Context, projectId string) (*api.MessageResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } - var result Message - res, err := client.Do(req) + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.InvitationsLeaveURI, nil, projectId) if err != nil { - return result, err + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - jsonErr := GetJson(res, &result) - if jsonErr != nil { - fmt.Printf("error deleting invitation: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil + log.Printf("Calling %s\n", URI) // TODO + + req, err := http.NewRequestWithContext(ctx, "DELETE", URI, nil) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } + + // Do it! + var resp api.MessageResult + err = c.Client.Do(ctx, req, &resp) + + if err != nil { + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil } diff --git a/pkg/api/manage/v1/keys.go b/pkg/api/manage/v1/keys.go index 08706bcf..163d810d 100644 --- a/pkg/api/manage/v1/keys.go +++ b/pkg/api/manage/v1/keys.go @@ -6,206 +6,220 @@ package manage import ( "bytes" + "context" "encoding/json" - "fmt" - "io" "log" "net/http" - "net/url" "time" + + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1/interfaces" + version "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/version" + interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/interfaces" ) -type Key struct { - ApiKeyId string `json:"api_key_id"` - Key string `json:"key"` - Comment string `json:"comment"` - Created string `json:"created"` - Scopes []string `json:"scopes"` -} +func (c *ManageClient) ListKeys(ctx context.Context, projectId string) (*api.KeysResult, error) { + // checks + if ctx == nil { + ctx = context.Background() + } -type KeyResponseObj struct { - Member Member `json:"member"` - ApiKey Key `json:"api_key"` -} + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.KeysURI, nil, projectId) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + log.Printf("Calling %s\n", URI) // TODO -type KeyResponse struct { - ApiKeys []KeyResponseObj `json:"api_keys"` -} + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } -type CreateKeyOptions struct { - ExpirationDate time.Time `json:"expiration_date"` - TimeToLive int `json:"time_to_live"` - Tags []string `json:"tags"` -} + // Do it! + var resp api.KeysResult + err = c.Client.Do(ctx, req, &resp) -type CreateKeyRequest struct { - Comment string `json:"comment"` - Scopes []string `json:"scopes"` - ExpirationDate string `json:"expiration_date,omitempty"` - TimeToLive int `json:"time_to_live,omitempty"` + if err != nil { + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil } -func (dg *ManageClient) ListKeys(projectId string) (KeyResponse, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s/keys", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - //Handle Error - log.Panic(err) +func (c *ManageClient) GetKey(ctx context.Context, projectId string, keyId string) (*api.KeyResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.KeysByIdURI, nil, projectId, keyId) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } + log.Printf("Calling %s\n", URI) // TODO - var result KeyResponse - res, err := client.Do(req) + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) if err != nil { - return result, err - } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - jsonErr := GetJson(res, &result) - if jsonErr != nil { - fmt.Printf("error getting keys: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } -} + // Do it! + var resp api.KeyResult + err = c.Client.Do(ctx, req, &resp) -func (dg *ManageClient) GetKey(projectId string, keyId string) (KeyResponseObj, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s/keys/%s", dg.Client.Path, projectId, keyId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("GET", u.String(), nil) if err != nil { - //Handle Error - log.Panic(err) + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil +} + +func (c *ManageClient) CreateKey(ctx context.Context, projectId string, key *api.KeyCreateRequest) (*api.Key, error) { + // checks + if ctx == nil { + ctx = context.Background() } - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, + var expirationStr string + if !key.ExpirationDate.IsZero() { + expirationStr = key.ExpirationDate.Format(time.RFC3339) } - var result KeyResponseObj - res, err := client.Do(req) + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.KeysURI, nil, projectId) if err != nil { - return result, err + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - if res.StatusCode != 200 { + log.Printf("Calling %s\n", URI) // TODO - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) + type InternalKeyCreateRequest struct { + Comment string `json:"comment"` + Scopes []string `json:"scopes"` + ExpirationDate string `json:"expiration_date,omitempty"` + TimeToLive int `json:"time_to_live,omitempty"` + // Tags []string `json:"tags"` } - jsonErr := GetJson(res, &result) - - if jsonErr != nil { - fmt.Printf("error getting key: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil + internalKey := InternalKeyCreateRequest{ + Comment: key.Comment, + Scopes: key.Scopes, + ExpirationDate: expirationStr, + TimeToLive: key.TimeToLive, + // Tags: key.Tags, } -} -func (dg *ManageClient) CreateKey(projectId string, comment string, scopes []string, options CreateKeyOptions) (Key, error) { - var expirationDate string - if options.ExpirationDate.IsZero() { - expirationDate = "" - } else { - expirationDate = options.ExpirationDate.Format(time.RFC3339) - } - out, err := json.Marshal(CreateKeyRequest{ - Comment: comment, - Scopes: scopes, - ExpirationDate: expirationDate, - TimeToLive: options.TimeToLive, - }) - fmt.Println(string(out)) - buf := bytes.NewBuffer(out) + jsonStr, err := json.Marshal(internalKey) if err != nil { - log.Panic(err) + // klog.V(1).Infof("json.Marshal failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - client := new(http.Client) - path := fmt.Sprintf("%s/%s/keys", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("POST", u.String(), buf) + + req, err := http.NewRequestWithContext(ctx, "POST", URI, bytes.NewBuffer(jsonStr)) if err != nil { - //Handle Error - log.Panic(err) + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, - } + // Do it! + var resp api.Key + err = c.Client.Do(ctx, req, &resp) - var result Key - res, err := client.Do(req) if err != nil { - return result, err - } - if res.StatusCode != 200 { - - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) - } - jsonErr := GetJson(res, &result) + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil +} - if jsonErr != nil { - fmt.Printf("error Creating key: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil +func (c *ManageClient) DeleteKey(ctx context.Context, projectId string, keyId string) (*api.MessageResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } -} -func (dg *ManageClient) DeleteKey(projectId string, keyId string) (Message, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s/keys/%s", dg.Client.Path, projectId, keyId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("DELETE", u.String(), nil) + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.KeysByIdURI, nil, projectId, keyId) if err != nil { - //Handle Error - log.Panic(err) + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } + log.Printf("Calling %s\n", URI) // TODO - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, - } - var result Message - res, err := client.Do(req) + req, err := http.NewRequestWithContext(ctx, "DELETE", URI, nil) if err != nil { - return result, err + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) - } - jsonErr := GetJson(res, &result) + // Do it! + var resp api.MessageResult + err = c.Client.Do(ctx, req, &resp) - if jsonErr != nil { - fmt.Printf("error Creating key: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return Message{ - Message: "Key Deleted", - }, nil - } + if err != nil { + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil } diff --git a/pkg/api/manage/v1/manage.go b/pkg/api/manage/v1/manage.go index 6cccf5b2..1f44a1cd 100644 --- a/pkg/api/manage/v1/manage.go +++ b/pkg/api/manage/v1/manage.go @@ -5,25 +5,9 @@ package manage import ( - "encoding/json" - "net/http" - "runtime" - "strings" - client "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/prerecorded" ) -var sdkVersion string = "0.10.0" -var dgAgent string = "@deepgram/sdk/" + sdkVersion + " go/" + goVersion() - -func goVersion() string { - version := runtime.Version() - if strings.HasPrefix(version, "go") { - return version[2:] - } - return version -} - type ManageClient struct { *client.Client } @@ -31,9 +15,3 @@ type ManageClient struct { func New(client *client.Client) *ManageClient { return &ManageClient{client} } - -func GetJson(resp *http.Response, target interface{}) error { - defer resp.Body.Close() - - return json.NewDecoder(resp.Body).Decode(target) -} diff --git a/pkg/api/manage/v1/members.go b/pkg/api/manage/v1/members.go index 83e8194d..8de5fb80 100644 --- a/pkg/api/manage/v1/members.go +++ b/pkg/api/manage/v1/members.go @@ -5,213 +5,101 @@ package manage import ( - "fmt" - "io" + "context" "log" "net/http" - "net/url" - "strings" -) - -type Member struct { - Email string `json:"email"` - MemberId string `json:"member_id"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - Scopes []string `json:"scopes"` -} - -type MemberList struct { - Members []Member `json:"members"` -} - -type ScopeList struct { - Scopes []string `json:"scopes"` -} -func (dg *ManageClient) ListMembers(projectId string) (MemberList, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s/members", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - //Handle Error - log.Panic(err) - } + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1/interfaces" + version "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/version" + interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/interfaces" +) - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, +func (c *ManageClient) ListMembers(ctx context.Context, projectId string) (*api.MembersResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } - var result MemberList - res, err := client.Do(req) + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.MembersURI, nil, projectId) if err != nil { - return result, err - } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) - } - jsonErr := GetJson(res, &result) - - if jsonErr != nil { - fmt.Printf("error getting members: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } -} + log.Printf("Calling %s\n", URI) // TODO -func (dg *ManageClient) RemoveMember(projectId string, memberId string) (Message, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s/members/%s", dg.Client.Path, projectId, memberId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("DELETE", u.String(), nil) + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) if err != nil { - //Handle Error - log.Panic(err) + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, - } + // Do it! + var resp api.MembersResult + err = c.Client.Do(ctx, req, &resp) - var result Message - res, err := client.Do(req) if err != nil { - return result, err - } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) - } - jsonErr := GetJson(res, &result) - - if jsonErr != nil { - fmt.Printf("error removing member: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil } -func (dg *ManageClient) GetMemberScopes(projectId string, memberId string) (ScopeList, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s/members/%s/scopes", dg.Client.Path, projectId, memberId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - //Handle Error - log.Panic(err) - } - - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, +func (c *ManageClient) RemoveMember(ctx context.Context, projectId string, memberId string) (*api.MessageResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } - var result ScopeList - res, err := client.Do(req) + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.MembersByIdURI, nil, projectId, memberId) if err != nil { - return result, err - } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - jsonErr := GetJson(res, &result) + log.Printf("Calling %s\n", URI) // TODO - if jsonErr != nil { - fmt.Printf("error getting member scopes: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } -} - -type MemberScope struct { - Scope string `json:"scope"` -} - -func (dg *ManageClient) UpdateMemberScopes(projectId string, memberId string, scope string) (Message, error) { - newScope := fmt.Sprintf(`{"scope":"%s"}`, scope) - client := new(http.Client) - path := fmt.Sprintf("%s/%s/members/%s/scopes", dg.Client.Path, projectId, memberId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("PUT", u.String(), strings.NewReader(newScope)) + req, err := http.NewRequestWithContext(ctx, "DELETE", URI, nil) if err != nil { - //Handle Error - log.Panic(err) + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, - } + // Do it! + var resp api.MessageResult + err = c.Client.Do(ctx, req, &resp) - var result Message - res, err := client.Do(req) if err != nil { - return result, err - } - if res.StatusCode != 200 { - - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) - } - jsonErr := GetJson(res, &result) - - if jsonErr != nil { - fmt.Printf("error updating member scopes: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } -} - -func (dg *ManageClient) LeaveProject(projectId string) (Message, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s/leave", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("DELETE", u.String(), nil) - if err != nil { - //Handle Error - log.Panic(err) - } - - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, - } - - var result Message - res, err := client.Do(req) - if err != nil { - return result, err - } - if res.StatusCode != 200 { - - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) - } - jsonErr := GetJson(res, &result) - - if jsonErr != nil { - fmt.Printf("error leaving project: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil } diff --git a/pkg/api/manage/v1/projects.go b/pkg/api/manage/v1/projects.go index 0eebbe4f..5cd510de 100644 --- a/pkg/api/manage/v1/projects.go +++ b/pkg/api/manage/v1/projects.go @@ -6,177 +6,199 @@ package manage import ( "bytes" + "context" "encoding/json" - "fmt" - "io" "log" "net/http" - "net/url" -) - -type Project struct { - ProjectId string `json:"project_id"` - Name string `json:"name,omitempty"` - Company string `json:"company,omitempty"` -} - -type ProjectResponse struct { - Projects []Project `json:"projects"` -} -type ProjectUpdateOptions struct { - Name string `json:"name,omitempty"` - Company string `json:"company,omitempty"` -} + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1/interfaces" + version "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/version" + interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/interfaces" +) -func (dg *ManageClient) ListProjects() (ProjectResponse, error) { - client := new(http.Client) - // path := fmt.Sprintf("%s", dg.Client.Path) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: dg.Client.Path} - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - //Handle Error - log.Panic(err) +func (c *ManageClient) ListProjects(ctx context.Context) (*api.ProjectsResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.ProjectsURI, nil) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } + log.Printf("Calling %s\n", URI) // TODO - var result ProjectResponse - res, err := client.Do(req) + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) if err != nil { - return result, err + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) - } - jsonErr := GetJson(res, &result) - if jsonErr != nil { - fmt.Printf("error getting projects: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } -} + // Do it! + var resp api.ProjectsResult + err = c.Client.Do(ctx, req, &resp) -func (dg *ManageClient) GetProject(projectId string) (Project, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("GET", u.String(), nil) if err != nil { - //Handle Error - log.Panic(err) - } + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil +} - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, +func (c *ManageClient) GetProject(ctx context.Context, projectId string) (*api.ProjectResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } - var result Project - res, err := client.Do(req) + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.ProjectsByIdURI, nil, projectId) if err != nil { - return result, err - } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - jsonErr := GetJson(res, &result) + log.Printf("Calling %s\n", URI) // TODO - if jsonErr != nil { - fmt.Printf("error getting project %s: %s\n", projectId, jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } -} - -func (dg *ManageClient) UpdateProject(projectId string, options ProjectUpdateOptions) (Message, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - jsonStr, err := json.Marshal(options) + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) if err != nil { - log.Panic(err) - return Message{}, err + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - req, err := http.NewRequest("PATCH", u.String(), bytes.NewBuffer(jsonStr)) + + // Do it! + var resp api.ProjectResult + err = c.Client.Do(ctx, req, &resp) + if err != nil { - //Handle Error - log.Panic(err) - } + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil +} - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, +func (c *ManageClient) UpdateProject(ctx context.Context, projectId string, proj *api.ProjectUpdateRequest) (*api.MessageResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } - var result Message - res, err := client.Do(req) + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.ProjectsByIdURI, nil, projectId) if err != nil { - return result, err + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) + log.Printf("Calling %s\n", URI) // TODO + + jsonStr, err := json.Marshal(proj) + if err != nil { + // klog.V(1).Infof("json.Marshal failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - jsonErr := GetJson(res, &result) - if jsonErr != nil { - fmt.Printf("error updating project %s: %s\n", projectId, jsonErr.Error()) - return result, jsonErr - } else { - return result, nil + req, err := http.NewRequestWithContext(ctx, "PATCH", URI, bytes.NewBuffer(jsonStr)) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } -} -func (dg *ManageClient) DeleteProject(projectId string) (Message, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} + // Do it! + var resp api.MessageResult + err = c.Client.Do(ctx, req, &resp) - req, err := http.NewRequest("DELETE", u.String(), nil) if err != nil { - //Handle Error - log.Panic(err) - } + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil +} - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, +func (c *ManageClient) DeleteProject(ctx context.Context, projectId string) (*api.MessageResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } - var result Message - res, err := client.Do(req) + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.ProjectsByIdURI, nil, projectId) if err != nil { - return result, err - } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - jsonErr := GetJson(res, &result) + log.Printf("Calling %s\n", URI) // TODO - if jsonErr != nil { - fmt.Printf("error deleting project %s: %s\n", projectId, jsonErr.Error()) - return result, jsonErr - } else { - return Message{ - Message: "Project Successfully Deleted", - }, nil + req, err := http.NewRequestWithContext(ctx, "DELETE", URI, nil) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } + + // Do it! + var resp api.MessageResult + err = c.Client.Do(ctx, req, &resp) + + if err != nil { + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil } diff --git a/pkg/api/manage/v1/scopes.go b/pkg/api/manage/v1/scopes.go new file mode 100644 index 00000000..80c8ae89 --- /dev/null +++ b/pkg/api/manage/v1/scopes.go @@ -0,0 +1,114 @@ +// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. +// Use of this source code is governed by a MIT license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT + +package manage + +import ( + "bytes" + "context" + "encoding/json" + "log" + "net/http" + + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1/interfaces" + version "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/version" + interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/interfaces" +) + +func (c *ManageClient) GetMemberScopes(ctx context.Context, projectId string, memberId string) (*api.ScopeResult, error) { + // checks + if ctx == nil { + ctx = context.Background() + } + + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.MembersScopeByIdURI, nil, projectId, memberId) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + log.Printf("Calling %s\n", URI) // TODO + + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // Do it! + var resp api.ScopeResult + err = c.Client.Do(ctx, req, &resp) + + if err != nil { + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil +} + +func (c *ManageClient) UpdateMemberScopes(ctx context.Context, projectId string, memberId string, scope *api.ScopeUpdateRequest) (*api.MessageResult, error) { + // checks + if ctx == nil { + ctx = context.Background() + } + + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.MembersScopeByIdURI, nil, projectId, memberId) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + log.Printf("Calling %s\n", URI) // TODO + + jsonStr, err := json.Marshal(scope) + if err != nil { + // klog.V(1).Infof("json.Marshal failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + req, err := http.NewRequestWithContext(ctx, "PUT", URI, bytes.NewBuffer(jsonStr)) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // Do it! + var resp api.MessageResult + err = c.Client.Do(ctx, req, &resp) + + if err != nil { + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil +} diff --git a/pkg/api/manage/v1/types.go b/pkg/api/manage/v1/types.go deleted file mode 100644 index 2a9bdf4c..00000000 --- a/pkg/api/manage/v1/types.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2023 Deepgram SDK contributors. All Rights Reserved. -// Use of this source code is governed by a MIT license that can be found in the LICENSE file. -// SPDX-License-Identifier: MIT - -package manage - -import ( - "bytes" - "io" -) - -type InvitationOptions struct { - Email string `json:"email"` - Scope string `json:"scope"` -} - -type InvitationList struct { - Invites []InvitationOptions `json:"invites"` -} - -type Message struct { - Message string `json:"message"` -} - -type TranscriptionSource interface { - ReadStreamSource | UrlSource | BufferSource -} - -type ReadStreamSource struct { - Stream io.Reader `json:"stream"` - Mimetype string `json:"mimetype"` -} - -type UrlSource struct { - Url string `json:"url"` -} - -type BufferSource struct { - Buffer bytes.Buffer `json:"buffer"` - Mimetype string `json:"mimetype"` -} diff --git a/pkg/api/manage/v1/usage.go b/pkg/api/manage/v1/usage.go index 7043abcf..3666273e 100644 --- a/pkg/api/manage/v1/usage.go +++ b/pkg/api/manage/v1/usage.go @@ -5,231 +5,191 @@ package manage import ( - "fmt" - "io" + "context" "log" "net/http" - "net/url" - "github.com/google/go-querystring/query" + api "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/manage/v1/interfaces" + version "github.com/deepgram-devs/deepgram-go-sdk/pkg/api/version" + interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/interfaces" ) -type UsageRequestListOptions struct { - Start string `json:"start" url:"start,omitempty"` - End string `json:"end" url:"end,omitempty"` - Page int `json:"page" url:"page,omitempty"` - Limit int `json:"limit" url:"limit,omitempty"` - Status string `json:"status" url:"status,omitempty"` -} - -type UsageOptions struct { - Accessor string `json:"accessor" url:"accessor,omitempty"` - Alternatives bool `json:"alternatives" url:"alternatives,omitempty"` - AnalyzeSentiment bool `json:"analyze_sentiment" url:"analyze_sentiment,omitempty"` - DetectEntities bool `json:"detect_entities" url:"detect_entities,omitempty"` - DetectLanguage bool `json:"detect_language" url:"detect_language,omitempty"` - DetectTopics bool `json:"detect_topics" url:"detect_topics,omitempty"` - Diarize bool `json:"diarize" url:"diarize,omitempty"` - End string `json:"end" url:"end,omitempty"` - InterimResults bool `json:"interim_results" url:"interim_results,omitempty"` - Keywords bool `json:"keywords" url:"keywords,omitempty"` - Method string `json:"method" url:"method,omitempty"` // Must be one of "sync" | "async" | "streaming" - Model string `json:"model" url:"model,omitempty"` - Multichannel bool `json:"multichannel" url:"multichannel,omitempty"` - Ner bool `json:"ner" url:"ner,omitempty"` - Numbers bool `json:"numbers" url:"numbers,omitempty"` - Numerals bool `json:"numerals" url:"numerals,omitempty"` - Paragraphs bool `json:"paragraphs" url:"paragraphs,omitempty"` - ProfanityFilter bool `json:"profanity_filter" url:"profanity_filter,omitempty"` - Punctuate bool `json:"punctuate" url:"punctuate,omitempty"` - Redact bool `json:"redact" url:"redact,omitempty"` - Replace bool `json:"replace" url:"replace,omitempty"` - Search bool `json:"search" url:"search,omitempty"` - Sentiment bool `json:"sentiment" url:"sentiment,omitempty"` - SentimentThreshold float64 `json:"sentiment_threshold" url:"sentiment_threshold,omitempty"` - SmartFormat bool `json:"smart_format" url:"smart_format,omitempty"` - Start string `json:"start" url:"start,omitempty"` - Summarize bool `json:"summarize" url:"summarize,omitempty"` - Tag []string `json:"tag" url:"tag,omitempty"` - Translate bool `json:"translate" url:"translate,omitempty"` - Utterances bool `json:"utterances" url:"utterances,omitempty"` - UttSplit bool `json:"utt_split" url:"utt_split,omitempty"` -} +func (c *ManageClient) ListRequests(ctx context.Context, projectId string, use *api.UsageListRequest) (*api.UsageListResult, error) { + // checks + if ctx == nil { + ctx = context.Background() + } -type UsageResponseDetail struct { - Start string `json:"start"` - End string `json:"end"` - Hours float64 `json:"hours"` - Requests int `json:"requests"` -} + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.UsageRequestURI, use, projectId) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + log.Printf("Calling %s\n", URI) // TODO -type UsageSummary struct { - Start string `json:"start"` - End string `json:"end"` - Resolution interface{} `json:"resolution"` - Results []UsageResponseDetail `json:"results"` -} + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } -type UsageRequestList struct { - Page int `json:"page" url:"page,omitempty"` - Limit int `json:"limit" url:"limit,omitempty"` - Requests interface{} `json:"requests" url:"requests,omitempty"` -} + // Do it! + var resp api.UsageListResult + err = c.Client.Do(ctx, req, &resp) -type UsageRequest struct { - RequestId string `json:"request_id" url:"request_id,omitempty"` - Created string `json:"created" url:"created,omitempty"` - Path string `json:"path" url:"path,omitempty"` - Accessor string `json:"accessor" url:"accessor,omitempty"` - Response interface{} `json:"response" url:"response,omitempty"` - Callback interface{} `json:"callback" url:"callback,omitempty"` + if err != nil { + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil } -func (dg *ManageClient) ListRequests(projectId string, options UsageRequestListOptions) (UsageRequestList, error) { - query, _ := query.Values(options) - client := new(http.Client) - path := fmt.Sprintf("%s/%s/requests", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path, RawQuery: query.Encode()} - - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - //Handle Error - log.Panic(err) +func (c *ManageClient) GetRequest(ctx context.Context, projectId string, requestId string) (*api.UsageRequestResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.UsageRequestByIdURI, nil, projectId, requestId) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } + log.Printf("Calling %s\n", URI) // TODO - var result UsageRequestList - res, err := client.Do(req) + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) if err != nil { - return result, err + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) - } - jsonErr := GetJson(res, &result) - if jsonErr != nil { - fmt.Printf("error getting request list: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } + // Do it! + var resp api.UsageRequestResult + err = c.Client.Do(ctx, req, &resp) + if err != nil { + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil } -func (dg *ManageClient) GetRequest(projectId string, requestId string) (UsageRequest, error) { - client := new(http.Client) - path := fmt.Sprintf("%s/%s/requests/%s", dg.Client.Path, projectId, requestId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path} - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - //Handle Error - log.Panic(err) +func (c *ManageClient) GetFields(ctx context.Context, projectId string, use *api.UsageListRequest) (*api.UsageFieldResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.UsageFieldsURI, use, projectId) + if err != nil { + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } + log.Printf("Calling %s\n", URI) // TODO - var result UsageRequest - res, err := client.Do(req) + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) if err != nil { - return result, err + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) - } - jsonErr := GetJson(res, &result) - if jsonErr != nil { - fmt.Printf("error getting request %s: %s\n", requestId, jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } -} + // Do it! + var resp api.UsageFieldResult + err = c.Client.Do(ctx, req, &resp) -func (dg *ManageClient) GetFields(projectId string, options UsageRequestListOptions) (interface{}, error) { - query, _ := query.Values(options) - client := new(http.Client) - path := fmt.Sprintf("%s/%s/usage/fields", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path, RawQuery: query.Encode()} - req, err := http.NewRequest("GET", u.String(), nil) if err != nil { - //Handle Error - log.Panic(err) - } + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil +} - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, +func (c *ManageClient) GetUsage(ctx context.Context, projectId string, use *api.UsageRequest) (*api.UsageResult, error) { + // checks + if ctx == nil { + ctx = context.Background() } - var result interface{} - res, err := client.Do(req) + // request + URI, err := version.GetManageAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.UsageURI, use, projectId) if err != nil { - return result, err - } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - jsonErr := GetJson(res, &result) + log.Printf("Calling %s\n", URI) // TODO - if jsonErr != nil { - fmt.Printf("error getting fields: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } -} - -func (dg *ManageClient) GetUsage(projectId string, options UsageOptions) (UsageSummary, error) { - query, _ := query.Values(options) - client := new(http.Client) - path := fmt.Sprintf("%s/%s/usage", dg.Client.Path, projectId) - u := url.URL{Scheme: "https", Host: dg.Client.Host, Path: path, RawQuery: query.Encode()} - req, err := http.NewRequest("GET", u.String(), nil) + req, err := http.NewRequestWithContext(ctx, "GET", URI, nil) if err != nil { - //Handle Error - log.Panic(err) + // klog.V(1).Infof("http.NewRequestWithContext failed. Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err } - req.Header = http.Header{ - "Host": []string{dg.Client.Host}, - "Content-Type": []string{"application/json"}, - "Authorization": []string{"token " + dg.ApiKey}, - "User-Agent": []string{dgAgent}, - } + // Do it! + var resp api.UsageResult + err = c.Client.Do(ctx, req, &resp) - var result UsageSummary - res, err := client.Do(req) if err != nil { - return result, err - } - if res.StatusCode != 200 { - b, _ := io.ReadAll(res.Body) - log.Panic(string(b)) - } - jsonErr := GetJson(res, &result) - - if jsonErr != nil { - fmt.Printf("error getting usage: %s\n", jsonErr.Error()) - return result, jsonErr - } else { - return result, nil - } + if e, ok := err.(*interfaces.StatusError); ok { + if e.Resp.StatusCode != http.StatusOK { + // klog.V(1).Infof("HTTP Code: %v\n", e.Resp.StatusCode) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + } + + // klog.V(1).Infof("Platform Supplied Err: %v\n", err) + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return nil, err + } + + // klog.V(3).Infof("XXXXXXXX Succeeded\n") + // klog.V(6).Infof("XXXXXXXX LEAVE\n") + return &resp, nil } diff --git a/pkg/api/version/constants.go b/pkg/api/version/constants.go index a1909e48..83594fef 100644 --- a/pkg/api/version/constants.go +++ b/pkg/api/version/constants.go @@ -6,11 +6,6 @@ package version import "errors" -const ( - // default host - DefaultHost string = "api.deepgram.com" -) - var ( // ErrInvalidPath invalid path ErrInvalidPath = errors.New("invalid path") diff --git a/pkg/api/version/live-version.go b/pkg/api/version/live-version.go index f9679d03..f678f9fb 100644 --- a/pkg/api/version/live-version.go +++ b/pkg/api/version/live-version.go @@ -11,10 +11,12 @@ import ( "context" "fmt" "net/url" + "regexp" "github.com/google/go-querystring/query" interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/interfaces" + common "github.com/deepgram-devs/deepgram-go-sdk/pkg/common" ) const ( @@ -22,15 +24,33 @@ const ( LiveAPIVersion string = "v1" // paths - LivePath string = "%s/listen" + LivePath string = "listen" ) -func GetLiveAPI(ctx context.Context, options interfaces.LiveTranscriptionOptions) (string, error) { - if options.Host == "" { - options.Host = DefaultHost +func GetLiveAPI(ctx context.Context, host, version, path string, options interfaces.LiveTranscriptionOptions, args ...interface{}) (string, error) { + if path == "" { + return "", ErrInvalidPath } - if options.ApiVersion == "" { - options.ApiVersion = LiveAPIVersion + + if host == "" { + host = common.DefaultHost + } + if version == "" { + version = LiveAPIVersion + } + + r, err := regexp.Compile("^(v[0-9]+|%%s)/") + if err != nil { + // fmt.Printf("regexp.Compile err: %v\n", err) + return "", err + } + + match := r.MatchString(path) + fmt.Printf("match: %t\n", match) + + if match { + // version = r.FindStringSubmatch(path)[0] + path = r.ReplaceAllString(path, "") } q, err := query.Values(options) @@ -46,6 +66,9 @@ func GetLiveAPI(ctx context.Context, options interfaces.LiveTranscriptionOptions } } - u := url.URL{Scheme: "wss", Host: options.Host, Path: fmt.Sprintf(LivePath, options.ApiVersion), RawQuery: q.Encode()} + fullpath := fmt.Sprintf("%%s/%s", path) + completeFullpath := fmt.Sprintf(fullpath, append([]interface{}{version}, args...)...) + u := url.URL{Scheme: "wss", Host: host, Path: completeFullpath, RawQuery: q.Encode()} + return u.String(), nil } diff --git a/pkg/api/version/manage-version.go b/pkg/api/version/manage-version.go index 3a1b13c0..13b6059e 100644 --- a/pkg/api/version/manage-version.go +++ b/pkg/api/version/manage-version.go @@ -13,45 +13,61 @@ import ( "net/url" "regexp" - "github.com/google/go-querystring/query" - interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/interfaces" + common "github.com/deepgram-devs/deepgram-go-sdk/pkg/common" + "github.com/google/go-querystring/query" ) const ( // version ManageAPIVersion string = "v1" - // Project: /v1/projects - // Keys: /v1/projects//keys - // Members: /v1/projects/members + // balances + BalancesURI string = "projects/%s/balances" + BalancesByIdURI string = "projects/%s/balances/%s" + + // invitations + InvitationsURI string = "projects/%s/invites" + InvitationsByIdURI string = "projects/%s/invites/%s" + InvitationsLeaveURI string = "projects/%s/leave" + + // Keys + KeysURI string = "projects/%s/keys" + KeysByIdURI string = "projects/%s/keys/%s" + + // Members + MembersURI string = "projects/%s/members" + MembersByIdURI string = "projects/%s/members/%s" + + // projects + ProjectsURI string = "projects" + ProjectsByIdURI string = "projects/%s" - // keys - // Path: "/v1/projects", - // TranscriptionPath: "/v1/listen", - // - // path := fmt.Sprintf("%s/%s/keys", dg.Client.Path, projectId) //list - // path := fmt.Sprintf("%s/%s/keys/%s", dg.Client.Path, projectId, keyId) //get - // path := fmt.Sprintf("%s/%s/keys", dg.Client.Path, projectId) // create - // path := fmt.Sprintf("%s/%s/keys/%s", dg.Client.Path, projectId, keyId) //delete + // scopes + MembersScopeByIdURI string = "projects/%s/members/%s/scopes" + // usage + UsageRequestURI string = "projects/%s/requests" + UsageRequestByIdURI string = "projects/%s/requests/%s" + UsageURI string = "projects/%s/usage" + UsageFieldsURI string = "projects/%s/usage/fields" ) -func GetManageAPI(ctx context.Context, host, version, path, key string, vals interface{}) (string, error) { +func GetManageAPI(ctx context.Context, host, version, path string, vals interface{}, args ...interface{}) (string, error) { if path == "" { return "", ErrInvalidPath } if host == "" { - host = DefaultHost + host = common.DefaultHost } if version == "" { version = ManageAPIVersion } - r, err := regexp.Compile("^(v[0-9]+)/") + r, err := regexp.Compile("^(v[0-9]+|%%s)/") if err != nil { - fmt.Printf("regexp.Compile err: %v\n", err) + // fmt.Printf("regexp.Compile err: %v\n", err) return "", err } @@ -63,19 +79,34 @@ func GetManageAPI(ctx context.Context, host, version, path, key string, vals int path = r.ReplaceAllString(path, "") } - q, err := query.Values(vals) - if err != nil { - return "", err + var q url.Values + if vals != nil { + q, err = query.Values(vals) + if err != nil { + return "", err + } } if parameters, ok := ctx.Value(interfaces.ParametersContext{}).(map[string][]string); ok { for k, vs := range parameters { for _, v := range vs { + if q == nil { + q = url.Values{} + } q.Add(k, v) } } } - u := url.URL{Scheme: "https", Host: host, Path: fmt.Sprintf("%s/%s", version, path), RawQuery: q.Encode()} + fullpath := fmt.Sprintf("%%s/%s", path) + completeFullpath := fmt.Sprintf(fullpath, append([]interface{}{version}, args...)...) + + var u url.URL + if q != nil { + u = url.URL{Scheme: "https", Host: host, Path: completeFullpath, RawQuery: q.Encode()} + } else { + u = url.URL{Scheme: "https", Host: host, Path: completeFullpath} + } + return u.String(), nil } diff --git a/pkg/api/version/prerecorded-version.go b/pkg/api/version/prerecorded-version.go index 125ea4cb..2d378eb3 100644 --- a/pkg/api/version/prerecorded-version.go +++ b/pkg/api/version/prerecorded-version.go @@ -11,10 +11,12 @@ import ( "context" "fmt" "net/url" + "regexp" "github.com/google/go-querystring/query" interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/interfaces" + common "github.com/deepgram-devs/deepgram-go-sdk/pkg/common" ) const ( @@ -22,15 +24,33 @@ const ( PrerecordedAPIVersion string = "v1" // paths - PrerecordedPath string = "%s/listen" + PrerecordedPath string = "listen" ) -func GetPrerecordedAPI(ctx context.Context, options interfaces.PreRecordedTranscriptionOptions) (string, error) { - if options.Host == "" { - options.Host = DefaultHost +func GetPrerecordedAPI(ctx context.Context, host, version, path string, options interfaces.PreRecordedTranscriptionOptions, args ...interface{}) (string, error) { + if path == "" { + return "", ErrInvalidPath } - if options.ApiVersion == "" { - options.ApiVersion = PrerecordedAPIVersion + + if host == "" { + host = common.DefaultHost + } + if version == "" { + version = PrerecordedAPIVersion + } + + r, err := regexp.Compile("^(v[0-9]+|%%s)/") + if err != nil { + // fmt.Printf("regexp.Compile err: %v\n", err) + return "", err + } + + match := r.MatchString(path) + fmt.Printf("match: %t\n", match) + + if match { + // version = r.FindStringSubmatch(path)[0] + path = r.ReplaceAllString(path, "") } q, err := query.Values(options) @@ -46,6 +66,9 @@ func GetPrerecordedAPI(ctx context.Context, options interfaces.PreRecordedTransc } } - u := url.URL{Scheme: "https", Host: options.Host, Path: fmt.Sprintf(PrerecordedPath, options.ApiVersion), RawQuery: q.Encode()} + fullpath := fmt.Sprintf("%%s/%s", path) + completeFullpath := fmt.Sprintf(fullpath, append([]interface{}{version}, args...)...) + u := url.URL{Scheme: "https", Host: host, Path: completeFullpath, RawQuery: q.Encode()} + return u.String(), nil } diff --git a/pkg/client/interfaces/types-prerecorded.go b/pkg/client/interfaces/types-prerecorded.go index 9e6f2edd..a03b6d4b 100644 --- a/pkg/client/interfaces/types-prerecorded.go +++ b/pkg/client/interfaces/types-prerecorded.go @@ -5,11 +5,6 @@ package interfaces type PreRecordedTranscriptionOptions struct { - // internal - Host string `url:"-"` - ApiVersion string `url:"-"` - - // live options Alternatives int `json:"alternatives" url:"alternatives,omitempty" ` AnalyzeSentiment bool `json:"analyze_sentiment" url:"analyze_sentiment,omitempty" ` Callback string `json:"callback" url:"callback,omitempty" ` diff --git a/pkg/client/interfaces/types-stream.go b/pkg/client/interfaces/types-stream.go index 99de2ed7..2dab96bb 100644 --- a/pkg/client/interfaces/types-stream.go +++ b/pkg/client/interfaces/types-stream.go @@ -5,13 +5,6 @@ package interfaces type LiveTranscriptionOptions struct { - // internal - Host string `url:"-"` - ApiVersion string `url:"-"` - RedirectService bool `url:"-"` - SkipServerAuth bool `url:"-"` - - // live options Alternatives int `json:"alternatives" url:"alternatives,omitempty" ` Callback string `json:"callback" url:"callback,omitempty" ` Channels int `json:"channels" url:"channels,omitempty" ` diff --git a/pkg/client/live/client.go b/pkg/client/live/client.go index 045a260b..663d7351 100644 --- a/pkg/client/live/client.go +++ b/pkg/client/live/client.go @@ -25,11 +25,11 @@ import ( ) func NewWithDefaults(ctx context.Context, apiKey string, options interfaces.LiveTranscriptionOptions) (*Client, error) { - return New(ctx, apiKey, options, nil) + return New(ctx, apiKey, &ClientOptions{}, options, nil) } // New create new websocket connection -func New(ctx context.Context, apiKey string, options interfaces.LiveTranscriptionOptions, callback msginterfaces.LiveMessageCallback) (*Client, error) { +func New(ctx context.Context, apiKey string, cOptions *ClientOptions, tOptions interfaces.LiveTranscriptionOptions, callback msginterfaces.LiveMessageCallback) (*Client, error) { if apiKey == "" { if v := os.Getenv("DEEPGRAM_API_KEY"); v != "" { log.Println("DEEPGRAM_API_KEY found") @@ -46,7 +46,8 @@ func New(ctx context.Context, apiKey string, options interfaces.LiveTranscriptio // init conn := Client{ apiKey: apiKey, - options: options, + cOptions: cOptions, + tOptions: tOptions, sendBuf: make(chan []byte, 1), callback: callback, router: live.New(callback), @@ -96,8 +97,8 @@ func (c *Client) ConnectWithRetry(retries int64) *websocket.Conn { dialer := websocket.Dialer{ HandshakeTimeout: 45 * time.Second, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - RedirectService: c.options.RedirectService, - SkipServerAuth: c.options.SkipServerAuth, + RedirectService: c.cOptions.RedirectService, + SkipServerAuth: c.cOptions.SkipServerAuth, } // set websocket headers @@ -114,7 +115,7 @@ func (c *Client) ConnectWithRetry(retries int64) *websocket.Conn { } // sets the API key - myHeader.Set("Host", c.options.Host) + myHeader.Set("Host", c.cOptions.Host) myHeader.Set("Authorization", "token "+c.apiKey) myHeader.Set("User-Agent", interfaces.DgAgent) @@ -135,7 +136,7 @@ func (c *Client) ConnectWithRetry(retries int64) *websocket.Conn { i++ // create new connection - url, err := version.GetLiveAPI(c.org, c.options) + url, err := version.GetLiveAPI(c.org, c.cOptions.Host, c.cOptions.ApiVersion, version.LivePath, c.tOptions) if err != nil { log.Printf("version.GetLiveAPI failed. Err: %v\n", err) return nil // no point in retrying because this is going to fail on every retry @@ -147,7 +148,7 @@ func (c *Client) ConnectWithRetry(retries int64) *websocket.Conn { // c, resp, err := websocket.DefaultDialer.Dial(u.String(), header) ws, _, err := dialer.DialContext(c.ctx, url, myHeader) if err != nil { - log.Printf("Cannot connect to websocket: %s\n", c.options.Host) + log.Printf("Cannot connect to websocket: %s\n", c.cOptions.Host) continue } diff --git a/pkg/client/live/types.go b/pkg/client/live/types.go index a14c5abb..48872a0d 100644 --- a/pkg/client/live/types.go +++ b/pkg/client/live/types.go @@ -15,10 +15,20 @@ import ( interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/interfaces" ) +// ClientOptions defines any options for the client +type ClientOptions struct { + Host string + ApiVersion string + Path string + RedirectService bool + SkipServerAuth bool +} + // Client return websocket client connection type Client struct { - apiKey string - options interfaces.LiveTranscriptionOptions + cOptions *ClientOptions + apiKey string + tOptions interfaces.LiveTranscriptionOptions sendBuf chan []byte org context.Context diff --git a/pkg/client/prerecorded/prerecorded.go b/pkg/client/prerecorded/prerecorded.go index 06f55c32..b8583e77 100644 --- a/pkg/client/prerecorded/prerecorded.go +++ b/pkg/client/prerecorded/prerecorded.go @@ -26,7 +26,11 @@ type urlSource struct { } // New allocated a REST client -func New(apiKey string) *Client { +func NewWithDefaults() *Client { + return New("", &ClientOptions{}) +} + +func New(apiKey string, options *ClientOptions) *Client { if apiKey == "" { if v := os.Getenv("DEEPGRAM_API_KEY"); v != "" { log.Println("DEEPGRAM_API_KEY found") @@ -38,7 +42,11 @@ func New(apiKey string) *Client { } c := Client{ - Client: rest.New(apiKey), + Client: rest.New(apiKey, &rest.ClientOptions{ + Host: options.Host, + Version: options.Version, + }), + apiKey: apiKey, } return &c } @@ -71,7 +79,7 @@ func (c *Client) DoStream(ctx context.Context, src io.Reader, options interfaces //klog.V(6).Infof("rest.doCommonFile ENTER\n") // obtain URL - URI, err := version.GetPrerecordedAPI(ctx, options) + URI, err := version.GetPrerecordedAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.PrerecordedPath, options) if err != nil { log.Printf("version.GetPrerecordedAPI failed. Err: %v\n", err) return err @@ -95,10 +103,10 @@ func (c *Client) DoStream(ctx context.Context, src io.Reader, options interfaces } } - req.Header.Set("Host", options.Host) + req.Header.Set("Host", c.Client.Options.Host) req.Header.Set("Accept", "application/json") req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", "token "+c.ApiKey) + req.Header.Set("Authorization", "token "+c.apiKey) req.Header.Set("User-Agent", interfaces.DgAgent) err = c.HttpClient.Do(ctx, req, func(res *http.Response) error { @@ -176,7 +184,7 @@ func (c *Client) DoURL(ctx context.Context, url string, options interfaces.PreRe } // obtain URL - URI, err := version.GetPrerecordedAPI(ctx, options) + URI, err := version.GetPrerecordedAPI(ctx, c.Client.Options.Host, c.Client.Options.Version, version.PrerecordedPath, options) if err != nil { log.Printf("version.GetPrerecordedAPI failed. Err: %v\n", err) return err @@ -208,9 +216,9 @@ func (c *Client) DoURL(ctx context.Context, url string, options interfaces.PreRe } } - req.Header.Set("Host", options.Host) + req.Header.Set("Host", c.Client.Options.Host) req.Header.Set("Accept", "application/json") - req.Header.Set("Authorization", "token "+c.ApiKey) + req.Header.Set("Authorization", "token "+c.apiKey) req.Header.Set("User-Agent", interfaces.DgAgent) switch req.Method { @@ -289,7 +297,7 @@ func (c *Client) Do(ctx context.Context, req *http.Request, resBody interface{}) // req.Header.Set("Host", c.options.Host) req.Header.Set("Accept", "application/json") - req.Header.Set("Authorization", "token "+c.ApiKey) + req.Header.Set("Authorization", "token "+c.apiKey) req.Header.Set("User-Agent", interfaces.DgAgent) switch req.Method { diff --git a/pkg/client/prerecorded/types.go b/pkg/client/prerecorded/types.go index adcefff3..b1685853 100644 --- a/pkg/client/prerecorded/types.go +++ b/pkg/client/prerecorded/types.go @@ -8,7 +8,15 @@ import ( rest "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/rest" ) +// ClientOptions defines any options for the client +type ClientOptions struct { + Host string + Version string +} + // Client implements helper functionality for Prerecorded API type Client struct { *rest.Client + + apiKey string } diff --git a/pkg/client/rest/rest.go b/pkg/client/rest/rest.go index 264bcbfa..ae45290d 100644 --- a/pkg/client/rest/rest.go +++ b/pkg/client/rest/rest.go @@ -15,10 +15,18 @@ import ( "os" interfaces "github.com/deepgram-devs/deepgram-go-sdk/pkg/client/interfaces" + common "github.com/deepgram-devs/deepgram-go-sdk/pkg/common" ) +func NewWithDefaults() *Client { + return New("", &ClientOptions{}) +} + // New allocated a REST client -func New(apiKey string) *Client { +func New(apiKey string, options *ClientOptions) *Client { + if options.Host == "" { + options.Host = common.DefaultHost + } if apiKey == "" { if v := os.Getenv("DEEPGRAM_API_KEY"); v != "" { log.Println("DEEPGRAM_API_KEY found") @@ -31,7 +39,8 @@ func New(apiKey string) *Client { c := Client{ HttpClient: NewHTTPClient(), - ApiKey: apiKey, + Options: options, + apiKey: apiKey, } return &c } @@ -51,7 +60,7 @@ func (c *Client) Do(ctx context.Context, req *http.Request, resBody interface{}) // req.Header.Set("Host", c.options.Host) req.Header.Set("Accept", "application/json") - req.Header.Set("Authorization", "token "+c.ApiKey) + req.Header.Set("Authorization", "token "+c.apiKey) req.Header.Set("User-Agent", interfaces.DgAgent) switch req.Method { diff --git a/pkg/client/rest/types.go b/pkg/client/rest/types.go index 04a13723..bd583375 100644 --- a/pkg/client/rest/types.go +++ b/pkg/client/rest/types.go @@ -8,6 +8,12 @@ import ( "net/http" ) +// ClientOptions defines any options for the client +type ClientOptions struct { + Host string + Version string +} + // HttpClient which extends HTTP client type HttpClient struct { http.Client @@ -20,5 +26,6 @@ type HttpClient struct { type Client struct { *HttpClient - ApiKey string + Options *ClientOptions + apiKey string } diff --git a/pkg/client/interfaces/constants.go b/pkg/common/constants.go similarity index 67% rename from pkg/client/interfaces/constants.go rename to pkg/common/constants.go index 5674761e..be0572be 100644 --- a/pkg/client/interfaces/constants.go +++ b/pkg/common/constants.go @@ -2,9 +2,9 @@ // Use of this source code is governed by a MIT license that can be found in the LICENSE file. // SPDX-License-Identifier: MIT -package interfaces +package common -// API constants -// const ( -// DefaultHost string = "api.deepgram.com" -// ) +const ( + // default host + DefaultHost string = "api.deepgram.com" +) diff --git a/tests/prerecorded_test.go b/tests/prerecorded_test.go index b4169d47..18bf40c3 100644 --- a/tests/prerecorded_test.go +++ b/tests/prerecorded_test.go @@ -124,7 +124,7 @@ func TestPrerecordedFromURL(t *testing.T) { httpmock.RegisterResponder("POST", betaEndPoint, preRecordedFromURLHandler) t.Run("Test Basic PreRecordedFromURL", func(t *testing.T) { - c := client.New(MockAPIKey) + c := client.New(MockAPIKey, &client.ClientOptions{}) httpmock.ActivateNonDefault(&c.Client.HttpClient.Client) dg := prerecorded.New(c) _, err := dg.FromURL( @@ -138,7 +138,7 @@ func TestPrerecordedFromURL(t *testing.T) { }) t.Run("Test PreRecordedFromURL with summarize v1", func(t *testing.T) { - c := client.New(MockAPIKey) + c := client.New(MockAPIKey, &client.ClientOptions{}) httpmock.ActivateNonDefault(&c.Client.HttpClient.Client) dg := prerecorded.New(c) _, err := dg.FromURL( @@ -154,7 +154,7 @@ func TestPrerecordedFromURL(t *testing.T) { }) t.Run("Test PreRecordedFromURL with summarize v2", func(t *testing.T) { - c := client.New(MockAPIKey) + c := client.New(MockAPIKey, &client.ClientOptions{}) httpmock.ActivateNonDefault(&c.Client.HttpClient.Client) dg := prerecorded.New(c) _, err := dg.FromURL(