This repository has been archived by the owner on Oct 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ViewController.swift
1443 lines (1390 loc) · 65.2 KB
/
ViewController.swift
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ViewController.swift
// Radio Automne
//
// Created by Aydar Nasibullin on 30.09.2020.
// Copyright © 2020-2021 Fetch Development. All rights reserved.
//
import Cocoa
import Alamofire
import AVFoundation
import MediaPlayer
class View: NSView {
override func performKeyEquivalent(with event: NSEvent) -> Bool {
return true
}
}
class ViewController: NSViewController{
//*********************************************************************
//SYSTEM
//*********************************************************************
static var systemStatus = AutomneProperties.SystemStatus.standby
static var playbackControllerState = AutomneProperties.PlaybackControllerState.none
static let VERSION_NAME = "Samoyed"
//*********************************************************************
//OUTLETS
//*********************************************************************
@IBOutlet var bar: NSTouchBar!
@IBOutlet weak var terminalImage: NSImageView!
@IBOutlet weak var standbyButton: NSButton!
@IBOutlet weak var box: NSImageView!
@IBOutlet weak var mainLabel: NSTextField!
@IBOutlet weak var TBLabel: NSTextField!
@IBOutlet weak var frequencyControllerLabel: NSTextField!
@IBOutlet weak var volumeKnob: NSImageView!
@IBOutlet weak var statusLight: NSImageView!
@IBOutlet weak var TBStatusLight: NSImageView!
@IBOutlet weak var terminal: NSTextField!
@IBOutlet weak var frequencyControllerLight_stream: NSImageView!
@IBOutlet weak var frequencyControllerLight_tune: NSImageView!
@IBOutlet weak var frequencyControllerLight_new: NSImageView!
@IBOutlet weak var frequencyControllerLight_memory: NSImageView!
@IBOutlet weak var glitchStripe: NSImageView!
@IBOutlet weak var playbackControllerLight_play: NSImageView!
@IBOutlet weak var playbackControllerLight_sleep: NSImageView!
@IBOutlet weak var playbackControllerLight_stream: NSImageView!
@IBOutlet weak var playbackControllerLight_pause: NSImageView!
@IBOutlet weak var playbackControllerLight_deepwave: NSImageView!
@IBOutlet weak var playbackControllerLight_loading: NSImageView!
@IBOutlet weak var playbackControllerLight_error: NSImageView!
var allLights: [NSImageView] = []
//*********************************************************************
//ACTIONS
//*********************************************************************
///Frequency Controller
@IBAction func freqControlUpClicked(_ sender: Any) {
if ViewController.systemStatus != .busy && ViewController.systemStatus != .standby {
let i = ViewController.selectedFrequencyIndex
if i < ViewController.retrievedFrequencies.count - 1 {
switchFrequency(to: ViewController.retrievedFrequencies[i + 1], index: i + 1)
}
}
}
@IBAction func freqControlDownClicked(_ sender: Any) {
if ViewController.systemStatus != .busy && ViewController.systemStatus != .standby {
let i = ViewController.selectedFrequencyIndex
if i > 0 {
switchFrequency(to: ViewController.retrievedFrequencies[i - 1], index: i - 1)
}
}
}
@IBAction func freqControlSetClicked(_ sender: Any) {
if ViewController.systemStatus != .busy && ViewController.systemStatus != .standby && ViewController.systemStatus != .error {
ViewController.player.pause()
ViewController.mainDisplayState = .frequency
let fr = ViewController.selectedFrequency!
if fr.isStream! {
self.startStream(frequency: fr)
} else {
self.retrieveTracks(frequency: fr)
}
}
}
///System
@IBAction func standbyClicked(_ sender: Any) {
if ViewController.systemStatus == .standby{
powerOn()
}
else if ViewController.systemStatus != .busy{
powerOff()
SFX.playSFX(sfx: .buttonClick)
}
}
///Playback Controller
@IBAction func pauseClicked(_ sender: Any) {
if ViewController.playbackControllerState == .playing {
pause()
}
}
@IBAction func playClicked(_ sender: Any) {
if ViewController.systemStatus == .ready ||
ViewController.playbackControllerState == .playing {
play(from: ViewController.playbackIndex, init: true)
}
else if ViewController.playbackControllerState == .paused {
resume()
}
else if ViewController.systemStatus == .unset {
tprint("Frequency not set")
}
}
@IBAction func setupClicked(_ sender: Any) {
if ViewController.systemStatus != .busy && ViewController.systemStatus != .standby
&& !ViewController.inMenu{
let els = [
SetupMenu.SetupMenuElement(
title: "Display artwork",
value: ViewController.defaults.integer(forKey: "artwork"),
bounds: (0,2),
isAction: false),
SetupMenu.SetupMenuElement(
title: "Appearance",
value: (ViewController.defaults.integer(forKey: "appearance") == 0 ? 1 : ViewController.defaults.integer(forKey: "appearance")),
bounds: (1,7),
isAction: false),
SetupMenu.SetupMenuElement(
title: "Quick boot",
value: ViewController.defaults.integer(forKey: "qboot"),
bounds: (0,1),
isAction: false),
SetupMenu.SetupMenuElement(
title: "Sleep timer",
value: 0,
bounds: (0,9),
isAction: false),
SetupMenu.SetupMenuElement(
title: "Server",
value: ViewController.defaults.integer(forKey: "server"),
bounds: (1,2),
isAction: false),
SetupMenu.SetupMenuElement(
title: "Verbose",
value: ViewController.defaults.integer(forKey: "log"),
bounds: (0,1),
isAction: false),
SetupMenu.SetupMenuElement(
title: "Narrator",
value: ViewController.defaults.integer(forKey: "narrator"),
bounds: (0,1),
isAction: false),
SetupMenu.SetupMenuElement(
title: "Deepwave Chance",
value: ViewController.defaults.integer(forKey: "deepwave_chance"),
bounds: (0,4),
isAction: false),
SetupMenu.SetupMenuElement(
title: "Deepwave Count",
value: ViewController.defaults.integer(forKey: "deepwave_count"),
bounds: (1,3),
isAction: false)]
ViewController.smenu = SetupMenu.get(for: els)
tclear(cache: true)
tprint(ViewController.smenu.getRaw(), raw: true, noBreak: true, noWipe: true)
ViewController.inMenu = true
}
else if ViewController.inMenu{
saveDefaults()
}
}
@IBAction func helpClicked(_ sender: Any) {
sendToGithub()
}
@IBAction func nextClicked(_ sender: Any) {
if ViewController.systemStatus == .active && (ViewController.setFrequency == nil || !(ViewController.setFrequency?.isStream ?? true)){
advance()
}
}
@IBAction func prevClicked(_ sender: Any) {
if ViewController.systemStatus == .active && (ViewController.setFrequency == nil || !(ViewController.setFrequency?.isStream ?? true)){
reverse()
}
}
@IBAction func shareClicked(_ sender: Any) {
if ViewController.systemStatus == .active && (ViewController.setFrequency == nil || !(ViewController.setFrequency?.isStream ?? true)){
NSWorkspace.shared.open(URL(string: ViewController.currentTrack!.permalink_url!)!)
}
}
@IBAction func diveClicked(_ sender: Any) {
if ViewController.systemStatus == .active && (ViewController.setFrequency == nil || !(ViewController.setFrequency?.isStream ?? true)){
initDeepwave(with: ViewController.currentTrack!)
}
}
//*********************************************************************
//VARS
//*********************************************************************
static var player : AVPlayer = AVPlayer()
static var smenu = SetupMenu(elements: [], selected: 0)
static var playableQueue: [Track] = []
static var playbackIndex = 0
static var selectedFrequency: Frequency? = nil
static var selectedFrequencyIndex = -1
static var setFrequencyIndex = -1
static var demandFrequencyID = ""
static var setFrequency: Frequency? = nil
static var retrievedFrequencies: [Frequency] = []
static var ticker: Timer!
static var mainDisplaySwitchTimer: Timer!
static var sleepTimer: Timer!
static var playerWaitingTimeoutTimer: Timer!
static var terminalImageLeftTicks = 0
static var terminalStripeLeftTicks = 0
static var terminalImagePlaylistServed = false
static var volumeKnobAngle: CGFloat = 0.0
static var savedVolume = -1
static var firstCall = true
static var mainDisplayState = MainDisplayState.song
static var inMenu = false
static var playlist: Playlist? = nil
static var TSBP = 0
static var terminalCache = ""
static var currentTrack: Track? = nil
static var deepWaveInitiator: Track? = nil
static var configFilePath: URL? = nil
//*********************************************************************
//CONSTS
//*********************************************************************
let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
static let defaults = UserDefaults.standard
static let controlCenter = MPRemoteCommandCenter.shared()
static let controlCenterInfo = MPNowPlayingInfoCenter.default()
let fetchLogo = "### ### ### ### # #\n# # # # # #\n## ### # # ###\n# # # # # #\n# ### # ### # #"
static let states = [MainDisplayState.frequency, MainDisplayState.song, MainDisplayState.artist, MainDisplayState.time]
static let streamStates = [MainDisplayState.frequency, MainDisplayState.song, MainDisplayState.time]
static let fm = FileManager.default
static let freqDemandPlaceholder = "ID: >"
//*********************************************************************
//FUNCTIONS
//*********************************************************************
override func viewDidAppear() {
super.viewDidAppear()
// MARK: This would be worth implementing in case i add Favourites in the future. Anyway it wont work now and is possibly iOS-only.
// ViewController.controlCenter.likeCommand.addTarget {_ in
// return .success
// }
// ViewController.controlCenter.likeCommand.isEnabled = true
ViewController.controlCenter.togglePlayPauseCommand.addTarget{_ in
if ViewController.playbackControllerState == .paused {
self.resume()
return .success
} else if ViewController.playbackControllerState == .playing {
self.pause()
return .success
} else {
return .commandFailed
}
}
ViewController.controlCenter.playCommand.addTarget {_ in
if ViewController.playbackControllerState == .paused {
self.resume()
ViewController.controlCenterInfo.nowPlayingInfo!["MPNowPlayingInfoPropertyElapsedPlaybackTime"] = ViewController.player.currentTime().seconds
return .success
} else if ViewController.playbackControllerState == .playing{
return .success
} else {
return .commandFailed
}
}
ViewController.controlCenter.pauseCommand.addTarget {_ in
if ViewController.playbackControllerState == .playing {
self.pause()
ViewController.controlCenterInfo.nowPlayingInfo!["MPNowPlayingInfoPropertyElapsedPlaybackTime"] = ViewController.player.currentTime().seconds
return .success
} else if ViewController.playbackControllerState == .paused{
return .success
} else {
return .commandFailed
}
}
ViewController.controlCenter.nextTrackCommand.addTarget {_ in
if ViewController.systemStatus == .active && (ViewController.setFrequency == nil || !(ViewController.setFrequency?.isStream ?? true)){
self.advance()
return .success
} else {
return .commandFailed
}
}
ViewController.controlCenter.previousTrackCommand.addTarget {_ in
if ViewController.systemStatus == .active && (ViewController.setFrequency == nil || !(ViewController.setFrequency?.isStream ?? true)){
self.reverse()
return .success
} else {
return .commandFailed
}
}
ViewController.controlCenter.seekForwardCommand.addTarget {_ in
return .commandFailed
}
ViewController.controlCenter.seekBackwardCommand.addTarget {_ in
return .commandFailed
}
ViewController.controlCenter.changePlaybackPositionCommand.addTarget {_ in
if ViewController.controlCenterInfo.nowPlayingInfo != nil {
ViewController.controlCenterInfo.nowPlayingInfo!["MPNowPlayingInfoPropertyElapsedPlaybackTime"] = ViewController.player.currentTime().seconds
}
return .commandFailed
}
// SFX.testVoices()
// Uncomment to reset user settings
//
// ViewController.defaults.set(0, forKey: "artwork")
// ViewController.defaults.set(0, forKey: "appearance")
// ViewController.defaults.set(0, forKey: "qboot")
// ViewController.defaults.set(0, forKey: "deepwave")
touchBar = bar
NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
self.myKeyDown(with: $0)
return $0
}
updateAppearance()
allLights = [frequencyControllerLight_new,
frequencyControllerLight_tune,
frequencyControllerLight_stream,
frequencyControllerLight_memory,
playbackControllerLight_play,
playbackControllerLight_pause,
playbackControllerLight_error,
playbackControllerLight_loading,
playbackControllerLight_sleep,
playbackControllerLight_deepwave,
playbackControllerLight_stream]
ViewController.configFilePath = FileManager().homeDirectoryForCurrentUser.appendingPathComponent("Music/Radio Automne")
if let a = ViewController.configFilePath {
if !ViewController.fm.fileExists(atPath: a.path) {
try? ViewController.fm.createDirectory(atPath: a.path, withIntermediateDirectories: true, attributes: nil)
let fp = a.appendingPathComponent("config.json")
let jsonData = try? JSONEncoder().encode(CustomFrequencies(frequencies: [Frequency(name: "", reliable: false, num: "", isNew: false, isStream: false, playlistID: "", streamURL: "", streamDescription: "")]))
ViewController.fm.createFile(atPath: fp.path, contents: jsonData, attributes: nil)
ViewController.configFilePath = fp
} else {
ViewController.configFilePath = a.appendingPathComponent("config.json")
}
}
if ViewController.defaults.integer(forKey: "appearance") == 0 {
ViewController.defaults.set(1, forKey: "appearance")
ViewController.defaults.set(1, forKey: "deepwave_count")
ViewController.defaults.set(2, forKey: "artwork")
}
if ViewController.defaults.integer(forKey: "server") == 0 {
ViewController.defaults.set(1, forKey: "server")
}
}
override var representedObject: Any? {
didSet{ }
}
///System
func updateAppearance() {
switch ViewController.defaults.integer(forKey: "appearance") {
case 0,1:
volumeKnob.image = NSImage.init(named: "VolumeKnob_1")
box.image = NSImage.init(named: "Box_1")
standbyButton.image = NSImage.init(named: "OnStandby_1")
case 2:
volumeKnob.image = NSImage.init(named: "VolumeKnob_1")
box.image = NSImage.init(named: "Box_2")
standbyButton.image = NSImage.init(named: "OnStandby_1")
case 3:
volumeKnob.image = NSImage.init(named: "VolumeKnob_3")
box.image = NSImage.init(named: "Box_3")
standbyButton.image = NSImage.init(named: "OnStandby_3")
case 4:
volumeKnob.image = NSImage.init(named: "VolumeKnob_3")
box.image = NSImage.init(named: "Box_4")
standbyButton.image = NSImage.init(named: "OnStandby_3")
case 5:
volumeKnob.image = NSImage.init(named: "VolumeKnob_3")
box.image = NSImage.init(named: "Box_5")
standbyButton.image = NSImage.init(named: "OnStandby_5")
case 6:
volumeKnob.image = NSImage.init(named: "VolumeKnob_6")
box.image = NSImage.init(named: "Box_6")
standbyButton.image = NSImage.init(named: "OnStandby_6")
case 7:
volumeKnob.image = NSImage.init(named: "VolumeKnob_1")
box.image = NSImage.init(named: "Box_7")
standbyButton.image = NSImage.init(named: "OnStandby_1")
default: ()
}
}
func myKeyDown(with event: NSEvent) {
super.keyDown(with: event)
hideImage()
if event.keyCode == 0x7E && ViewController.inMenu //DOWN
{
tclear()
ViewController.smenu = ViewController.smenu.downSel()
tprint(ViewController.smenu.getRaw(), raw: true, noBreak: true, noWipe: true)
}
else if event.keyCode == 0x7D && ViewController.inMenu //UP
{
tclear()
ViewController.smenu = ViewController.smenu.upSel()
tprint(ViewController.smenu.getRaw(), raw: true, noBreak: true, noWipe: true)
}
else if event.keyCode == 0x7C //RIGHT
{
if ViewController.inMenu {
tclear()
ViewController.smenu = ViewController.smenu.increment([])
tprint(ViewController.smenu.getRaw(), raw: true, noBreak: true, noWipe: true)
} else {
if ViewController.systemStatus == .active && (ViewController.setFrequency == nil || !(ViewController.setFrequency?.isStream ?? true)){
advance()
}
}
}
else if event.keyCode == 0x7B //LEFT
{
if ViewController.inMenu {
tclear()
ViewController.smenu = ViewController.smenu.decrement()
tprint(ViewController.smenu.getRaw(), raw: true, noBreak: true, noWipe: true)
} else {
if ViewController.systemStatus == .active && (ViewController.setFrequency == nil || !(ViewController.setFrequency?.isStream ?? true)){
reverse()
}
}
}
else if event.keyCode == 36 //RETURN
{
if ViewController.inMenu {
saveDefaults()
} else {
if ViewController.systemStatus == .standby{
powerOn()
} else if ViewController.systemStatus != .busy {
powerOff()
}
}
}
if event.keyCode == 49 { //SPACE
if ViewController.systemStatus == .ready{
play(from: ViewController.playbackIndex)
}
else if ViewController.playbackControllerState == .playing {
pause()
}
else if ViewController.playbackControllerState == .paused {
resume()
}
}
else if event.keyCode == 12 { //Q
exit(0)
}
else if event.keyCode == 14 { //E
if ViewController.TSBP < 14{
ViewController.TSBP += 1
} else if ViewController.playbackControllerState == .playing{
ViewController.TSBP = 0
tclear()
tprint(AutomneKeys.dedication, raw: true, noWipe: true)
}
}
else if event.keyCode == 0 && ViewController.systemStatus != .busy && ViewController.systemStatus != .standby{ //A
let i = ViewController.selectedFrequencyIndex
if i > 0 {
switchFrequency(to: ViewController.retrievedFrequencies[i - 1], index: i - 1)
}
}
else if event.keyCode == 2 && ViewController.systemStatus != .busy && ViewController.systemStatus != .standby{ //D
let i = ViewController.selectedFrequencyIndex
if i < ViewController.retrievedFrequencies.count - 1 {
switchFrequency(to: ViewController.retrievedFrequencies[i + 1], index: i + 1)
}
}
else if event.keyCode == 1 && ViewController.systemStatus != .busy && ViewController.systemStatus != .standby{ //S
ViewController.player.pause()
ViewController.mainDisplayState = .frequency
let fr = ViewController.selectedFrequency!
if fr.isStream! {
self.startStream(frequency: fr)
} else {
self.retrieveTracks(frequency: fr)
}
}
else {
guard ViewController.selectedFrequencyIndex == 0 else { return }
var k: Int? = nil
switch event.keyCode {
case 18...21:
k = Int(event.keyCode - 17)
case 19:
k = 2
case 20:
k = 3
case 21:
k = 4
case 23:
k = 5
case 22:
k = 6
case 26:
k = 7
case 28:
k = 8
case 25:
k = 9
case 29:
k = 0
case 51:
k = 51
// case let k:
// print(k)
default: ()
}
if let key = k {
if key == 51 {
ViewController.demandFrequencyID = String(ViewController.demandFrequencyID.dropLast())
} else {
ViewController.demandFrequencyID += String(key)
}
setFreqLabel(to: "ID: >\(ViewController.demandFrequencyID)")
}
}
}
func sendToGithub() {
NSWorkspace.shared.open(URL(string: "https://github.com/Lesterrry/Radio-Automne")!)
}
func saveDefaults() {
let log = ViewController.defaults.integer(forKey: "log") == 1
ViewController.defaults.set(ViewController.smenu.elements[0].value, forKey: "artwork")
ViewController.defaults.set(ViewController.smenu.elements[1].value, forKey: "appearance")
ViewController.defaults.set(ViewController.smenu.elements[2].value, forKey: "qboot")
ViewController.defaults.set(ViewController.smenu.elements[4].value, forKey: "server")
ViewController.defaults.set(ViewController.smenu.elements[5].value, forKey: "log")
ViewController.defaults.set(ViewController.smenu.elements[6].value, forKey: "narrator")
ViewController.defaults.set(ViewController.smenu.elements[7].value, forKey: "deepwave_chance")
ViewController.defaults.set(ViewController.smenu.elements[8].value, forKey: "deepwave_count")
ViewController.inMenu = false
trestore()
if log { tprint("Configuration saved") }
updateAppearance()
ViewController.sleepTimer?.invalidate()
if ViewController.smenu.elements[3].value != 0 && ViewController.systemStatus == .active{
ViewController.sleepTimer = Timer.scheduledTimer(
timeInterval: TimeInterval(ViewController.smenu.elements[3].value * 600),
target: self,
selector: #selector(self.sleep), userInfo: nil, repeats: false)
}
if ViewController.systemStatus == .active {
checkAndInvokeImage()
}
}
@objc func sleep() {
powerOff()
AutomneCore.notify(title: "🌌 Good night")
AutomneCore.systemSleep()
}
func powerOn() {
let log = ViewController.defaults.integer(forKey: "log") == 1
for light in allLights {
light.isHidden = false
}
tprint("AutomneOS \(ViewController.VERSION_NAME)", raw: true)
tprint(appVersion ?? "", raw: true)
glitchStripe.isHidden = false
setSystemStatus(to: AutomneProperties.SystemStatus.busy)
TBLabel.stringValue = "AutomneOS " + ViewController.VERSION_NAME
ViewController.ticker = Timer.scheduledTimer(
timeInterval: 1.0,
target: self,
selector: #selector(self.tick), userInfo: nil, repeats: true)
ViewController.mainDisplaySwitchTimer = Timer.scheduledTimer(
timeInterval: 3.5,
target: self,
selector: #selector(self.mainDisplayTick), userInfo: nil, repeats: true)
if ViewController.defaults.integer(forKey: "qboot") == 0{
SFX.playSFX(sfx: SFX.Effects.powerOn)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) {
for light in self.allLights {
light.isHidden = true
}
self.setPlaybackLabel(to: "Radio Automne")
self.tprint(log ? "Loading mainframe..." : "Booting...")
}
if log {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
self.tprint("SUCCESS")
self.tprint("Making leaves yellow...")
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 3.5) {
if log { self.tprint("SUCCESS") }
self.setFreqLabel(to: "Configuring...")
self.tprint("Configuring mod...")
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5.5) {
if log { self.tprint("SUCCESS") }
self.setFreqLabel(to: "Configured")
if log { self.tprint("Compiling 'Endless Autumn.scpt'...") }
}
DispatchQueue.main.asyncAfter(deadline: .now() + 8.35) {
self.tclear()
self.tprint(self.fetchLogo, raw: true, noBreak: true)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 12) {
self.retrieveFrequencies()
}
} else {
SFX.playSFX(sfx: SFX.Effects.buttonClick)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) {
for light in self.allLights {
light.isHidden = true
}
self.tprint("[QUICK BOOT]", raw: true)
self.retrieveFrequencies()
}
}
if appVersion != ViewController.defaults.string(forKey: "version"){
ViewController.defaults.set(appVersion, forKey: "version")
AutomneCore.systemSleepCheck()
}
}
func powerOff() {
ViewController.setFrequencyIndex = -1
ViewController.setFrequency = nil
ViewController.player = AVPlayer()
TBLabel.stringValue = ""
glitchStripe.isHidden = true
removeImage()
ViewController.sleepTimer?.invalidate()
setSystemStatus(to: .standby)
setPlaybackControllerState(to: .none)
setFreqLabel(to: "")
setPlaybackLabel(to: "")
ViewController.inMenu = false
for light in allLights{
light.isHidden = true
}
terminal.stringValue = ""
ViewController.inMenu = false
SFX.shutUp(speaker: true)
ViewController.ticker.invalidate()
ViewController.mainDisplaySwitchTimer.invalidate()
}
@objc func tick() {
let sv = ViewController.savedVolume
let vol = AutomneCore.getSystemVolume()
if vol != sv && !ViewController.firstCall{
self.rotate(
from: ViewController.volumeKnobAngle,
by: CGFloat(((abs(vol - ViewController.savedVolume)) / 6) * (sv - vol > 0 ? 1 : -1)), timeToRotate: 0.5)
}
else if ViewController.firstCall{
ViewController.firstCall = false
}
ViewController.savedVolume = vol
if ViewController.terminalImageLeftTicks == 0 && terminalImage.isHidden{
showImage()
} else if ViewController.terminalImageLeftTicks > 0 {
ViewController.terminalImageLeftTicks -= 1
}
if ViewController.terminalStripeLeftTicks == 0 {
stripe()
ViewController.terminalStripeLeftTicks = 15
} else if ViewController.terminalStripeLeftTicks > 0 {
ViewController.terminalStripeLeftTicks -= 1
}
if ViewController.playbackControllerState == .playing{
let b = playbackControllerLight_play.isHidden
if ViewController.player.reasonForWaitingToPlay != nil {
ViewController.player.playImmediately(atRate: 1.0)
playbackControllerLight_loading.isHidden = false
if ViewController.playerWaitingTimeoutTimer == nil
|| !ViewController.playerWaitingTimeoutTimer.isValid{
ViewController.playerWaitingTimeoutTimer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(self.playerWaitingTimeout), userInfo: nil, repeats: false)
}
} else {
ViewController.playerWaitingTimeoutTimer?.invalidate()
playbackControllerLight_loading.isHidden = true
playbackControllerLight_deepwave.isHidden = !(ViewController.currentTrack?.deepWave ?? false)
if ViewController.sleepTimer != nil && ViewController.sleepTimer.isValid {
playbackControllerLight_sleep.isHidden = false
}
else{
playbackControllerLight_sleep.isHidden = true
}
if ViewController.setFrequency != nil && ViewController.setFrequency!.isStream ?? true {
playbackControllerLight_stream.isHidden = false
} else {
playbackControllerLight_play.isHidden = !b
}
}
}
if ViewController.systemStatus == .active && ViewController.playbackControllerState != .error && ViewController.mainDisplayState == .time{
var stdv: String?
if ViewController.sleepTimer != nil && ViewController.sleepTimer.isValid{
let c = Int(floor(Date.init().distance(to: ViewController.sleepTimer.fireDate)))
stdv = String(c / 60) + ":" + String(c % 60)
}
let tail = (stdv == nil ? "" : (" Sleep: " + stdv!))
if ViewController.setFrequency != nil && (ViewController.setFrequency?.isStream)! {
self.setPlaybackLabel(to: "Live " + tail)
}
else {
let sec = Int(ViewController.player.currentTime().seconds)
let dur = (ViewController.currentTrack!.duration ?? 600000) / 1000
let val = dur - sec
let pSec = val % 60
let muzzle = " -" + String(val / 60) + ":"
let withers = (pSec < 10 ? ("0" + String(pSec)) : String(pSec))
self.setPlaybackLabel(to: muzzle + withers + tail)
}
}
}
func setSystemStatus(to: AutomneProperties.SystemStatus) {
ViewController.systemStatus = to
switch to {
case .active, .ready, .unset:
statusLight.image = NSImage.init(named: "StatusLight_ready")
TBStatusLight.image = NSImage.init(named: "StatusLight_ready")
case .error:
statusLight.image = NSImage.init(named: "StatusLight_error")
TBStatusLight.image = NSImage.init(named: "StatusLight_error")
setFreqLabel(to: "ERR")
setPlaybackLabel(to: "ERR")
AutomneCore.notify(title: "🆘 System error encountered")
default:
statusLight.image = NSImage.init(named: "StatusLight_" + to.rawValue)
TBStatusLight.image = NSImage.init(named: "StatusLight_" + to.rawValue)
}
}
///Volume knob
func rotate(from: CGFloat, by: CGFloat, timeToRotate: Double) {
CATransaction.begin()
CATransaction.setCompletionBlock({
ViewController.volumeKnobAngle = from + by
})
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = from
rotateAnimation.byValue = by
rotateAnimation.duration = timeToRotate
rotateAnimation.repeatCount = 1
rotateAnimation.fillMode = CAMediaTimingFillMode.both
rotateAnimation.isRemovedOnCompletion = false
volumeKnob.layer?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
volumeKnob.layer?.position = CGPoint(x: volumeKnob.frame.origin.x + volumeKnob.frame.width / 2,
y: volumeKnob.frame.origin.y + volumeKnob.frame.height / 2)
volumeKnob.layer?.add(rotateAnimation, forKey: nil)
CATransaction.commit()
}
///Playback Controller
@objc func playerWaitingTimeout() {
let r = ViewController.player.reasonForWaitingToPlay
if r != nil{
if AutomneAxioms.isConnectedToNetwork(){
AutomneCore.notify(title: "⚠️ Couldn't play")
tprint("WARN1: AVP_W, " + r!.rawValue)
tprint("Couldn't play")
if !(ViewController.setFrequency?.isStream ?? true) {
ViewController.player.cancelPendingPrerolls()
advance()
}
}
else {
tprint("ERR11: AVP_W, " + r!.rawValue)
tprint("Check connection")
ViewController.player = AVPlayer()
setPlaybackControllerState(to: .error)
}
}
}
func setPlaybackControllerState(to: AutomneProperties.PlaybackControllerState, isStream: Bool = false) {
switch to {
case .playing:
playbackControllerLight_pause.isHidden = true
playbackControllerLight_error.isHidden = true
ViewController.controlCenterInfo.playbackState = .playing
case .paused:
playbackControllerLight_play.isHidden = true
playbackControllerLight_pause.isHidden = false
playbackControllerLight_loading.isHidden = true
playbackControllerLight_error.isHidden = true
playbackControllerLight_deepwave.isHidden = true
ViewController.controlCenterInfo.playbackState = .paused
case .loading:
playbackControllerLight_play.isHidden = true
playbackControllerLight_pause.isHidden = true
playbackControllerLight_loading.isHidden = false
playbackControllerLight_error.isHidden = true
playbackControllerLight_deepwave.isHidden = true
case .error:
playbackControllerLight_play.isHidden = true
playbackControllerLight_pause.isHidden = true
playbackControllerLight_loading.isHidden = true
playbackControllerLight_error.isHidden = false
playbackControllerLight_deepwave.isHidden = true
AutomneCore.notify(title: "🆘 Playback error encountered")
ViewController.controlCenterInfo.playbackState = .stopped
ViewController.controlCenterInfo.nowPlayingInfo = .none
removeImage()
case .none:
playbackControllerLight_play.isHidden = true
playbackControllerLight_pause.isHidden = true
playbackControllerLight_loading.isHidden = true
playbackControllerLight_error.isHidden = true
playbackControllerLight_deepwave.isHidden = true
ViewController.controlCenterInfo.playbackState = .stopped
ViewController.controlCenterInfo.nowPlayingInfo = .none
}
ViewController.playbackControllerState = to
playbackControllerLight_stream.isHidden = !isStream
}
///Player
@objc func playerDidFinishPlaying(sender: Notification) {
advance()
}
func advance() {
setSystemStatus(to: .busy)
if ViewController.playbackIndex < ViewController.playableQueue.count - 1{
play(from: ViewController.playbackIndex + 1)
} else {
ViewController.playableQueue.shuffle()
tprint("Stream was mixed (1)")
play(from: 0)
}
}
func reverse() {
setSystemStatus(to: .busy)
if ViewController.playbackIndex > 0 {
play(from: ViewController.playbackIndex - 1)
} else if ViewController.currentTrack != nil {
ViewController.playableQueue.shuffle()
tprint("Stream was mixed (2)")
play(from: 0)
}
}
func play(from: Int = 0, init: Bool = false) {
var url: URL
let isStream = (ViewController.setFrequency?.isStream) ?? false
let track: Track?
if isStream {
track = nil
url = URL(string: (ViewController.setFrequency?.streamURL!)!)!
setSystemStatus(to: .active)
ViewController.currentTrack = nil
tclear()
tprint("", raw: true)
tprint("", raw: true)
tprint(" ***", raw: true)
tprint((ViewController.setFrequency?.streamDescription)!, raw: true)
tprint(" ***", raw: true)
removeImage()
ViewController.controlCenterInfo.nowPlayingInfo = [
"mediaType": MPMediaType.anyAudio,
"albumTitle": "Live",
"artist": "FM " + ((ViewController.setFrequency?.num) ?? "unknown"),
"title": (ViewController.setFrequency?.name) ?? "Unknown",
MPNowPlayingInfoPropertyIsLiveStream: 1.0
]
let playerItem = AVPlayerItem.init(url: url)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: playerItem)
ViewController.player = AVPlayer.init(playerItem: playerItem)
ViewController.player.volume = 1.0
ViewController.player.play()
setPlaybackControllerState(to: .playing, isStream: true)
} else {
track = ViewController.playableQueue[from]
ViewController.currentTrack = track
if `init` {
tclear()
tprint("", raw: true)
tprint("", raw: true)
tprint(" ***", raw: true)
tprint(ViewController.playlist!.description!, raw: true)
tprint(" ***", raw: true)
} else {
let e = AutomneAxioms.emojis.randomElement()!
tprint(e + " " + (AutomneAxioms.messages.randomElement() ?? "Playing..."), raw: true, addBreak: true)
AutomneCore.notify(title: e + (track!.user?.username ?? "Unknown") + " in our broadcast",
subtitle: (track!.deepWave! ? "🌀 " : "") + (track!.title ?? "Unknown"))
}
setPlaybackControllerState(to: .loading)
ViewController.playbackIndex = from
let url = URL(string: track!.media!.transcodings![0].url!
+ AutomneAxioms.SCTailQueue[0]
+ AutomneKeys.scKey)!
AF.request(url).response { response in
let decoder = JSONDecoder()
switch response.result {
case .success( _):
guard let data = response.data else {
self.tprint("ERROR122: No data from url callback")
self.setSystemStatus(to: AutomneProperties.SystemStatus.error)
SFX.shutUp()
return
}
let obj = try! decoder.decode(TrackStreamURLCallback.self, from: data)
let playerItem = AVPlayerItem.init(url: URL(string: obj.url!)!)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: playerItem)
ViewController.player = AVPlayer.init(playerItem: playerItem)
ViewController.player.volume = 1.0
if ViewController.defaults.integer(forKey: "narrator") == 1 && !isStream {
let a = SFX.composeAndSpeak(track: (track!.title ?? "unknown"), artist: (track!.user?.username) ?? "unknown")
if a.0 {
DispatchQueue.main.asyncAfter(deadline: .now() + 4.0, execute: { ViewController.player.play() })
} else {
ViewController.player.play()
if ViewController.defaults.integer(forKey: "log") == 1 {
self.tprint("WARN4: (synth) \(a.1 ?? "nil")")
}
}
} else {
ViewController.player.play()
}
let b = ViewController.defaults.integer(forKey: "deepwave_chance")
if b != 0 && !isStream && !(track!.deepWave ?? false) {
let c = Int.random(in: 0...(10 - (b * 2)))
if c == 0 || c == 1 {
self.initDeepwave(with: track!, count: ViewController.defaults.integer(forKey: "deepwave_count"), add: true)
}
}
ViewController.mainDisplayState = .frequency
self.setPlaybackControllerState(to: .playing)
if ViewController.player.error != nil {
self.setSystemStatus(to: .error)
self.setPlaybackControllerState(to: .error)
self.tprint("ERROR7: " + ViewController.player.error!.localizedDescription)
}
case .failure(let error):
self.tprint("ERROR1: " + error.localizedDescription)
self.setSystemStatus(to: AutomneProperties.SystemStatus.error)
SFX.shutUp()
}
}
self.setSystemStatus(to: .active)
self.playbackControllerLight_deepwave.isHidden = !track!.deepWave!
DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: {
self.checkAndInvokeImage()
})
let a = ViewController.controlCenterInfo.nowPlayingInfo?["artwork"]
ViewController.controlCenterInfo.nowPlayingInfo = [
"mediaType": MPMediaType.music,
"albumTitle": (ViewController.setFrequency?.name) ?? "Deepwave",
"artist": (track?.user?.username) ?? "Unknown",
"title": ((track!.deepWave ?? false) ? "🌀 " : "") + ((track?.title) ?? "Unknown"),
"playbackDuration": TimeInterval(exactly: track!.duration! / 1000)!,
"bookmarkTime": TimeInterval(exactly: 0.0)!,
MPNowPlayingInfoPropertyIsLiveStream: 0.0,
]
ViewController.controlCenterInfo.nowPlayingInfo!["artwork"] = a ?? .none
}
}
func pause(){
ViewController.player.pause()
ViewController.sleepTimer?.invalidate()
setSystemStatus(to: .active)
setPlaybackControllerState(to: .paused)
}
func resume(){
ViewController.player.play()
if ViewController.player.error != nil{
setSystemStatus(to: .error)
setPlaybackControllerState(to: .error)
tprint("ERROR9: " + ViewController.player.error!.localizedDescription)