Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Piperly/App/PiperlyApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import SwiftUI
struct PiperlyApp: App {
@StateObject private var bookStore = BookStore()
private let ttsEngine = TTSEngine()
@AppStorage("hasCompletedVoiceSetup") private var hasCompletedVoiceSetup = false
@State private var showVoiceSetup = false
@Environment(\.scenePhase) private var scenePhase

Expand All @@ -31,13 +30,14 @@ struct PiperlyApp: App {
.task {
await bookStore.importSampleBooksIfNeeded()
}
.onAppear {
if !hasCompletedVoiceSetup {
.onChange(of: bookStore.selectedProfileID, initial: true) {
if !bookStore.activeProfile.hasCompletedVoiceSetup {
showVoiceSetup = true
}
}
.sheet(isPresented: $showVoiceSetup) {
VoiceSetupSheet(ttsEngine: ttsEngine)
.environmentObject(bookStore)
}
.onChange(of: scenePhase) { _, newPhase in
if newPhase != .active {
Expand Down
144 changes: 139 additions & 5 deletions Piperly/Models/ReaderProfile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,24 +20,158 @@ struct ReaderProfile: Identifiable, Codable, Hashable, Sendable {
static let defaultName = "Reader"
static let defaultAvatarSymbol = "person.crop.circle.fill"
static let defaultColorName = "accent"
static let defaultVoiceIdentifier = ""
static let defaultSpeechRate = 0.45
static let defaultFontSize = 22.0
static let defaultReaderTheme = "piperly"

enum NicknameValidationError: Error, Equatable, LocalizedError {
case empty
case tooLong
case containsWhitespace
case containsDigits
case containsAccountIdentifier

var errorDescription: String? {
switch self {
case .empty:
"Enter a nickname."
case .tooLong:
"Keep nicknames under 20 characters."
case .containsWhitespace:
"Use one nickname, not a full name."
case .containsDigits:
"Do not enter birthdays or ages."
case .containsAccountIdentifier:
"Do not enter email addresses or Apple IDs."
}
}
}

let id: UUID
var name: String
private(set) var name: String
var avatarSymbol: String
var colorName: String
let createdAt: Date
var voiceIdentifier: String
var speechRate: Double
var fontSize: Double
var readerTheme: String
var hasCompletedVoiceSetup: Bool

init(
id: UUID = UUID(),
name: String = Self.defaultName,
name: String,
avatarSymbol: String = Self.defaultAvatarSymbol,
colorName: String = Self.defaultColorName,
createdAt: Date = .now
) {
createdAt: Date = .now,
voiceIdentifier: String = Self.defaultVoiceIdentifier,
speechRate: Double = Self.defaultSpeechRate,
fontSize: Double = Self.defaultFontSize,
readerTheme: String = Self.defaultReaderTheme,
hasCompletedVoiceSetup: Bool = false
) throws {
self.id = id
self.name = name
self.name = try Self.validatedNickname(name)
self.avatarSymbol = avatarSymbol
self.colorName = colorName
self.createdAt = createdAt
self.voiceIdentifier = voiceIdentifier
self.speechRate = speechRate
self.fontSize = fontSize
self.readerTheme = readerTheme
self.hasCompletedVoiceSetup = hasCompletedVoiceSetup
}

init() {
id = UUID()
name = Self.defaultName
avatarSymbol = Self.defaultAvatarSymbol
colorName = Self.defaultColorName
createdAt = .now
voiceIdentifier = Self.defaultVoiceIdentifier
speechRate = Self.defaultSpeechRate
fontSize = Self.defaultFontSize
readerTheme = Self.defaultReaderTheme
hasCompletedVoiceSetup = false
}

mutating func updateNickname(_ name: String) throws {
self.name = try Self.validatedNickname(name)
}

static func nicknameValidationError(for name: String) -> NicknameValidationError? {
do {
_ = try validatedNickname(name)
return nil
} catch let error as NicknameValidationError {
return error
} catch {
return .empty
}
}

/// Non-throwing sanitizer for decode: coerces a legacy or invalid persisted
/// nickname into a valid one instead of throwing, so a name that was valid
/// under an older rule (e.g. contained a space or digit) can't wipe the
/// whole profiles array on upgrade. Validation still throws at create/update.
private static func sanitizedNickname(_ name: String) -> String {
if let valid = try? validatedNickname(name) { return valid }
var stripped = name.trimmingCharacters(in: .whitespacesAndNewlines)
stripped.removeAll { $0.isWhitespace || $0.isNumber || $0 == "@" || $0 == "." }
let trimmed = String(stripped.prefix(20))
return (try? validatedNickname(trimmed)) ?? defaultName
}

private static func validatedNickname(_ name: String) throws -> String {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty {
throw NicknameValidationError.empty
}
if trimmed.count > 20 {
throw NicknameValidationError.tooLong
}
if trimmed.rangeOfCharacter(from: .whitespacesAndNewlines) != nil {
throw NicknameValidationError.containsWhitespace
}
if trimmed.rangeOfCharacter(from: .decimalDigits) != nil {
throw NicknameValidationError.containsDigits
}
if trimmed.contains("@") || trimmed.contains(".") {
throw NicknameValidationError.containsAccountIdentifier
}
return trimmed
}

private enum CodingKeys: String, CodingKey {
case id
case name
case avatarSymbol
case colorName
case createdAt
case voiceIdentifier
case speechRate
case fontSize
case readerTheme
case hasCompletedVoiceSetup
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(UUID.self, forKey: .id)
name = Self.sanitizedNickname(try container.decode(String.self, forKey: .name))
avatarSymbol = try container.decode(String.self, forKey: .avatarSymbol)
colorName = try container.decode(String.self, forKey: .colorName)
createdAt = try container.decode(Date.self, forKey: .createdAt)
voiceIdentifier = try container.decodeIfPresent(String.self, forKey: .voiceIdentifier)
?? Self.defaultVoiceIdentifier
speechRate = try container.decodeIfPresent(Double.self, forKey: .speechRate)
?? Self.defaultSpeechRate
fontSize = try container.decodeIfPresent(Double.self, forKey: .fontSize)
?? Self.defaultFontSize
readerTheme = try container.decodeIfPresent(String.self, forKey: .readerTheme)
?? Self.defaultReaderTheme
hasCompletedVoiceSetup = try container.decodeIfPresent(Bool.self, forKey: .hasCompletedVoiceSetup)
?? false
}
}
81 changes: 68 additions & 13 deletions Piperly/Services/BookStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class BookStore: ObservableObject {

private let documentsURL: URL
private let coversURL: URL
private let userDefaults: UserDefaults
private let booksKey = "piperly_books"
private let profilesKey = "piperly_reader_profiles"
private let selectedProfileKey = "piperly_selected_profile_id"
Expand All @@ -49,7 +50,7 @@ class BookStore: ObservableObject {
/// (legacy/corrupt) instead of dropping the whole array. Flags total loss
/// so `persistArray` won't clobber the bytes.
private func loadArray<T: Decodable>(_ type: T.Type, forKey key: String) -> [T]? {
guard let data = UserDefaults.standard.data(forKey: key) else { return nil }
guard let data = userDefaults.data(forKey: key) else { return nil }
if let decoded = try? JSONDecoder().decode([T].self, from: data) {
corruptedStoreKeys.remove(key)
return decoded
Expand Down Expand Up @@ -79,14 +80,15 @@ class BookStore: ObservableObject {
if values.isEmpty && corruptedStoreKeys.contains(key) { return }
if !values.isEmpty { corruptedStoreKeys.remove(key) }
if let data = try? JSONEncoder().encode(values) {
UserDefaults.standard.set(data, forKey: key)
userDefaults.set(data, forKey: key)
}
}

init() {
init(userDefaults: UserDefaults = .standard) {
let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
self.documentsURL = docs.appendingPathComponent("Books", isDirectory: true)
self.coversURL = docs.appendingPathComponent("Covers", isDirectory: true)
self.userDefaults = userDefaults

try? FileManager.default.createDirectory(at: documentsURL, withIntermediateDirectories: true)
try? FileManager.default.createDirectory(at: coversURL, withIntermediateDirectories: true)
Expand Down Expand Up @@ -129,7 +131,7 @@ class BookStore: ObservableObject {
}

func loadSelectedProfileID() {
guard let rawValue = UserDefaults.standard.string(forKey: selectedProfileKey),
guard let rawValue = userDefaults.string(forKey: selectedProfileKey),
let id = UUID(uuidString: rawValue) else {
return
}
Expand All @@ -138,7 +140,7 @@ class BookStore: ObservableObject {

func saveSelectedProfileID() {
guard let selectedProfileID else { return }
UserDefaults.standard.set(selectedProfileID.uuidString, forKey: selectedProfileKey)
userDefaults.set(selectedProfileID.uuidString, forKey: selectedProfileKey)
}

/// Guarantees there is always at least one profile and a valid selection.
Expand Down Expand Up @@ -174,8 +176,8 @@ class BookStore: ObservableObject {
}

@discardableResult
func addProfile(name: String, avatarSymbol: String, colorName: String) -> ReaderProfile {
let profile = ReaderProfile(
func addProfile(name: String, avatarSymbol: String, colorName: String) throws -> ReaderProfile {
let profile = try ReaderProfile(
name: Self.sanitizedProfileName(name),
avatarSymbol: avatarSymbol,
colorName: colorName
Expand All @@ -187,9 +189,9 @@ class BookStore: ObservableObject {
return profile
}

func updateProfile(_ profileID: UUID, name: String, avatarSymbol: String, colorName: String) {
func updateProfile(_ profileID: UUID, name: String, avatarSymbol: String, colorName: String) throws {
guard let index = profiles.firstIndex(where: { $0.id == profileID }) else { return }
profiles[index].name = Self.sanitizedProfileName(name)
try profiles[index].updateNickname(Self.sanitizedProfileName(name))
profiles[index].avatarSymbol = avatarSymbol
profiles[index].colorName = colorName
saveProfiles()
Expand All @@ -215,8 +217,61 @@ class BookStore: ObservableObject {
}

private static func sanitizedProfileName(_ name: String) -> String {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? ReaderProfile.defaultName : trimmed
name.trimmingCharacters(in: .whitespacesAndNewlines)
}

func updateActiveProfile(_ update: (inout ReaderProfile) -> Void) {
guard let index = profiles.firstIndex(where: { $0.id == activeProfileID }) else { return }
update(&profiles[index])
saveProfiles()
}

var activeVoiceIdentifier: String {
activeProfile.voiceIdentifier
}

var activeSpeechRate: Double {
activeProfile.speechRate
}

var activeFontSize: Double {
activeProfile.fontSize
}

var activeReaderTheme: ReaderTheme {
ReaderTheme(rawValue: activeProfile.readerTheme) ?? .piperly
}

var activeVoiceIdentifierBinding: Binding<String> {
Binding(
get: { self.activeVoiceIdentifier },
set: { value in self.updateActiveProfile { $0.voiceIdentifier = value } }
)
}

var activeSpeechRateBinding: Binding<Double> {
Binding(
get: { self.activeSpeechRate },
set: { value in self.updateActiveProfile { $0.speechRate = value } }
)
}

var activeFontSizeBinding: Binding<Double> {
Binding(
get: { self.activeFontSize },
set: { value in self.updateActiveProfile { $0.fontSize = value } }
)
}

var activeReaderThemeBinding: Binding<String> {
Binding(
get: { self.activeProfile.readerTheme },
set: { value in self.updateActiveProfile { $0.readerTheme = value } }
)
}

func completeVoiceSetup() {
updateActiveProfile { $0.hasCompletedVoiceSetup = true }
}

func loadReadingStates() {
Expand Down Expand Up @@ -450,15 +505,15 @@ class BookStore: ObservableObject {
// MARK: - Samples

func importSampleBooksIfNeeded() async {
let hasImportedSamples = UserDefaults.standard.bool(forKey: "piperly_samples_imported")
let hasImportedSamples = userDefaults.bool(forKey: "piperly_samples_imported")
guard !hasImportedSamples else { return }

let sampleFiles = Bundle.main.urls(forResourcesWithExtension: "epub", subdirectory: nil) ?? []
for url in sampleFiles {
_ = try? await importBundledBook(from: url)
}

UserDefaults.standard.set(true, forKey: "piperly_samples_imported")
userDefaults.set(true, forKey: "piperly_samples_imported")
}

private func importBundledBook(from bundleURL: URL) async throws -> Book {
Expand Down
12 changes: 4 additions & 8 deletions Piperly/Views/Reader/ReaderView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,6 @@ struct ReaderView: View {
@State private var showWordBubble = false
@State private var isNewWord = false
@State private var showingWordList = false
@AppStorage("selectedVoiceIdentifier") private var selectedVoiceIdentifier: String = ""
@AppStorage("speechRate") private var speechRate: Double = 0.45
@AppStorage("readerFontSize") private var fontSize: Double = 22
@AppStorage("readerTheme") private var selectedTheme: String = ReaderTheme.piperly.rawValue
@StateObject private var wordTapCoordinator = WordTapCoordinator()
@State private var navigator: EPUBNavigatorViewController?
@State private var currentLocator: Locator?
Expand Down Expand Up @@ -263,11 +259,11 @@ struct ReaderView: View {
}

private var theme: ReaderTheme {
ReaderTheme(rawValue: selectedTheme) ?? .piperly
bookStore.activeReaderTheme
}

private var readerPreferences: EPUBPreferences {
theme.epubPreferences(fontSize: fontSize)
theme.epubPreferences(fontSize: bookStore.activeFontSize)
}

private var restoredLocator: Locator? {
Expand All @@ -286,8 +282,8 @@ struct ReaderView: View {
}
ttsEngine.speak(
word: word,
voiceIdentifier: selectedVoiceIdentifier,
rate: Float(speechRate)
voiceIdentifier: bookStore.activeVoiceIdentifier,
rate: Float(bookStore.activeSpeechRate)
)
}

Expand Down
Loading
Loading