keys-for-all/docs/COMMUNITY_FEATURES.md
2025-07-22 18:27:21 -07:00

29 KiB

Keys for All - Community Sharing & Distribution Features

Community Philosophy

The Keys for All community features are built on the principle of "paying it forward" - creating a supportive ecosystem where users can help each other access VoiceUwu's advanced features. This system benefits everyone:

  • Users with means can support those without
  • Students and learners get access to professional tools
  • The community grows stronger through mutual support

Community Pool System

Overview

The Community Pool is a shared repository of donated license keys available to users who demonstrate genuine need. It operates on trust, verification, and fair distribution principles.

┌─────────────────────────────────────┐
│         Community Pool              │
├─────────────────────────────────────┤
│  Available Keys: 147                │
│  ├─ Level 1: 112                    │
│  └─ Level 2: 35                     │
│                                     │
│  [Donate Keys] [Request a Key]      │
└─────────────────────────────────────┘

Donation System

How to Donate

struct KeyDonationView: View {
    @State private var selectedKeys: Set<String> = []
    @State private var donationMessage = ""
    @State private var isAnonymous = false
    
    var body: some View {
        Form {
            Section("Select Keys to Donate") {
                ForEach(inventory.keys, id: \.self) { key in
                    HStack {
                        Image(systemName: selectedKeys.contains(key) ? "checkmark.circle.fill" : "circle")
                        Text(obfuscateKey(key))
                        Spacer()
                        Text(key.level.displayName)
                    }
                    .onTapGesture {
                        toggleSelection(key)
                    }
                }
            }
            
            Section("Dedication (Optional)") {
                TextEditor(text: $donationMessage)
                    .frame(height: 100)
                Toggle("Donate Anonymously", isOn: $isAnonymous)
            }
            
            Section {
                Button("Donate \(selectedKeys.count) Keys") {
                    donateToCommunity()
                }
                .disabled(selectedKeys.isEmpty)
            }
        }
    }
}

Donation Recognition

  • Public Recognition: Donors can choose to be recognized in the community feed
  • Dedication Messages: Add inspiring messages to encourage recipients
  • Impact Tracking: See how many users your donations have helped
  • Badges: Special recognition for frequent donors

Request System

Eligibility Categories

  1. Students

    • Verification: .edu email address
    • Automatic approval for verified institutions
    • One key per academic year
  2. Open Source Contributors

    • Verification: Active GitHub profile
    • Contribution history review
    • Priority for maintainers
  3. Financial Hardship

    • Honor system based
    • Brief explanation required
    • Community review process
  4. Educational Organizations

    • Bulk requests for classrooms
    • Institution verification
    • Volume based on class size

Request Process

class CommunityRequestManager {
    enum RequestCategory {
        case student(email: String)
        case openSource(githubUsername: String)
        case financialHardship(explanation: String)
        case educational(institution: String, studentCount: Int)
    }
    
    struct KeyRequest {
        let id: UUID
        let category: RequestCategory
        let requestedLevel: LicenseLevel
        let timestamp: Date
        let deviceID: String
        let status: RequestStatus
    }
    
    enum RequestStatus {
        case pending
        case approved
        case denied(reason: String)
        case fulfilled
    }
    
    func submitRequest(_ request: KeyRequest) async throws {
        // Validate eligibility
        try await validateEligibility(request)
        
        // Check request limits
        try await checkRequestLimits(request.deviceID)
        
        // Submit for review
        try await queueForReview(request)
        
        // Send confirmation
        notifyRequestReceived(request)
    }
    
    private func validateEligibility(_ request: KeyRequest) async throws {
        switch request.category {
        case .student(let email):
            guard email.hasSuffix(".edu") else {
                throw RequestError.invalidStudentEmail
            }
            
        case .openSource(let username):
            let contributions = try await fetchGitHubContributions(username)
            guard contributions.count >= 10 else {
                throw RequestError.insufficientContributions
            }
            
        case .educational(let institution, let count):
            guard count >= 10 else {
                throw RequestError.minimumStudentCount
            }
            try await verifyInstitution(institution)
            
        case .financialHardship:
            // Honor system - no verification required
            break
        }
    }
}

Fair Distribution Algorithm

class FairDistributionSystem {
    private let distributionQueue = DistributionQueue()
    
    struct DistributionCriteria {
        let waitTime: TimeInterval
        let category: RequestCategory
        let previousRequests: Int
        let communityContributions: Int
    }
    
