Skip to content

Commit

Permalink
Make inpost service ctx aware
Browse files Browse the repository at this point in the history
  • Loading branch information
alufers committed Oct 5, 2023
1 parent 76f9b83 commit 66f7faa
Show file tree
Hide file tree
Showing 8 changed files with 48 additions and 38 deletions.
20 changes: 12 additions & 8 deletions inpostextra/inpost_service.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package inpostextra

import "gorm.io/gorm"
import (
"context"

"gorm.io/gorm"
)

type InpostService interface {
SendSMSCode(phoneNumber string) error
ConfirmSMSCode(phoneNumber string, code string) (*InpostCredentials, error)
Authenticate(creds *InpostCredentials) error
ReauthenticateIfNeeded(db *gorm.DB, creds *InpostCredentials) error
GetParcel(db *gorm.DB, creds *InpostCredentials, shipmentNumber string) (*InpostParcel, error)
GetUserParcels(db *gorm.DB, creds *InpostCredentials) (*GetTrackedParcelsResponse, error)
OpenParcelLocker(db *gorm.DB, creds *InpostCredentials, shipmentNumber string) error
SendSMSCode(ctx context.Context, phoneNumber string) error
ConfirmSMSCode(ctx context.Context, phoneNumber string, code string) (*InpostCredentials, error)
Authenticate(ctx context.Context, creds *InpostCredentials) error
ReauthenticateIfNeeded(ctx context.Context, db *gorm.DB, creds *InpostCredentials) error
GetParcel(ctx context.Context, db *gorm.DB, creds *InpostCredentials, shipmentNumber string) (*InpostParcel, error)
GetUserParcels(ctx context.Context, db *gorm.DB, creds *InpostCredentials) (*GetTrackedParcelsResponse, error)
OpenParcelLocker(ctx context.Context, db *gorm.DB, creds *InpostCredentials, shipmentNumber string) error
}
44 changes: 24 additions & 20 deletions inpostextra/inpost_service_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package inpostextra

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -34,7 +35,10 @@ func NewInpostService(
}
}

