-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContentView.swift
More file actions
571 lines (512 loc) · 16.7 KB
/
Copy pathContentView.swift
File metadata and controls
571 lines (512 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//
// ContentView.swift
// PlayolaPlayerExample
//
// Created by Brian D Keane on 12/29/24.
//
import PlayolaPlayer
import SwiftUI
// Main thread responsiveness monitor
class MainThreadMonitor: ObservableObject {
@Published var isResponsive = true
@Published var fps: Double = 60
private var displayLink: CADisplayLink?
private var lastUpdate: CFTimeInterval = 0
private var frameCount = 0
init() {
startMonitoring()
}
deinit {
displayLink?.invalidate()
}
private func startMonitoring() {
displayLink = CADisplayLink(target: self, selector: #selector(update))
displayLink?.add(to: .main, forMode: .common)
}
@objc private func update(displayLink: CADisplayLink) {
frameCount += 1
let elapsed = displayLink.timestamp - lastUpdate
if elapsed >= 1.0 {
fps = Double(frameCount) / elapsed
isResponsive = fps > 30 // Consider unresponsive if below 30 FPS
frameCount = 0
lastUpdate = displayLink.timestamp
}
}
}
struct ContentView: View {
@ObservedObject var player = PlayolaStationPlayer.shared
@StateObject private var threadMonitor = MainThreadMonitor()
@State private var showingStationPicker = false
@State private var showingScheduleViewer = false
@State private var selectedStationId: String = "9d79fd38-1940-4312-8fe8-3b9b50d49c6c"
var body: some View {
ZStack {
// Background gradient
LinearGradient(
gradient: Gradient(colors: [Color.black, Color.gray.opacity(0.3)]),
startPoint: .topLeading,
endPoint: .bottomTrailing
)
.ignoresSafeArea()
VStack(spacing: 30) {
// Header with thread monitor
HStack {
VStack(alignment: .leading, spacing: 5) {
Text("Main Thread Monitor")
.font(.headline)
.foregroundColor(.white)
Text("Watch this during loading")
.font(.caption)
.foregroundColor(.white.opacity(0.6))
}
Spacer()
ThreadResponsivenessIndicator(monitor: threadMonitor)
}
.padding()
Spacer()
// Main content
VStack(spacing: 25) {
// Album art placeholder with animation
ZStack {
RoundedRectangle(cornerRadius: 20)
.fill(Color.white.opacity(0.1))
.frame(width: 250, height: 250)
if player.isPlaying {
Image(systemName: "music.note")
.font(.system(size: 80))
.foregroundColor(.white.opacity(0.7))
.rotationEffect(.degrees(player.isPlaying ? 360 : 0))
.animation(
player.isPlaying
? Animation.linear(duration: 3).repeatForever(autoreverses: false) : .default,
value: player.isPlaying
)
} else {
Image(systemName: "radio")
.font(.system(size: 80))
.foregroundColor(.white.opacity(0.5))
}
}
// Now playing info
VStack(spacing: 10) {
if case .playing(let spin) = player.state {
Text(spin.audioBlock.title)
.font(.title2)
.fontWeight(.semibold)
.foregroundColor(.white)
.lineLimit(1)
Text(spin.audioBlock.artist)
.font(.headline)
.foregroundColor(.white.opacity(0.7))
.lineLimit(1)
} else if case .loading(let progress) = player.state {
VStack(spacing: 15) {
Text("Loading Station...")
.font(.headline)
.foregroundColor(.white.opacity(0.8))
ProgressView(value: progress)
.progressViewStyle(LinearProgressViewStyle(tint: .white))
.frame(width: 200)
Text("\(Int(progress * 100))%")
.font(.caption)
.foregroundColor(.white.opacity(0.6))
}
} else if case .paused(let spin) = player.state {
Text(spin.audioBlock.title)
.font(.title2)
.fontWeight(.semibold)
.foregroundColor(.white.opacity(0.7))
.lineLimit(1)
Text("Paused")
.font(.headline)
.foregroundColor(.white.opacity(0.5))
} else if case .error(let error) = player.state {
VStack(spacing: 8) {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundColor(.yellow)
Text(error.errorDescription ?? "Couldn't start the station")
.font(.subheadline)
.multilineTextAlignment(.center)
.foregroundColor(.white.opacity(0.8))
Text("Tap play to try again")
.font(.caption)
.foregroundColor(.white.opacity(0.6))
}
} else {
Text("Ready to Play")
.font(.title3)
.foregroundColor(.white.opacity(0.6))
}
}
.frame(height: 80)
// Offset playback controls
VStack(spacing: 20) {
// Time offset buttons
Text("Play from different times:")
.font(.caption)
.foregroundColor(.white.opacity(0.6))
HStack(spacing: 15) {
Button("5min ago") {
playWithOffset(-300) // 5 minutes ago
}
.buttonStyle(OffsetButtonStyle())
Button("1min ago") {
playWithOffset(-60) // 1 minute ago
}
.buttonStyle(OffsetButtonStyle())
Button("10sec ago") {
playWithOffset(-10) // 10 seconds ago
}
.buttonStyle(OffsetButtonStyle())
}
HStack(spacing: 15) {
Button("10sec future") {
playWithOffset(10) // 10 seconds from now
}
.buttonStyle(OffsetButtonStyle())
Button("1min future") {
playWithOffset(60) // 1 minute from now
}
.buttonStyle(OffsetButtonStyle())
Button("5min future") {
playWithOffset(300) // 5 minutes from now
}
.buttonStyle(OffsetButtonStyle())
}
}
// Main playback controls
HStack(spacing: 40) {
// Station picker
Button(
action: { showingStationPicker.toggle() },
label: {
Image(systemName: "list.bullet")
.font(.title2)
.foregroundColor(.white.opacity(0.8))
})
// Play/Stop button (current time)
Button(
action: { playOrPause() },
label: {
ZStack {
Circle()
.fill(buttonColor(for: player.state))
.frame(width: 80, height: 80)
Image(systemName: buttonIcon(for: player.state))
.font(.title)
.foregroundColor(.white)
.offset(x: shouldOffsetIcon(for: player.state) ? 3 : 0) // Center play icon
}
})
// Schedule viewer
Button(
action: { showingScheduleViewer.toggle() },
label: {
Image(systemName: "calendar")
.font(.title2)
.foregroundColor(.white.opacity(0.8))
})
}
}
Spacer()
}
}
.sheet(isPresented: $showingStationPicker) {
StationPickerView(selectedStationId: $selectedStationId)
}
.sheet(isPresented: $showingScheduleViewer) {
ScheduleViewer(selectedStationId: selectedStationId)
}
}
func playOrPause() {
Task {
switch await player.state {
case .loading:
// Cancel loading
await player.stop()
case .playing:
// Stop playing
await player.stop()
case .idle, .error, .paused:
// Start (or retry after a failed start / resume after a pause —
// play() re-fetches the schedule and re-syncs to now)
do {
try await player.play(stationId: selectedStationId)
} catch {
// Handle errors gracefully (including cancellation during loading).
// The terminal .error state is surfaced via player.state above.
print("Failed to start playback: \(error)")
}
}
}
}
func playWithOffset(_ offsetSeconds: TimeInterval) {
Task {
// Always stop current playback first
await player.stop()
// Calculate the target date
let atDate = Date().addingTimeInterval(offsetSeconds)
do {
try await player.play(
stationId: selectedStationId,
atDate: atDate
)
print("Started playback with offset: \(offsetSeconds) seconds (at: \(atDate))")
} catch {
print("Failed to start offset playback: \(error)")
}
}
}
}
// Thread responsiveness indicator
struct ThreadResponsivenessIndicator: View {
@ObservedObject var monitor: MainThreadMonitor
@State private var rotation: Double = 0
var body: some View {
VStack(spacing: 8) {
// Visual spinner that shows thread responsiveness
ZStack {
Circle()
.stroke(Color.white.opacity(0.2), lineWidth: 3)
.frame(width: 40, height: 40)
Circle()
.trim(from: 0, to: 0.7)
.stroke(
monitor.isResponsive ? Color.green : Color.red,
style: StrokeStyle(lineWidth: 3, lineCap: .round)
)
.frame(width: 40, height: 40)
.rotationEffect(.degrees(rotation))
.animation(
monitor.isResponsive
? Animation.linear(duration: 1).repeatForever(autoreverses: false)
: Animation.easeInOut(duration: 2).repeatForever(autoreverses: false),
value: rotation
)
Text("\(Int(monitor.fps))")
.font(.caption2)
.fontWeight(.bold)
.foregroundColor(.white)
}
VStack(spacing: 2) {
Text("\(Int(monitor.fps)) FPS")
.font(.caption)
.fontWeight(.semibold)
.foregroundColor(monitor.isResponsive ? .green : .red)
Text(monitor.isResponsive ? "Responsive" : "BLOCKED")
.font(.caption2)
.foregroundColor(monitor.isResponsive ? .white.opacity(0.6) : .red)
.fontWeight(monitor.isResponsive ? .regular : .bold)
}
}
.padding()
.background(
RoundedRectangle(cornerRadius: 12)
.fill(Color.black.opacity(0.5))
.overlay(
RoundedRectangle(cornerRadius: 12)
.stroke(
monitor.isResponsive ? Color.green.opacity(0.3) : Color.red.opacity(0.5), lineWidth: 1
)
)
)
.scaleEffect(monitor.isResponsive ? 1.0 : 1.1)
.animation(.easeInOut(duration: 0.3), value: monitor.isResponsive)
.onAppear {
rotation = 360
}
}
}
// API Models
struct StationListsResponse: Codable {
let stationLists: [StationList]
}
struct StationList: Codable {
let id: String
let title: String
let hidden: Bool?
let stations: [StationInfo]
}
struct StationInfo: Codable, Identifiable {
let id: String
let name: String
let playolaID: String?
let imageURL: String?
let desc: String?
let longDesc: String?
let type: String
}
// Station picker sheet
struct StationPickerView: View {
@Environment(\.dismiss) var dismiss
@Binding var selectedStationId: String
@State private var stations: [StationInfo] = []
@State private var isLoading = true
@State private var errorMessage: String?
var body: some View {
NavigationView {
ZStack {
if isLoading {
ProgressView("Loading stations...")
.padding()
} else if let error = errorMessage {
VStack(spacing: 16) {
Text("Failed to load stations")
.font(.headline)
Text(error)
.font(.caption)
.foregroundColor(.secondary)
Button("Retry") {
Task { await loadStations() }
}
}
.padding()
} else {
List(stations) { station in
Button(
action: {
Task {
do {
// Use playolaID for playola stations
let stationId = station.playolaID ?? station.id
selectedStationId = stationId
try await PlayolaStationPlayer.shared.play(stationId: stationId)
} catch {
print("Failed to start playback: \(error)")
}
}
dismiss()
},
label: {
HStack {
// Show image if available
if let imageURL = station.imageURL, let url = URL(string: imageURL) {
AsyncImage(url: url) { image in
image
.resizable()
.aspectRatio(contentMode: .fit)
} placeholder: {
Image(systemName: "radio")
.foregroundColor(.blue)
}
.frame(width: 40, height: 40)
.cornerRadius(8)
} else {
Image(systemName: "radio")
.foregroundColor(.blue)
.frame(width: 40, height: 40)
}
VStack(alignment: .leading, spacing: 4) {
Text(station.name)
.font(.headline)
if let desc = station.desc {
Text(desc)
.font(.caption)
.foregroundColor(.secondary)
}
}
Spacer()
}
.padding(.vertical, 4)
})
}
}
}
.navigationTitle("Select Station")
.navigationBarItems(trailing: Button("Done") { dismiss() })
.task {
await loadStations()
}
}
}
private func loadStations() async {
isLoading = true
errorMessage = nil
do {
let url = URL(string: "https://admin-api.playola.fm/v1/developer/station-lists")!
let (data, _) = try await URLSession.shared.data(from: url)
let response = try JSONDecoder().decode(StationListsResponse.self, from: data)
// Get stations from in_development_list and artist_list
var allStations: [StationInfo] = []
for list in response.stationLists {
if list.id == "in_development_list" || list.id == "artist_list" {
// Filter to only include playola type stations
let playolaStations = list.stations.filter { $0.type == "playola" }
allStations.append(contentsOf: playolaStations)
}
}
await MainActor.run {
self.stations = allStations
self.isLoading = false
}
} catch {
await MainActor.run {
self.errorMessage = error.localizedDescription
self.isLoading = false
}
}
}
}
func isLoading(_ state: PlayolaStationPlayer.State) -> Bool {
if case .loading = state {
return true
}
return false
}
func buttonColor(for state: PlayolaStationPlayer.State) -> Color {
switch state {
case .loading:
return Color.orange
case .playing:
return Color.red
case .idle:
return Color.green
case .error:
return Color.green
case .paused:
return Color.green
}
}
func buttonIcon(for state: PlayolaStationPlayer.State) -> String {
switch state {
case .loading:
return "stop.fill"
case .playing:
return "stop.fill"
case .idle:
return "play.fill"
case .error:
return "arrow.clockwise"
case .paused:
return "play.fill"
}
}
func shouldOffsetIcon(for state: PlayolaStationPlayer.State) -> Bool {
// Offset centers the play triangle; .paused shows play.fill like .idle.
switch state {
case .idle, .paused:
return true
default:
return false
}
}
// Custom button style for offset buttons
struct OffsetButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.caption)
.padding(.horizontal, 12)
.padding(.vertical, 8)
.background(
RoundedRectangle(cornerRadius: 16)
.fill(Color.white.opacity(configuration.isPressed ? 0.3 : 0.2))
)
.foregroundColor(.white)
.scaleEffect(configuration.isPressed ? 0.95 : 1.0)
.animation(.easeInOut(duration: 0.1), value: configuration.isPressed)
}
}
#Preview {
ContentView()
}