    func processDistribution() async {
        let availableKeys = await fetchAvailableKeys()
        let pendingRequests = await fetchPendingRequests()
        
        // Sort requests by priority
        let prioritizedRequests = prioritizeRequests(
            pendingRequests,
            using: calculatePriority
        )
        
        // Distribute keys fairly
        for request in prioritizedRequests {
            guard let key = availableKeys.first(where: { 
                $0.level >= request.requestedLevel 
            }) else {
                break // No more suitable keys
            }
            
            await distributeKey(key, to: request)
            availableKeys.removeAll { $0 == key }
        }
    }
    
    private func calculatePriority(_ criteria: DistributionCriteria) -> Int {
        var priority = 0
        
        // Category weights
        switch criteria.category {
        case .student: priority += 30
        case .openSource: priority += 40
        case .educational: priority += 50
        case .financialHardship: priority += 35
        }
        
        // Wait time bonus (1 point per day)
        priority += Int(criteria.waitTime / 86400)
        
        // First-time requester bonus
        if criteria.previousRequests == 0 {
            priority += 20
        }
        
        // Community contribution bonus
        priority += criteria.communityContributions * 5
        
        return priority
    }
}

Key Sharing Features

Direct Sharing Methods

1. Message/Email Sharing

struct ShareKeyView: View {
    let key: String
    @State private var shareMethod: ShareMethod = .message
    
    enum ShareMethod {
        case message, email, qrCode, copyLink
    }
    
    var shareContent: String {
        """
        🎁 I'm sharing a VoiceUwu Pro key with you!
        
        Your license key: \(key)
        
        To activate:
        1. Open VoiceUwu
        2. Go to Settings → Keys for All
        3. Tap "Have a Key?" and paste this code
        
        This unlocks:
        • Advanced voice monitoring
        • Enhanced haptic feedback
        • Multiple visualization themes
        • And more!
        
        Enjoy your upgraded VoiceUwu experience! 🎵
        """
    }
    
    var body: some View {
        VStack(spacing: 20) {
            // Share method selector
            Picker("Share Method", selection: $shareMethod) {
                Label("Message", systemImage: "message").tag(ShareMethod.message)
                Label("Email", systemImage: "envelope").tag(ShareMethod.email)
                Label("QR Code", systemImage: "qrcode").tag(ShareMethod.qrCode)
                Label("Copy Link", systemImage: "link").tag(ShareMethod.copyLink)
            }
            .pickerStyle(SegmentedPickerStyle())
            
            // Share action
            Button("Share Key") {
                shareKey()
            }
            .buttonStyle(PrimaryButtonStyle())
        }
    }
    
    func shareKey() {
        switch shareMethod {
        case .message:
            shareViaMessage()
        case .email:
            shareViaEmail()
        case .qrCode:
            showQRCode()
        case .copyLink:
            copyUniversalLink()
        }
        
        // Track sharing
        KeySharingTracker.shared.trackShare(
            key: key,
            method: shareMethod
        )
    }
}

2. QR Code Sharing

struct QRCodeGenerator {
    static func generate(for key: String) -> UIImage? {
        // Create deep link URL
        let deepLink = "voiceuwu://activate?key=\(key)"
        
        // Generate QR code
        let data = deepLink.data(using: .utf8)
        
        if let filter = CIFilter(name: "CIQRCodeGenerator") {
            filter.setValue(data, forKey: "inputMessage")
            filter.setValue("H", forKey: "inputCorrectionLevel")
            
            if let outputImage = filter.outputImage {
                // Scale up for better quality
                let transform = CGAffineTransform(scaleX: 10, y: 10)
                let scaledImage = outputImage.transformed(by: transform)
                
                // Add VoiceUwu branding
                return addBranding(to: scaledImage)
            }
        }
        
        return nil
    }
    
    static func addBranding(to qrImage: CIImage) -> UIImage? {
        let context = CIContext()
        guard let cgImage = context.createCGImage(qrImage, from: qrImage.extent) else {
            return nil
        }
        
        let size = CGSize(width: cgImage.width, height: cgImage.height + 100)
        UIGraphicsBeginImageContext(size)
        
        // Draw QR code
        UIImage(cgImage: cgImage).draw(in: CGRect(x: 0, y: 50, width: cgImage.width, height: cgImage.height))
        
        // Add text
        let text = "Scan to activate VoiceUwu Pro"
        let attributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 24, weight: .medium),
            .foregroundColor: UIColor.label
        ]
        
        let textSize = text.size(withAttributes: attributes)
        let textRect = CGRect(
            x: (size.width - textSize.width) / 2,
            y: 10,
            width: textSize.width,
            height: textSize.height
        )
        
        text.draw(in: textRect, withAttributes: attributes)
        
        let brandedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return brandedImage
    }
}
class UniversalLinkGenerator {
    static func generateActivationLink(for key: String) -> URL? {
        var components = URLComponents()
        components.scheme = "https"
        components.host = "voiceuwu.app"
        components.path = "/activate"
        components.queryItems = [
            URLQueryItem(name: "key", value: key),
            URLQueryItem(name: "source", value: "share")
        ]
        
        return components.url
    }
    
