playstore.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. package controller
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/ente-io/museum/pkg/controller/commonbilling"
  6. "github.com/ente-io/museum/pkg/repo/storagebonus"
  7. "os"
  8. "github.com/ente-io/stacktrace"
  9. log "github.com/sirupsen/logrus"
  10. "github.com/awa/go-iap/playstore"
  11. "github.com/ente-io/museum/ente"
  12. "github.com/ente-io/museum/pkg/repo"
  13. "github.com/ente-io/museum/pkg/utils/config"
  14. "github.com/ente-io/museum/pkg/utils/email"
  15. "google.golang.org/api/androidpublisher/v3"
  16. )
  17. // PlayStoreController provides abstractions for handling billing on AppStore
  18. type PlayStoreController struct {
  19. PlayStoreClient *playstore.Client
  20. BillingRepo *repo.BillingRepository
  21. FileRepo *repo.FileRepository
  22. UserRepo *repo.UserRepository
  23. StorageBonusRepo *storagebonus.Repository
  24. BillingPlansPerCountry ente.BillingPlansPerCountry
  25. CommonBillCtrl *commonbilling.Controller
  26. }
  27. // PlayStorePackageName is the package name of the PlayStore item
  28. const PlayStorePackageName = "io.ente.photos"
  29. // Return a new instance of PlayStoreController
  30. func NewPlayStoreController(
  31. plans ente.BillingPlansPerCountry,
  32. billingRepo *repo.BillingRepository,
  33. fileRepo *repo.FileRepository,
  34. userRepo *repo.UserRepository,
  35. storageBonusRepo *storagebonus.Repository,
  36. commonBillCtrl *commonbilling.Controller,
  37. ) *PlayStoreController {
  38. playStoreClient, err := newPlayStoreClient()
  39. if err != nil {
  40. log.Fatal(err)
  41. }
  42. // We don't do nil checks for playStoreClient in the definitions of these
  43. // methods - if they're getting called, that means we're not in a test
  44. // environment and so playStoreClient really should've been there.
  45. return &PlayStoreController{
  46. PlayStoreClient: playStoreClient,
  47. BillingRepo: billingRepo,
  48. FileRepo: fileRepo,
  49. UserRepo: userRepo,
  50. BillingPlansPerCountry: plans,
  51. StorageBonusRepo: storageBonusRepo,
  52. CommonBillCtrl: commonBillCtrl,
  53. }
  54. }
  55. func newPlayStoreClient() (*playstore.Client, error) {
  56. playStoreCredentialsFile, err := config.CredentialFilePath("pst-service-account.json")
  57. if err != nil {
  58. return nil, stacktrace.Propagate(err, "")
  59. }
  60. if playStoreCredentialsFile == "" {
  61. // Can happen when running locally
  62. return nil, nil
  63. }
  64. jsonKey, err := os.ReadFile(playStoreCredentialsFile)
  65. if err != nil {
  66. return nil, stacktrace.Propagate(err, "")
  67. }
  68. playStoreClient, err := playstore.New(jsonKey)
  69. if err != nil {
  70. return nil, stacktrace.Propagate(err, "")
  71. }
  72. return playStoreClient, nil
  73. }
  74. // HandleNotification handles a PlayStore notification
  75. func (c *PlayStoreController) HandleNotification(notification playstore.DeveloperNotification) error {
  76. transactionID := notification.SubscriptionNotification.PurchaseToken
  77. productID := notification.SubscriptionNotification.SubscriptionID
  78. purchase, err := c.verifySubscription(productID, transactionID)
  79. if err != nil {
  80. return stacktrace.Propagate(err, "")
  81. }
  82. originalTransactionID := transactionID
  83. if purchase.LinkedPurchaseToken != "" {
  84. originalTransactionID = purchase.LinkedPurchaseToken
  85. }
  86. subscription, err := c.BillingRepo.GetSubscriptionForTransaction(originalTransactionID, ente.PlayStore)
  87. if err != nil {
  88. // First subscription, no user to link to
  89. log.Warn("Could not find transaction against " + originalTransactionID)
  90. log.Error(err)
  91. return nil
  92. }
  93. switch notification.SubscriptionNotification.NotificationType {
  94. case playstore.SubscriptionNotificationTypeExpired:
  95. user, err := c.UserRepo.Get(subscription.UserID)
  96. if err != nil {
  97. if errors.Is(err, ente.ErrUserDeleted) {
  98. // no-op user has already been deleted
  99. return nil
  100. }
  101. return stacktrace.Propagate(err, "")
  102. }
  103. // send deletion email for folks who are either on individual plan or admin of a family plan
  104. if user.FamilyAdminID == nil || *user.FamilyAdminID == subscription.UserID {
  105. storage, surpErr := c.StorageBonusRepo.GetPaidAddonSurplusStorage(context.Background(), subscription.UserID)
  106. if surpErr != nil {
  107. return stacktrace.Propagate(surpErr, "")
  108. }
  109. if storage == nil || *storage <= 0 {
  110. err = email.SendTemplatedEmail([]string{user.Email}, "ente", "support@ente.io",
  111. ente.SubscriptionEndedEmailSubject,
  112. ente.SubscriptionEndedEmailTemplate, map[string]interface{}{}, nil)
  113. if err != nil {
  114. return stacktrace.Propagate(err, "")
  115. }
  116. } else {
  117. log.WithField("storage", storage).Info("User has surplus storage, not sending email")
  118. }
  119. }
  120. // TODO: Add cron to delete files of users with expired subscriptions
  121. case playstore.SubscriptionNotificationTypeAccountHold:
  122. user, err := c.UserRepo.Get(subscription.UserID)
  123. if err != nil {
  124. return stacktrace.Propagate(err, "")
  125. }
  126. err = email.SendTemplatedEmail([]string{user.Email}, "ente", "support@ente.io",
  127. ente.AccountOnHoldEmailSubject,
  128. ente.OnHoldTemplate, map[string]interface{}{
  129. "PaymentProvider": "PlayStore",
  130. }, nil)
  131. if err != nil {
  132. return stacktrace.Propagate(err, "")
  133. }
  134. case playstore.SubscriptionNotificationTypeCanceled:
  135. err := c.BillingRepo.UpdateSubscriptionCancellationStatus(subscription.UserID, true)
  136. if err != nil {
  137. return stacktrace.Propagate(err, "")
  138. }
  139. }
  140. if transactionID != originalTransactionID { // Upgrade, Downgrade or Resubscription
  141. var newPlan ente.BillingPlan
  142. plans := c.BillingPlansPerCountry["EU"] // Country code is irrelevant since Storage will be the same for a given subscriptionID
  143. for _, plan := range plans {
  144. if plan.AndroidID == productID {
  145. newPlan = plan
  146. break
  147. }
  148. }
  149. if newPlan.Storage < subscription.Storage { // Downgrade
  150. canDowngrade, canDowngradeErr := c.CommonBillCtrl.CanDowngradeToGivenStorage(newPlan.Storage, subscription.UserID)
  151. if canDowngradeErr != nil {
  152. return stacktrace.Propagate(canDowngradeErr, "")
  153. }
  154. if !canDowngrade {
  155. return stacktrace.Propagate(ente.ErrCannotDowngrade, "")
  156. }
  157. log.Info("Usage is good")
  158. }
  159. newSubscription := ente.Subscription{
  160. Storage: newPlan.Storage,
  161. ExpiryTime: purchase.ExpiryTimeMillis * 1000,
  162. ProductID: productID,
  163. PaymentProvider: ente.AppStore,
  164. OriginalTransactionID: originalTransactionID,
  165. Attributes: ente.SubscriptionAttributes{LatestVerificationData: transactionID},
  166. }
  167. err = c.BillingRepo.ReplaceSubscription(
  168. subscription.ID,
  169. newSubscription,
  170. )
  171. if err != nil {
  172. return stacktrace.Propagate(err, "")
  173. }
  174. err = c.AcknowledgeSubscription(productID, transactionID)
  175. if err != nil {
  176. return stacktrace.Propagate(err, "")
  177. }
  178. } else {
  179. err = c.BillingRepo.UpdateSubscriptionExpiryTime(
  180. subscription.ID, purchase.ExpiryTimeMillis*1000)
  181. if err != nil {
  182. return stacktrace.Propagate(err, "")
  183. }
  184. }
  185. return c.BillingRepo.LogPlayStorePush(subscription.UserID, notification, *purchase)
  186. }
  187. // GetVerifiedSubscription verifies and returns the verified subscription
  188. func (c *PlayStoreController) GetVerifiedSubscription(userID int64, productID string, verificationData string) (ente.Subscription, error) {
  189. var s ente.Subscription
  190. s.UserID = userID
  191. s.ProductID = productID
  192. s.PaymentProvider = ente.PlayStore
  193. s.Attributes.LatestVerificationData = verificationData
  194. plans := c.BillingPlansPerCountry["EU"] // Country code is irrelevant since Storage will be the same for a given subscriptionID
  195. response, err := c.verifySubscription(productID, verificationData)
  196. if err != nil {
  197. return ente.Subscription{}, stacktrace.Propagate(err, "")
  198. }
  199. for _, plan := range plans {
  200. if plan.AndroidID == productID {
  201. s.Storage = plan.Storage
  202. break
  203. }
  204. }
  205. s.OriginalTransactionID = verificationData
  206. s.ExpiryTime = response.ExpiryTimeMillis * 1000
  207. return s, nil
  208. }
  209. // AcknowledgeSubscription acknowledges a subscription to PlayStore
  210. func (c *PlayStoreController) AcknowledgeSubscription(subscriptionID string, token string) error {
  211. req := &androidpublisher.SubscriptionPurchasesAcknowledgeRequest{}
  212. context := context.Background()
  213. return c.PlayStoreClient.AcknowledgeSubscription(context, PlayStorePackageName, subscriptionID, token, req)
  214. }
  215. // CancelSubscription cancels a PlayStore subscription
  216. func (c *PlayStoreController) CancelSubscription(subscriptionID string, verificationData string) error {
  217. context := context.Background()
  218. return c.PlayStoreClient.CancelSubscription(context, PlayStorePackageName, subscriptionID, verificationData)
  219. }
  220. func (c *PlayStoreController) verifySubscription(subscriptionID string, verificationData string) (*androidpublisher.SubscriptionPurchase, error) {
  221. context := context.Background()
  222. return c.PlayStoreClient.VerifySubscription(context, PlayStorePackageName, subscriptionID, verificationData)
  223. }