func (s *InpostServiceImpl) makeJSONRequest(creds *InpostCredentials, method string, path string, data interface{}, respRef interface{}) error {
func (s *InpostServiceImpl) makeJSONRequest(
ctx context.Context,
creds *InpostCredentials, method string, path string, data interface{}, respRef interface{},
) error {
var bodyBuf io.Reader
if method != "GET" && method != "HEAD" {
body, err := json.Marshal(data)
Expand All @@ -47,7 +51,7 @@ func (s *InpostServiceImpl) makeJSONRequest(creds *InpostCredentials, method str
if bodyBuf != nil {
log.Printf("Body: %s", bodyBuf)
}
httpReq, err := http.NewRequest(method, s.BaseURL+path, bodyBuf)
httpReq, err := http.NewRequestWithContext(ctx, method, s.BaseURL+path, bodyBuf)
if err != nil {
return fmt.Errorf("error creating HTTP request: %s", err)
}
Expand Down Expand Up @@ -87,17 +91,17 @@ func (s *InpostServiceImpl) makeJSONRequest(creds *InpostCredentials, method str
return nil
}

func (s *InpostServiceImpl) SendSMSCode(phoneNumber string) error {
func (s *InpostServiceImpl) SendSMSCode(ctx context.Context, phoneNumber string) error {
phoneNumber = NormalizePhoneNumber(phoneNumber)

// make a post request to /v1/sendSMSCode with the phone number sent as JSON
data := map[string]string{
"phoneNumber": phoneNumber,
}
return s.makeJSONRequest(nil, "POST", "/v1/sendSMSCode", data, nil)
return s.makeJSONRequest(ctx, nil, "POST", "/v1/sendSMSCode", data, nil)
}

func (s *InpostServiceImpl) ConfirmSMSCode(phoneNumber string, code string) (*InpostCredentials, error) {
func (s *InpostServiceImpl) ConfirmSMSCode(ctx context.Context, phoneNumber string, code string) (*InpostCredentials, error) {
phoneNumber = NormalizePhoneNumber(phoneNumber)
// make a post request to /v1/confirmSMSCode with the phone number and code sent as JSON
data := map[string]string{
Expand All @@ -110,7 +114,7 @@ func (s *InpostServiceImpl) ConfirmSMSCode(phoneNumber string, code string) (*In
AuthToken string `json:"authToken"`
RefreshToken string `json:"refreshToken"`
}{}
err := s.makeJSONRequest(nil, "POST", "/v1/confirmSMSCode", data, out)
err := s.makeJSONRequest(ctx, nil, "POST", "/v1/confirmSMSCode", data, out)
if err != nil {
return nil, err
}
Expand All @@ -124,7 +128,7 @@ func (s *InpostServiceImpl) ConfirmSMSCode(phoneNumber string, code string) (*In
}

// Authenticate uses the refresh token to get a new access token.
func (s *InpostServiceImpl) Authenticate(creds *InpostCredentials) error {
func (s *InpostServiceImpl) Authenticate(ctx context.Context, creds *InpostCredentials) error {
// make a post request to /v1/authenticate with the access token and refresh token sent as JSON
data := map[string]string{
"phoneOS": "Android",
Expand All @@ -135,7 +139,7 @@ func (s *InpostServiceImpl) Authenticate(creds *InpostCredentials) error {
ReauthenticationRequired bool `json:"reauthenticationRequired"`
RefreshTokenExpiryDate *time.Time `json:"refreshTokenExpiryDate"`
}{}
err := s.makeJSONRequest(nil, "POST", "/v1/authenticate", data, out)
err := s.makeJSONRequest(ctx, nil, "POST", "/v1/authenticate", data, out)
if err != nil {
return err
}
Expand All @@ -150,7 +154,7 @@ func (s *InpostServiceImpl) Authenticate(creds *InpostCredentials) error {
return nil
}

func (s *InpostServiceImpl) ReauthenticateIfNeeded(db *gorm.DB, creds *InpostCredentials) error {
func (s *InpostServiceImpl) ReauthenticateIfNeeded(ctx context.Context, db *gorm.DB, creds *InpostCredentials) error {
if creds.RefreshToken == "" {
return fmt.Errorf("refresh token is empty")
}
Expand All @@ -164,7 +168,7 @@ func (s *InpostServiceImpl) ReauthenticateIfNeeded(db *gorm.DB, creds *InpostCre
expirationDate := time.Unix(claims.ExpiresAt, 0)
if expirationDate.Before(time.Now()) {
log.Printf("Inpost token for phone number %v expired %v ago, refreshing...", creds.PhoneNumber, time.Since(expirationDate))
err := s.Authenticate(creds)
err := s.Authenticate(ctx, creds)
if err != nil {
return err
}
Expand All @@ -177,38 +181,38 @@ func (s *InpostServiceImpl) ReauthenticateIfNeeded(db *gorm.DB, creds *InpostCre
return nil
}

func (s *InpostServiceImpl) GetParcel(db *gorm.DB, creds *InpostCredentials, shipmentNumber string) (*InpostParcel, error) {
err := s.ReauthenticateIfNeeded(db, creds)
func (s *InpostServiceImpl) GetParcel(ctx context.Context, db *gorm.DB, creds *InpostCredentials, shipmentNumber string) (*InpostParcel, error) {
err := s.ReauthenticateIfNeeded(ctx, db, creds)
if err != nil {
return nil, err
}

// make a get request to /v1/parcel/{shipmentNumber}
out := &InpostParcel{}
err = s.makeJSONRequest(creds, "GET", fmt.Sprintf("/v3/parcels/tracked/%s", shipmentNumber), nil, out)
err = s.makeJSONRequest(ctx, creds, "GET", fmt.Sprintf("/v3/parcels/tracked/%s", shipmentNumber), nil, out)
if err != nil {
return nil, err
}
return out, nil
}

func (s *InpostServiceImpl) GetUserParcels(db *gorm.DB, creds *InpostCredentials) (*GetTrackedParcelsResponse, error) {
err := s.ReauthenticateIfNeeded(db, creds)
func (s *InpostServiceImpl) GetUserParcels(ctx context.Context, db *gorm.DB, creds *InpostCredentials) (*GetTrackedParcelsResponse, error) {
err := s.ReauthenticateIfNeeded(ctx, db, creds)
if err != nil {
return nil, err
}

// make a get request to parcels
out := &GetTrackedParcelsResponse{}
err = s.makeJSONRequest(creds, "GET", "/v3/parcels/tracked", nil, &out)
err = s.makeJSONRequest(ctx, creds, "GET", "/v3/parcels/tracked", nil, &out)
if err != nil {
return nil, err
}
return out, nil
}

func (s *InpostServiceImpl) OpenParcelLocker(db *gorm.DB, creds *InpostCredentials, shipmentNumber string) error {
parcel, err := s.GetParcel(db, creds, shipmentNumber)
func (s *InpostServiceImpl) OpenParcelLocker(ctx context.Context, db *gorm.DB, creds *InpostCredentials, shipmentNumber string) error {
parcel, err := s.GetParcel(ctx, db, creds, shipmentNumber)
if err != nil {
return fmt.Errorf("error getting parcel details before opening: %v", err)
}
Expand All @@ -231,13 +235,13 @@ func (s *InpostServiceImpl) OpenParcelLocker(db *gorm.DB, creds *InpostCredentia
},
}
validateResp := &ValidateCompartmentResponse{}
err = s.makeJSONRequest(creds, "POST", "/v1/collect/validate", startOpenSessionRequest, validateResp)
err = s.makeJSONRequest(ctx, creds, "POST", "/v1/collect/validate", startOpenSessionRequest, validateResp)
if err != nil {
return fmt.Errorf("error validating compartment: %v", err)
}

openResp := make(map[string]any)
err = s.makeJSONRequest(creds, "POST", "/v1/collect/compartment/open/"+validateResp.SessionUUID, map[string]any{
err = s.makeJSONRequest(ctx, creds, "POST", "/v1/collect/compartment/open/"+validateResp.SessionUUID, map[string]any{
"sessionUuid": validateResp.SessionUUID,
}, &openResp)
if err != nil {
Expand Down
3 changes: 2 additions & 1 deletion inpostextra/inpost_service_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package inpostextra_test

import (
"context"
"net/http"
"testing"

Expand All @@ -25,7 +26,7 @@ func TestInpostServiceSendSMSCode(t *testing.T) {
serv := inpostextra.NewInpostService(&http.Client{
Transport: mockTransport,
})
err := serv.SendSMSCode("123456789")
err := serv.SendSMSCode(context.TODO(), "123456789")
assert.NoError(t, err)
assert.Equal(t, 1, mockTransport.RequestCount)
}
7 changes: 4 additions & 3 deletions paczkobot/bot_app.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package paczkobot
import (
"log"
"net/http"
"time"

"github.com/alufers/paczkobot/httphelpers"
"github.com/alufers/paczkobot/inpostextra"
"github.com/alufers/paczkobot/tghelpers"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
Expand Down Expand Up @@ -33,9 +35,8 @@ func NewBotApp(b *tgbotapi.BotAPI, DB *gorm.DB) (a *BotApp) {
Bot: b,
DB: DB,
}
a.BaseHTTPClient = &http.Client{
Timeout: 10,
}
a.BaseHTTPClient = httphelpers.NewClientWithLogger()
a.BaseHTTPClient.Timeout = time.Second * 25
a.AskService = tghelpers.NewAskService(a.Bot)
a.CommandDispatcher = tghelpers.NewCommandDispatcher(
b,
Expand Down
4 changes: 2 additions & 2 deletions paczkobot/inpost_login_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func (f *InpostLoginCommand) Execute(ctx context.Context) error {
if err != nil {
return err
}
err = f.App.InpostService.SendSMSCode(phoneNumber)
err = f.App.InpostService.SendSMSCode(ctx, phoneNumber)
if err != nil {
return fmt.Errorf("failed to send sms code: %v", err)
}
Expand All @@ -43,7 +43,7 @@ func (f *InpostLoginCommand) Execute(ctx context.Context) error {
return err
}

creds, err := f.App.InpostService.ConfirmSMSCode(phoneNumber, code)
creds, err := f.App.InpostService.ConfirmSMSCode(ctx, phoneNumber, code)
if err != nil {
return fmt.Errorf("failed to confirm sms code: %v", err)
}
Expand Down
4 changes: 2 additions & 2 deletions paczkobot/inpost_open_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func (f *InpostOpenCommand) Execute(ctx context.Context) error {
}

for _, cred := range creds {
p, err := f.App.InpostService.GetParcel(f.App.DB, cred, trackingNumber)
p, err := f.App.InpostService.GetParcel(ctx, f.App.DB, cred, trackingNumber)
if err != nil {
log.Printf("failed to get parcel: %v", err)
continue
Expand All @@ -98,7 +98,7 @@ func (f *InpostOpenCommand) Execute(ctx context.Context) error {
if err != nil {
return err
}
err = f.App.InpostService.OpenParcelLocker(f.App.DB, cred, p.ShipmentNumber)
err = f.App.InpostService.OpenParcelLocker(ctx, f.App.DB, cred, p.ShipmentNumber)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion paczkobot/inpost_qr_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (f *InpostQrCommand) Execute(ctx context.Context) error {
}

for _, cred := range creds {
p, err := f.App.InpostService.GetParcel(f.App.DB, cred, trackingNumber)
p, err := f.App.InpostService.GetParcel(ctx, f.App.DB, cred, trackingNumber)
if err != nil {
log.Printf("failed to get parcel: %v", err)
continue
Expand Down
2 changes: 1 addition & 1 deletion paczkobot/inpost_scanner_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func NewInpostScannerService(app *BotApp) *InpostScannerService {
}

func (s *InpostScannerService) ScanUserPackages(ctx context.Context, creds *inpostextra.InpostCredentials) error {
resp, err := s.app.InpostService.GetUserParcels(s.app.DB, creds)
resp, err := s.app.InpostService.GetUserParcels(ctx, s.app.DB, creds)
if err != nil {
return err
}
Expand Down

0 comments on commit 66f7faa

Please sign in to comment.