    static func handleUniversalLink(_ url: URL) -> Bool {
        guard url.host == "voiceuwu.app",
              url.path == "/activate",
              let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
              let key = components.queryItems?.first(where: { $0.name == "key" })?.value else {
            return false
        }
        
        // Validate and activate key
        Task {
            do {
                try await VULicenseManager.shared.activate(key: key)
                showSuccessNotification()
            } catch {
                showErrorAlert(error)
            }
        }
        
        return true
    }
}

Bulk Distribution System

Organization Dashboard

struct BulkDistributionDashboard: View {
    @StateObject private var distributionManager = BulkDistributionManager()
    @State private var selectedPack: BulkPack?
    
    var body: some View {
        ScrollView {
            VStack(spacing: 20) {
                // Overview cards
                HStack(spacing: 15) {
                    StatCard(
                        title: "Total Keys",
                        value: "\(distributionManager.totalKeys)",
                        icon: "key.fill"
                    )
                    
                    StatCard(
                        title: "Distributed",
                        value: "\(distributionManager.distributedKeys)",
                        icon: "paperplane.fill"
                    )
                    
                    StatCard(
                        title: "Activated",
                        value: "\(distributionManager.activatedKeys)",
                        icon: "checkmark.circle.fill"
                    )
                }
                
                // Distribution methods
                Section("Distribution Methods") {
                    DistributionMethodCard(
                        title: "Email Blast",
                        description: "Send keys to multiple recipients",
                        icon: "envelope.fill",
                        action: showEmailDistribution
                    )
                    
                    DistributionMethodCard(
                        title: "CSV Export",
                        description: "Export keys for manual distribution",
                        icon: "doc.text.fill",
                        action: exportToCSV
                    )
                    
                    DistributionMethodCard(
                        title: "QR Sheet",
                        description: "Generate printable QR codes",
                        icon: "qrcode",
                        action: generateQRSheet
                    )
                    
                    DistributionMethodCard(
                        title: "API Access",
                        description: "Programmatic distribution",
                        icon: "chevron.left.forwardslash.chevron.right",
                        action: showAPISettings
                    )
                }
                
                // Recent activity
                Section("Recent Activity") {
                    ForEach(distributionManager.recentActivity) { activity in
                        ActivityRow(activity: activity)
                    }
                }
            }
            .padding()
        }
        .navigationTitle("Bulk Distribution")
    }
}

Email Distribution

class EmailDistributionService {
    struct EmailCampaign {
        let recipients: [String]
        let subject: String
        let template: EmailTemplate
        let keys: [String]
        let trackingEnabled: Bool
    }
    
    enum EmailTemplate {
        case welcome
        case classroom
        case organization
        case custom(String)
        
        var content: String {
            switch self {
            case .welcome:
                return """
                Welcome to VoiceUwu Pro!
                
                You've been given access to VoiceUwu's professional features.
                
                Your personal license key: {{KEY}}
                
                Getting Started:
                1. Download VoiceUwu from the App Store
                2. Open Settings → Keys for All
                3. Enter your license key
                
                Happy voice training!
                """
                
            case .classroom:
                return """
                Dear Student,
                
                Your instructor has provided you with a VoiceUwu Pro license
                for use in your voice training course.
                
                License Key: {{KEY}}
                Course: {{COURSE_NAME}}
                
                Please activate your key before the first class.
                
                Activation Instructions:
                [Detailed steps...]
                """
                
            case .organization:
                return """
                {{ORGANIZATION}} VoiceUwu License
                
                Your organization has provided you with a professional
                VoiceUwu license.
                
                License Details:
                - Key: {{KEY}}
                - Level: {{LEVEL}}
                - Support: {{SUPPORT_EMAIL}}
                
                [Activation instructions...]
                """
                
            case .custom(let content):
                return content
            }
        }
    }
    
    func sendCampaign(_ campaign: EmailCampaign) async throws {
        // Validate recipients
        let validRecipients = campaign.recipients.filter { isValidEmail($0) }
        
        // Assign keys to recipients
        let assignments = zip(validRecipients, campaign.keys)
        
        // Send emails in batches
        for batch in assignments.chunked(into: 50) {
            try await sendBatch(batch, using: campaign.template)
            
            // Rate limiting
            try await Task.sleep(nanoseconds: 1_000_000_000) // 1 second
        }
        
        // Track distribution
        if campaign.trackingEnabled {
            await trackCampaign(campaign)
        }
    }
}

