From e76dbf044ef1d199299629651feb524cd01daf82 Mon Sep 17 00:00:00 2001 From: Majd Alfhaily Date: Sat, 8 Apr 2023 22:56:52 +0200 Subject: [PATCH] Refactor purchase flow (#169) --- pkg/appstore/appstore_purchase.go | 72 ++++++++++++++------------ pkg/appstore/appstore_purchase_test.go | 59 +++++++++++++++++++++ pkg/appstore/constants.go | 6 ++- pkg/appstore/errors.go | 3 +- pkg/util/string.go | 2 +- 5 files changed, 107 insertions(+), 35 deletions(-) diff --git a/pkg/appstore/appstore_purchase.go b/pkg/appstore/appstore_purchase.go index 351ee56..626ca19 100644 --- a/pkg/appstore/appstore_purchase.go +++ b/pkg/appstore/appstore_purchase.go @@ -32,6 +32,41 @@ func (a *appstore) Purchase(bundleID string) error { return nil } +func (a *appstore) purchase(bundleID string, guid string, attemptToRenewCredentials bool) error { + acc, err := a.account() + if err != nil { + return errors.Wrap(err, ErrGetAccount.Error()) + } + + countryCode, err := a.countryCodeFromStoreFront(acc.StoreFront) + if err != nil { + return errors.Wrap(err, ErrInvalidCountryCode.Error()) + } + + app, err := a.lookup(bundleID, countryCode) + if err != nil { + return errors.Wrap(err, ErrAppLookup.Error()) + } + + if app.Price > 0 { + return ErrPaidApp + } + + err = a.purchaseWithParams(acc, app, bundleID, guid, attemptToRenewCredentials, PricingParameterAppStore) + if err != nil { + if err == ErrTemporarilyUnavailable { + err = a.purchaseWithParams(acc, app, bundleID, guid, attemptToRenewCredentials, PricingParameterAppleArcade) + if err != nil { + return errors.Wrapf(err, "failed to purchase item with param '%s'", PricingParameterAppleArcade) + } + } + + return errors.Wrapf(err, "failed to purchase item with param '%s'", PricingParameterAppStore) + } + + return nil +} + func (a *appstore) purchaseWithParams(acc Account, app App, bundleID string, guid string, attemptToRenewCredentials bool, pricingParameters string) error { req := a.purchaseRequest(acc, app, acc.StoreFront, guid, pricingParameters) res, err := a.purchaseClient.Send(req) @@ -43,6 +78,11 @@ func (a *appstore) purchaseWithParams(acc Account, app App, bundleID string, gui return ErrTemporarilyUnavailable } + if res.Data.CustomerMessage == CustomerMessageSubscriptionRequired { + a.logger.Verbose().Interface("response", res).Send() + return ErrSubscriptionRequired + } + if res.Data.FailureType == FailureTypePasswordTokenExpired { if attemptToRenewCredentials { a.logger.Verbose().Msg("retrieving new password token") @@ -79,38 +119,6 @@ func (a *appstore) purchaseWithParams(acc Account, app App, bundleID string, gui return nil } -func (a *appstore) purchase(bundleID string, guid string, attemptToRenewCredentials bool) error { - acc, err := a.account() - if err != nil { - return errors.Wrap(err, ErrGetAccount.Error()) - } - - countryCode, err := a.countryCodeFromStoreFront(acc.StoreFront) - if err != nil { - return errors.Wrap(err, ErrInvalidCountryCode.Error()) - } - - app, err := a.lookup(bundleID, countryCode) - if err != nil { - return errors.Wrap(err, ErrAppLookup.Error()) - } - - if app.Price > 0 { - return ErrPaidApp - } - - for _, pricingParameters := range []string{"STDQ", "GAME"} { - if err := a.purchaseWithParams(acc, app, bundleID, guid, attemptToRenewCredentials, pricingParameters); err == ErrTemporarilyUnavailable { - continue - } else if err != nil { - return err - } else { - return nil - } - } - return ErrTemporarilyUnavailable -} - func (*appstore) countryCodeFromStoreFront(storeFront string) (string, error) { for key, val := range StoreFronts { parts := strings.Split(storeFront, "-") diff --git a/pkg/appstore/appstore_purchase_test.go b/pkg/appstore/appstore_purchase_test.go index 151ca8b..ebf2c4e 100644 --- a/pkg/appstore/appstore_purchase_test.go +++ b/pkg/appstore/appstore_purchase_test.go @@ -444,6 +444,65 @@ var _ = Describe("AppStore (Purchase)", func() { }) }) + When("subscription is required", func() { + BeforeEach(func() { + mockKeychain.EXPECT(). + Get("account"). + Return([]byte("{\"storeFront\":\"143441\"}"), nil) + + mockSearchClient.EXPECT(). + Send(gomock.Any()). + Return(http.Result[SearchResult]{ + StatusCode: 200, + Data: SearchResult{ + Count: 1, + Results: []App{ + { + ID: 0, + BundleID: "", + Name: "", + Version: "", + Price: 0, + }, + }, + }, + }, nil) + + mockMachine.EXPECT(). + MacAddress(). + Return("00:00:00:00:00:00", nil) + + mockPurchaseClient.EXPECT(). + Send(pricingParametersMatcher{"STDQ"}). + Return(http.Result[PurchaseResult]{ + StatusCode: 200, + Data: PurchaseResult{ + CustomerMessage: "This item is temporarily unavailable.", + FailureType: FailureTypeTemporarilyUnavailable, + }, + }, nil) + + mockPurchaseClient.EXPECT(). + Send(pricingParametersMatcher{"GAME"}). + Return(http.Result[PurchaseResult]{ + StatusCode: 200, + Data: PurchaseResult{ + CustomerMessage: CustomerMessageSubscriptionRequired, + }, + }, nil) + + mockLogger.EXPECT(). + Verbose(). + Return(nil). + Times(2) + }) + + It("returns error", func() { + err := as.Purchase("") + Expect(err).To(MatchError(ContainSubstring(ErrSubscriptionRequired.Error()))) + }) + }) + When("successfully purchases the app", func() { BeforeEach(func() { mockKeychain.EXPECT(). diff --git a/pkg/appstore/constants.go b/pkg/appstore/constants.go index cfd6a92..829fc64 100644 --- a/pkg/appstore/constants.go +++ b/pkg/appstore/constants.go @@ -6,7 +6,8 @@ const ( FailureTypeLicenseNotFound = "9610" FailureTypeTemporarilyUnavailable = "2059" - CustomerMessageBadLogin = "MZFinance.BadLogin.Configurator_message" + CustomerMessageBadLogin = "MZFinance.BadLogin.Configurator_message" + CustomerMessageSubscriptionRequired = "Subscription Required" iTunesAPIDomain = "itunes.apple.com" iTunesAPIPathSearch = "/search" @@ -20,4 +21,7 @@ const ( PrivateAppStoreAPIPathDownload = "/WebObjects/MZFinance.woa/wa/volumeStoreDownloadProduct" HTTPHeaderStoreFront = "X-Set-Apple-Store-Front" + + PricingParameterAppStore = "STDQ" + PricingParameterAppleArcade = "GAME" ) diff --git a/pkg/appstore/errors.go b/pkg/appstore/errors.go index e001b35..d6a0191 100644 --- a/pkg/appstore/errors.go +++ b/pkg/appstore/errors.go @@ -49,9 +49,10 @@ var ( ErrRequest = errors.New("failed to send request") ErrResolveDestinationPath = errors.New("failed to resolve destination path") ErrSetKeychainItem = errors.New("failed to save item in keychain") + ErrSubscriptionRequired = errors.New("subscription required") + ErrTemporarilyUnavailable = errors.New("item is temporarily unavailable") ErrUnmarshal = errors.New("failed to unmarshal data") ErrWriteMetadataFile = errors.New("failed to write metadata") ErrWriteSinfData = errors.New("failed to write sinf data") ErrZipSinfs = errors.New("failed to zip sinfs and sinf paths") - ErrTemporarilyUnavailable = errors.New("item is temporarily unavailable") ) diff --git a/pkg/util/string.go b/pkg/util/string.go index 33946ca..019d1af 100644 --- a/pkg/util/string.go +++ b/pkg/util/string.go @@ -6,4 +6,4 @@ func IfEmpty(value, fallback string) string { } return value -} \ No newline at end of file +}