Damus Purple initial Proof-of-Concept support

This commit includes various code changes necessary to get a basic proof of concept of the feature working.

This is NOT a full working feature yet, only a preliminary prototype/PoC. It includes:
- [X] Basic Storekit configuration
- [X] Basic purchase mechanism
- [X] Basic layout and copywriting
- [X] Basic design
- [X] Manage button (To help user cancel their subscription)
- [X] Thank you confirmation + special welcome view
- [X] Star badge on profile (by checking the Damus Purple API)
- [X] Connection to Damus purple API for fetching account info, registering for an account and sending over the App Store receipt data

The feature sits behind a feature flag which is OFF by default (it can be turned ON via Settings --> Developer settings --> Enable experimental Purple API and restarting the app)

Testing
---------

PASS

Device: iPhone 15 Pro simulator
iOS: 17.0.1
Damus: This commit
damus-api: 59ce44a92cff1c1aaed9886f9befbd5f1053821d
Server: Ubuntu 22.04 (VM)
Setup:
1. On the server, delete the `mdb` database files to start from scratch
2. In iOS, reinstall the app if necessary to make sure there are no in-app purchases
3. Enable subscriptions support via developer settings with localhost test mode and restart app
4. Start server with mock parameters (Run `npm run dev`)

Steps:
1. Open top bar and click on "Purple"
2. Purple screen should appear and show both benefits and the purchase options. PASS
3. Click on "monthly". An Apple screen to confirm purchase should appear. PASS
4. Welcome screen with animation should appear. PASS
5. Click continue and restart app (Due to known issue tracked at https://github.com/damus-io/damus/issues/1814)
6. Post something
7. Gold star should appear beside your name
8. Look at the server logs. There should be some requests to create the account (POST), to send the receipt (POST), and to get account status
9. Go to purple view. There should be some information about the subscription, as well as a "manage" button. PASS
10. Click on "manage" button. An iOS sheet should appear allow the user to unsubscribe or manage their subscription to Damus Purple.

Feature flag testing
--------------------

PASS

Preconditions: Continue from above test
Steps:
1. Disable Damus Purple experiment support on developer settings. Restart the app.
2. Check your post. There should be no star beside your profile name. PASS
3. Check side menu. There should be no "Damus Purple" option. PASS
4. Check server logs. There should be no new requests being done to the server. PASS

Closes: https://github.com/damus-io/damus/issues/1422
This commit is contained in:
Daniel D’Aquino
2023-03-22 07:24:34 -06:00
committed by William Casarin
parent f7e407e030
commit 4703ed80a7
35 changed files with 1170 additions and 19 deletions

View File

@@ -87,7 +87,6 @@ struct LoginView: View {
}
if let p = parsed {
Button(action: {
Task {
do {

View File

@@ -208,6 +208,10 @@ struct NoteContentView: View {
}
func load(force_artifacts: Bool = false) {
if case .loading = damus_state.events.get_cache_data(event.id).artifacts_model.state {
return
}
// always reload artifacts on load
let plan = get_preload_plan(evcache: damus_state.events, ev: event, our_keypair: damus_state.keypair, settings: damus_state.settings)

View File

@@ -10,12 +10,13 @@ import SwiftUI
/// Profile Name used when displaying an event in the timeline
@MainActor
struct EventProfileName: View {
let damus_state: DamusState
var damus_state: DamusState
let pubkey: Pubkey
@State var display_name: DisplayName?
@State var nip05: NIP05?
@State var donation: Int?
@State var is_purple_user: Bool?
let size: EventViewKind
@@ -25,6 +26,7 @@ struct EventProfileName: View {
self.size = size
let donation = damus.ndb.lookup_profile(pubkey).map({ p in p?.profile?.damus_donation }).value
self._donation = State(wrappedValue: donation)
is_purple_user = nil
}
var friend_type: FriendType? {
@@ -47,7 +49,12 @@ struct EventProfileName: View {
return profile.reactions == false
}
var supporter: Int? {
func supporter_percentage() -> Int? {
if damus_state.settings.enable_experimental_purple_api,
is_purple_user == true {
return 100
}
guard let donation, donation > 0
else {
return nil
@@ -92,7 +99,7 @@ struct EventProfileName: View {
.frame(width: 14, height: 14)
}
if let supporter {
if let supporter = self.supporter_percentage() {
SupporterBadge(percent: supporter)
}
}
@@ -119,6 +126,13 @@ struct EventProfileName: View {
donation = profile.damus_donation
}
}
.onAppear(perform: {
Task {
if damus_state.settings.enable_experimental_purple_api {
is_purple_user = await damus_state.purple.is_profile_subscribed_to_purple(pubkey: self.pubkey) ?? false
}
}
})
}
}

View File

@@ -0,0 +1,428 @@
//
// DamusPurpleView.swift
// damus
//
// Created by William Casarin on 2023-03-21.
//
import SwiftUI
import StoreKit
fileprivate let damus_products = ["purpleyearly","purple"]
enum ProductState {
case loading
case loaded([Product])
case failed
var products: [Product]? {
switch self {
case .loading:
return nil
case .loaded(let ps):
return ps
case .failed:
return nil
}
}
}
func non_discounted_price(_ product: Product) -> String {
return (product.price * 1.1984569224).formatted(product.priceFormatStyle)
}
enum DamusPurpleType: String {
case yearly = "purpleyearly"
case monthly = "purple"
}
struct PurchasedProduct {
let tx: StoreKit.Transaction
let product: Product
}
struct DamusPurpleView: View {
let purple_api: DamusPurple
let keypair: Keypair
@State var products: ProductState
@State var purchased: PurchasedProduct? = nil
@State var selection: DamusPurpleType = .yearly
@State var show_welcome_sheet: Bool = false
@State var show_manage_subscriptions = false
@Environment(\.dismiss) var dismiss
init(purple: DamusPurple, keypair: Keypair) {
self._products = State(wrappedValue: .loading)
self.purple_api = purple
self.keypair = keypair
}
var body: some View {
ZStack {
Rectangle()
.background(.black)
ScrollView {
MainContent
.padding(.top, 75)
.background(content: {
ZStack {
Image("purple-blue-gradient-1")
.offset(CGSize(width: 300.0, height: -0.0))
Image("purple-blue-gradient-1")
.offset(CGSize(width: 300.0, height: -0.0))
}
})
}
}
.navigationBarTitleDisplayMode(.inline)
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: BackNav())
.onReceive(handle_notify(.switched_timeline)) { _ in
dismiss()
}
.onAppear {
notify(.display_tabbar(false))
}
.onDisappear {
notify(.display_tabbar(true))
}
.task {
await load_products()
}
.ignoresSafeArea(.all)
.sheet(isPresented: $show_welcome_sheet, content: {
DamusPurpleWelcomeView()
})
.manageSubscriptionsSheet(isPresented: $show_manage_subscriptions)
}
func handle_transactions(products: [Product]) async {
for await update in StoreKit.Transaction.updates {
switch update {
case .verified(let tx):
let prod = products.filter({ prod in tx.productID == prod.id }).first
if let prod,
let expiration = tx.expirationDate,
Date.now < expiration
{
self.purchased = PurchasedProduct(tx: tx, product: prod)
break
}
case .unverified:
continue
}
}
}
func load_products() async {
do {
let products = try await Product.products(for: damus_products)
self.products = .loaded(products)
await handle_transactions(products: products)
print("loaded products", products)
} catch {
self.products = .failed
print("Failed to fetch products: \(error.localizedDescription)")
}
}
func IconOnBox(_ name: String) -> some View {
ZStack {
RoundedRectangle(cornerRadius: 20.0)
.background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 20.0))
.frame(width: 80, height: 80)
.overlay(
RoundedRectangle(cornerRadius: 20)
.stroke(LinearGradient(
colors: [DamusColors.pink, .white.opacity(0), .white.opacity(0.5), .white.opacity(0)],
startPoint: .topLeading,
endPoint: .bottomTrailing), lineWidth: 1)
)
Image(name)
.resizable()
.frame(width: 50, height: 50)
.foregroundColor(.white)
}
}
func Icon(_ name: String) -> some View {
Image(name)
.resizable()
.frame(width: 50, height: 50)
.foregroundColor(.white)
}
func Title(_ txt: String) -> some View {
Text(txt)
.font(.title3)
.bold()
.foregroundColor(.white)
.padding(.bottom, 3)
}
func Subtitle(_ txt: String) -> some View {
Text(txt)
.foregroundColor(.white.opacity(0.65))
}
var ProductLoadError: some View {
Text("Ah dang there was an error loading subscription information from the AppStore. Please try again later :(")
.foregroundColor(.white)
}
var SaveText: Text {
Text("Save 14%")
.font(.callout)
.italic()
.foregroundColor(DamusColors.green)
}
func subscribe(_ product: Product) async throws {
let result = try await product.purchase()
switch result {
case .success(.verified(let tx)):
print("success \(tx.debugDescription)")
show_welcome_sheet = true
case .success(.unverified(let tx, let res)):
print("success unverified \(tx.debugDescription) \(res.localizedDescription)")
show_welcome_sheet = true
case .pending:
break
case .userCancelled:
break
@unknown default:
break
}
switch result {
case .success:
self.purple_api.starred_profiles_cache[keypair.pubkey] = nil
Task {
await self.purple_api.send_receipt()
}
default:
break
}
}
var product: Product? {
return self.products.products?.filter({
prod in prod.id == selection.rawValue
}).first
}
func price_description(product: Product) -> some View {
if product.id == "purpleyearly" {
return (
AnyView(
HStack(spacing: 10) {
Text("Anually")
Spacer()
Text(verbatim: non_discounted_price(product)).strikethrough().foregroundColor(DamusColors.white.opacity(0.5))
Text(verbatim: product.displayPrice).fontWeight(.bold)
}
)
)
} else {
return (
AnyView(
HStack(spacing: 10) {
Text("Monthly")
Spacer()
Text(verbatim: product.displayPrice).fontWeight(.bold)
}
)
)
}
}
func ProductsView(_ products: [Product]) -> some View {
VStack(spacing: 10) {
Text("Save 20% off on an annual subscription")
.font(.callout.bold())
.foregroundColor(.white)
ForEach(products) { product in
Button(action: {
Task { @MainActor in
do {
try await subscribe(product)
} catch {
print(error.localizedDescription)
}
}
}, label: {
price_description(product: product)
})
.buttonStyle(GradientButtonStyle())
}
}
.padding(.horizontal, 20)
}
func PurchasedView(_ purchased: PurchasedProduct) -> some View {
VStack(spacing: 10) {
Text("Purchased!")
.font(.title2)
.foregroundColor(.white)
price_description(product: purchased.product)
.foregroundColor(.white)
.opacity(0.65)
.frame(width: 200)
Text("Purchased on")
.font(.title2)
.foregroundColor(.white)
Text(format_date(UInt32(purchased.tx.purchaseDate.timeIntervalSince1970)))
.foregroundColor(.white)
.opacity(0.65)
if let expiry = purchased.tx.expirationDate {
Text("Renews on")
.font(.title2)
.foregroundColor(.white)
Text(format_date(UInt32(expiry.timeIntervalSince1970)))
.foregroundColor(.white)
.opacity(0.65)
}
Button(action: {
show_manage_subscriptions = true
}, label: {
Text("Manage")
})
.buttonStyle(GradientButtonStyle())
}
}
var ProductStateView: some View {
Group {
switch self.products {
case .failed:
ProductLoadError
case .loaded(let products):
if let purchased {
PurchasedView(purchased)
} else {
ProductsView(products)
}
case .loading:
ProgressView()
.progressViewStyle(.circular)
}
}
}
var MainContent: some View {
VStack {
HStack(spacing: 20) {
Image("damus-dark-logo")
.resizable()
.frame(width: 60, height: 60)
.clipShape(RoundedRectangle(cornerRadius: 15.0))
.overlay(
RoundedRectangle(cornerRadius: 15)
.stroke(LinearGradient(
colors: [DamusColors.lighterPink.opacity(0.8), .white.opacity(0), DamusColors.deepPurple.opacity(0.6)],
startPoint: .topLeading,
endPoint: .bottomTrailing), lineWidth: 1)
)
.shadow(radius: 5)
VStack(alignment: .leading) {
Text("Purple")
.font(.system(size: 60.0).weight(.bold))
.foregroundStyle(
LinearGradient(
colors: [DamusColors.lighterPink, DamusColors.deepPurple],
startPoint: .bottomLeading,
endPoint: .topTrailing
)
)
.foregroundColor(.white)
.tracking(-2)
}
}
.padding(.bottom, 30)
VStack(alignment: .leading, spacing: 30) {
Subtitle("Help us stay independent in our mission for Freedom tech with our Purple subscription, and look cool doing it!")
.multilineTextAlignment(.center)
HStack(spacing: 20) {
IconOnBox("heart.fill")
VStack(alignment: .leading) {
Title("Help Build The Future")
Subtitle("Support Damus development to help build the future of decentralized communication on the web.")
}
}
HStack(spacing: 20) {
IconOnBox("ai-3-stars.fill")
VStack(alignment: .leading) {
Title("Exclusive features")
.padding(.bottom, -3)
HStack(spacing: 3) {
Image("calendar")
.resizable()
.frame(width: 15, height: 15)
Text("Coming soon")
.font(.caption)
.bold()
}
.foregroundColor(DamusColors.pink)
.padding(.vertical, 3)
.padding(.horizontal, 8)
.background(DamusColors.lightBackgroundPink)
.cornerRadius(30.0)
Subtitle("Be the first to access upcoming premium features: Automatic translations, longer note storage, and more")
.padding(.top, 3)
}
}
HStack(spacing: 20) {
IconOnBox("badge")
VStack(alignment: .leading) {
Title("Supporter Badge")
Subtitle("Get a special badge on your profile to show everyone your contribution to Freedom tech")
}
}
}
.padding([.trailing, .leading], 30)
.padding(.bottom, 20)
VStack(alignment: .center) {
ProductStateView
}
.padding([.top], 20)
Spacer()
}
}
}
struct DamusPurpleView_Previews: PreviewProvider {
static var previews: some View {
/*
DamusPurpleView(products: [
DamusProduct(name: "Yearly", id: "purpleyearly", price: Decimal(69.99)),
DamusProduct(name: "Monthly", id: "purple", price: Decimal(6.99)),
])
*/
DamusPurpleView(purple: test_damus_state.purple, keypair: test_damus_state.keypair)
}
}

View File

@@ -0,0 +1,127 @@
//
// DamusPurpleWelcomeView.swift
// damus
//
// Created by Daniel DAquino on 2023-12-04.
//
import Foundation
import SwiftUI
fileprivate extension Animation {
static func content() -> Animation {
Animation.easeInOut(duration: 1).delay(3)
}
}
struct DamusPurpleWelcomeView: View {
@Environment(\.dismiss) var dismiss
@State var start = false
var body: some View {
VStack {
Image("damus-dark-logo")
.resizable()
.frame(width: 50, height: 50)
.clipShape(RoundedRectangle(cornerRadius: 10.0))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(LinearGradient(
colors: [DamusColors.lighterPink.opacity(0.8), .white.opacity(0), DamusColors.deepPurple.opacity(0.6)],
startPoint: .topLeading,
endPoint: .bottomTrailing), lineWidth: 1)
)
.shadow(radius: 5)
.padding(20)
.opacity(start ? 1.0 : 0.0)
.animation(.content(), value: start)
Text("Welcome to Purple")
.font(.largeTitle)
.fontWeight(.bold)
.foregroundStyle(
LinearGradient(
colors: [.black, .black, DamusColors.pink, DamusColors.lighterPink],
startPoint: start ? .init(x: -3, y: 4) : .bottomLeading,
endPoint: start ? .topTrailing : .init(x: 3, y: -4)
)
)
.opacity(start ? 1.0 : 0.0)
.animation(Animation.easeInOut(duration: 3).delay(0), value: start)
Image(systemName: "star.fill")
.resizable()
.frame(width: 96, height: 90)
.foregroundStyle(
LinearGradient(
colors: [.black, DamusColors.purple, .white, .white],
startPoint: start ? .init(x: -1, y: 1.5) : .bottomLeading,
endPoint: start ? .topTrailing : .init(x: 10, y: -11)
)
)
.animation(Animation.snappy(duration: 3).delay(1), value: start)
.shadow(
color: start ? DamusColors.lightBackgroundPink : DamusColors.purple.opacity(0.3),
radius: start ? 30 : 10
)
.animation(Animation.snappy(duration: 3).delay(0), value: start)
.scaleEffect(x: start ? 1 : 3, y: start ? 1 : 3)
.opacity(start ? 1.0 : 0.0)
.animation(Animation.snappy(duration: 2).delay(0), value: start)
Text("Thank you very much for signing up for Damus\u{00A0}Purple. Your contribution helps us continue our fight for a more Open and Free\u{00A0}internet.\n\nYou will also get access to premium features, and a star badge on your profile.\n\nEnjoy!")
.lineSpacing(5)
.multilineTextAlignment(.center)
.foregroundStyle(.white.opacity(0.8))
.padding(.horizontal, 20)
.padding(.top, 50)
.padding(.bottom, 20)
.opacity(start ? 1.0 : 0.0)
.animation(.content(), value: start)
Button(action: {
dismiss()
}, label: {
HStack {
Spacer()
Text("Continue")
Spacer()
}
})
.padding(.horizontal, 30)
.buttonStyle(GradientButtonStyle())
.opacity(start ? 1.0 : 0.0)
.animation(Animation.easeInOut(duration: 2).delay(5), value: start)
}
.background(content: {
ZStack {
Rectangle()
.background(.black)
Image("purple-blue-gradient-1")
.offset(CGSize(width: 300.0, height: -0.0))
.opacity(start ? 1.0 : 0.2)
Image("stars-bg")
.resizable(resizingMode: .stretch)
.frame(width: 500, height: 500)
.offset(x: -100, y: 50)
.scaleEffect(start ? 1 : 1.1)
.animation(Animation.easeOut(duration: 3).delay(0), value: start)
Image("purple-blue-gradient-1")
.offset(CGSize(width: 300.0, height: -0.0))
.opacity(start ? 1.0 : 0.2)
}
})
.onAppear(perform: {
withAnimation(.easeOut(duration: 6), {
start = true
})
})
}
}
struct DamusPurpleWelcomeView_Previews: PreviewProvider {
static var previews: some View {
DamusPurpleWelcomeView()
}
}

View File

@@ -24,6 +24,12 @@ struct DeveloperSettingsView: View {
Toggle(NSLocalizedString("Send device token to localhost", comment: "Developer mode setting to send device token metadata to a local server instead of the damus.io server."), isOn: $settings.send_device_token_to_localhost)
.toggleStyle(.switch)
Toggle("Enable experimental Purple API support", isOn: $settings.enable_experimental_purple_api)
.toggleStyle(.switch)
Toggle("Purple API localhost test mode", isOn: $settings.purple_api_local_test_mode)
.toggleStyle(.switch)
}
}
}

View File

@@ -39,6 +39,7 @@ struct SideMenuView: View {
.onTapGesture {
isSidebarVisible.toggle()
}
content
}
}
@@ -51,17 +52,18 @@ struct SideMenuView: View {
NavigationLink(value: Route.Wallet(wallet: damus_state.wallet)) {
navLabel(title: NSLocalizedString("Wallet", comment: "Sidebar menu label for Wallet view."), img: "wallet")
/*
HStack {
Image("wallet")
.tint(DamusColors.adaptableBlack)
}
Text(NSLocalizedString("wallet", comment: "Sidebar menu label for Wallet view."))
.font(.title2)
.foregroundColor(textColor())
.frame(maxWidth: .infinity, alignment: .leading)
.dynamicTypeSize(.xSmall)
}*/
if damus_state.settings.enable_experimental_purple_api {
NavigationLink(destination: DamusPurpleView(purple: damus_state.purple, keypair: damus_state.keypair)) {
HStack(spacing: 13) {
Image("nostr-hashtag")
Text("Purple")
.foregroundColor(DamusColors.purple)
.font(.title2.weight(.bold))
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
NavigationLink(value: Route.MuteList(users: get_mutelist_users(damus_state.contacts.mutelist))) {