CSV Export

struct CSVExporter {
    static func exportKeys(_ keys: [BulkKey]) -> Data {
        var csv = "Key,Level,Status,Distributed To,Activated Date\n"
        
        for key in keys {
            csv += "\(key.value),"
            csv += "\(key.level.rawValue),"
            csv += "\(key.status),"
            csv += "\(key.distributedTo ?? ""),"
            csv += "\(key.activatedDate?.iso8601 ?? "")\n"
        }
        
        return csv.data(using: .utf8) ?? Data()
    }
    
    static func generateDistributionReport(_ distributions: [Distribution]) -> Data {
        var csv = "Date,Recipient,Key Level,Method,Status\n"
        
        for dist in distributions {
            csv += "\(dist.date.iso8601),"
            csv += "\(dist.recipient),"
            csv += "\(dist.keyLevel),"
            csv += "\(dist.method),"
            csv += "\(dist.status)\n"
        }
        
        return csv.data(using: .utf8) ?? Data()
    }
}

API Integration

class DistributionAPI {
    struct APICredentials {
        let organizationID: String
        let apiKey: String
        let webhookURL: URL?
    }
    
    // API Endpoints
    enum Endpoint {
        case generateKey(level: LicenseLevel)
        case distributeKey(key: String, to: String)
        case checkStatus(key: String)
        case listKeys(filter: KeyFilter?)
        case revokeKey(key: String)
    }
    
    // API Client
    class Client {
        private let credentials: APICredentials
        private let session = URLSession.shared
        
        func generateKey(level: LicenseLevel) async throws -> String {
            let request = buildRequest(for: .generateKey(level: level))
            let (data, _) = try await session.data(for: request)
            
            let response = try JSONDecoder().decode(KeyResponse.self, from: data)
            return response.key
        }
        
        func distributeKey(_ key: String, to recipient: String) async throws {
            let request = buildRequest(for: .distributeKey(key: key, to: recipient))
            _ = try await session.data(for: request)
            
            // Send webhook notification if configured
            if let webhookURL = credentials.webhookURL {
                await sendWebhook(
                    to: webhookURL,
                    event: .keyDistributed(key: key, recipient: recipient)
                )
            }
        }
    }
}

// Usage example
extension DistributionAPI {
    static func example() async throws {
        let api = DistributionAPI.Client(
            credentials: APICredentials(
                organizationID: "org_123",
                apiKey: "sk_live_...",
                webhookURL: URL(string: "https://example.com/webhook")
            )
        )
        
        // Generate a new key
        let key = try await api.generateKey(level: .level1)
        
        // Distribute to user
        try await api.distributeKey(key, to: "user@example.com")
    }
}

Community Engagement Features

Leaderboards and Recognition

struct CommunityLeaderboard: View {
    @StateObject private var leaderboard = LeaderboardManager()
    
    var body: some View {
        List {
            Section("Top Contributors This Month") {
                ForEach(leaderboard.topContributors) { contributor in
                    HStack {
                        Text("\(contributor.rank)")
                            .font(.headline)
                            .frame(width: 30)
                        
                        VStack(alignment: .leading) {
                            Text(contributor.displayName)
                                .font(.headline)
                            Text("\(contributor.keysdonated) keys donated")
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                        
                        Spacer()
                        
                        Image(systemName: contributor.badge.icon)
                            .foregroundColor(contributor.badge.color)
                    }
                }
            }
            
            Section("Community Impact") {
                StatRow(title: "Total Keys Donated", value: "\(leaderboard.totalDonated)")
                StatRow(title: "Students Helped", value: "\(leaderboard.studentsHelped)")
                StatRow(title: "Countries Reached", value: "\(leaderboard.countriesReached)")
            }
        }
        .navigationTitle("Community")
    }
}

Community Stories

struct CommunityStoriesView: View {
    @StateObject private var stories = CommunityStoriesManager()
    
    var body: some View {
        ScrollView {
            VStack(spacing: 20) {
                ForEach(stories.featured) { story in
                    StoryCard(story: story)
                }
            }
            .padding()
        }
    }
}

struct StoryCard: View {
    let story: CommunityStory
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            // Header
            HStack {
                Image(systemName: story.category.icon)
                    .foregroundColor(story.category.color)
                Text(story.category.title)
                    .font(.caption)
                    .textCase(.uppercase)
                Spacer()
                Text(story.date, style: .date)
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            
            // Content
            Text(story.title)
                .font(.headline)
            
            Text(story.content)
                .font(.body)
                .lineLimit(4)
                .foregroundColor(.secondary)
            
            // Engagement
            HStack {
                Button(action: { likeStory(story) }) {
                    Label("\(story.likes)", systemImage: "heart.fill")
                        .font(.caption)
                }
                
                Button(action: { shareStory(story) }) {
                    Label("Share", systemImage: "square.and.arrow.up")
                        .font(.caption)
                }
                
                Spacer()
                
                if story.keysInspired > 0 {
                    Label("\(story.keysInspired) keys donated", systemImage: "key.fill")
                        .font(.caption)
                        .foregroundColor(.green)
                }
            }
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(12)
        .shadow(radius: 2)
    }
}

Gamification Elements

struct CommunityBadges {
    enum Badge: String, CaseIterable {
        case firstDonation = "First Key Donated"
        case helping_hand = "Helping Hand (5 keys)"
        case community_hero = "Community Hero (25 keys)"
        case legendary_supporter = "Legendary Supporter (100 keys)"
        case student_champion = "Student Champion"
        case educator_ally = "Educator Ally"
        case global_contributor = "Global Contributor"
        
        var requirements: String {
            switch self {
            case .firstDonation: return "Donate your first key"
            case .helping_hand: return "Donate 5 keys total"
            case .community_hero: return "Donate 25 keys total"
            case .legendary_supporter: return "Donate 100 keys total"
            case .student_champion: return "Help 10 students"
            case .educator_ally: return "Support 3 educational institutions"
            case .global_contributor: return "Keys activated in 5+ countries"
            }
        }
        
        var icon: String {
            switch self {
            case .firstDonation: return "star.fill"
            case .helping_hand: return "hand.raised.fill"
            case .community_hero: return "person.3.fill"
            case .legendary_supporter: return "crown.fill"
            case .student_champion: return "graduationcap.fill"
            case .educator_ally: return "books.vertical.fill"
            case .global_contributor: return "globe.americas.fill"
            }
        }
    }
}

Privacy and Trust

Anonymous Donation Options

struct AnonymousDonation {
    static func donate(keys: [String], message: String?) async throws {
        // Hash donor information for privacy
        let donorHash = generateAnonymousHash()
        
        // Strip identifying information
        let sanitizedMessage = sanitizeMessage(message)
        
        // Submit donation
        try await CommunityPoolService.shared.donate(
            keys: keys,
            donorID: donorHash,
            message: sanitizedMessage,
            isAnonymous: true
        )
    }
    
    private static func generateAnonymousHash() -> String {
        let deviceID = UIDevice.current.identifierForVendor?.uuidString ?? ""
        let timestamp = Date().timeIntervalSince1970
        let combined = "\(deviceID)\(timestamp)"
        
        return SHA256.hash(data: Data(combined.utf8))
            .compactMap { String(format: "%02x", $0) }
            .joined()
            .prefix(8)
            .uppercased()
    }
}

Trust Indicators

struct TrustBadges: View {
    let user: CommunityUser
    
    var body: some View {
        HStack(spacing: 8) {
            if user.isVerifiedStudent {
                TrustBadge(
                    icon: "checkmark.seal.fill",
                    text: "Verified Student",
                    color: .blue
                )
            }
            
            if user.totalDonations > 10 {
                TrustBadge(
                    icon: "heart.circle.fill",
                    text: "Active Donor",
                    color: .pink
                )
            }
            
            if user.accountAge > 365 {
                TrustBadge(
                    icon: "clock.badge.checkmark.fill",
                    text: "Long-time User",
                    color: .purple
                )
            }
        }
    }
}

Success Metrics

Community Health Dashboard

struct CommunityHealthMetrics {
    let donationRate: Double // Keys donated per week
    let activationRate: Double // % of donated keys activated
    let averageTimeToActivation: TimeInterval
    let geographicDiversity: Int // Number of countries
    let studentImpact: Int // Students helped
    let returnDonorRate: Double // % who donate again
    
    var healthScore: Double {
        // Weighted calculation of community health
        let weights = [
            donationRate * 0.2,
            activationRate * 0.3,
            (1.0 / averageTimeToActivation) * 0.1,
            Double(geographicDiversity) / 100.0 * 0.2,
            Double(studentImpact) / 1000.0 * 0.1,
            returnDonorRate * 0.1
        ]
        
        return weights.reduce(0, +).clamped(to: 0...1) * 100
    }
}

This comprehensive community feature set creates a thriving ecosystem where users support each other, organizations can efficiently distribute licenses, and everyone benefits from the collective generosity of the VoiceUwu community.