forked from HammerPot/Maple-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMusicButton.swift
More file actions
265 lines (236 loc) · 8.53 KB
/
MusicButton.swift
File metadata and controls
265 lines (236 loc) · 8.53 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
//
// MusicButton.swift
// Maple
//
// Created by Potter on 3/26/25.
//
import SwiftUI
import UniformTypeIdentifiers
import AVFoundation
struct MusicButton: View {
@State private var importing = false
@State private var localFiles: [URL] = []
var body: some View {
Button("Add Music") {
importing = true
}
.fileImporter(
isPresented: $importing,
allowedContentTypes: [.audio],
allowsMultipleSelection: true
) { result in
switch result {
case .success(let files):
for file in files {
guard file.startAccessingSecurityScopedResource() else {
print("Failed to access the file")
continue
}
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
print("Documents directory: \(documentsDirectory)")
let songFolder = documentsDirectory.appendingPathComponent("tracks")
do {
if !FileManager.default.fileExists(atPath: songFolder.path) {
try FileManager.default.createDirectory(at: songFolder, withIntermediateDirectories: true, attributes: nil)
}
} catch {
print("Error creating song folder: \(error.localizedDescription)")
}
let UUID = UUID()
let fileExt = file.pathExtension
let fileName = UUID.uuidString + "." + fileExt
let destinationURL = songFolder.appendingPathComponent(fileName)
print("Destination URL: \(destinationURL)")
do {
if FileManager.default.fileExists(atPath: destinationURL.path) {
print("EXTREME EDGE CASE: File already exists with the same UUID, this should never happen. File is being removed and replaced.")
try FileManager.default.removeItem(at: destinationURL)
}
try FileManager.default.copyItem(at: file, to: destinationURL)
Task {
do {
let metadata = await extractMetadata(from: destinationURL, id: UUID)
var song = Song(id: UUID,
title: metadata.title,
artist: metadata.artist,
album: metadata.album,
year: metadata.year,
genre: metadata.genre,
duration: metadata.duration,
artwork: metadata.artwork,
trackNumber: metadata.trackNumber,
discNumber: metadata.discNumber,
ext: metadata.ext,
url: destinationURL)
let jsonURL = songFolder.appendingPathComponent("tracks.json")
let jsonDecoder = JSONDecoder()
let jsonEncoder = JSONEncoder()
var songs: [Song] = []
if !FileManager.default.fileExists(atPath: jsonURL.path) {
songs.append(song)
let _jsonData = try jsonEncoder.encode(songs)
try _jsonData.write(to: jsonURL)
}
else {
let jsonData = try Data(contentsOf: jsonURL)
var songs:[Song] = try jsonDecoder.decode([Song].self, from: jsonData)
songs.append(song)
let _jsonData = try jsonEncoder.encode(songs)
try _jsonData.write(to: jsonURL)
}
loadAlbums(song: song)
loadArtist(song: song)
print("Song \(destinationURL.lastPathComponent) has finished doing its last do-task in theory")
}
}
print("Song \(destinationURL.lastPathComponent) this print should be AFTER do-task's")
} catch {
print("Error copying file: \(error.localizedDescription)")
}
file.stopAccessingSecurityScopedResource()
}
loadLocalFiles()
case .failure(let error):
print("Error importing files: \(error.localizedDescription)")
}
importing = false
}
}
private func formatFileSize(file: URL) -> String {
do {
let resourceValues = try file.resourceValues(forKeys: [.fileSizeKey])
let fileSize = resourceValues.fileSize ?? 0
let byteCountFormatter = ByteCountFormatter()
byteCountFormatter.allowedUnits = [.useMB]
byteCountFormatter.countStyle = .file
return byteCountFormatter.string(fromByteCount: Int64(fileSize))
} catch {
return "Unknown size"
}
}
}
struct MusicButtonPlus: View {
@State private var importing = false
@State private var localFiles: [URL] = []
var body: some View {
Button() {
importing = true
} label: {
Image(systemName: "plus")
.font(.title.weight(.semibold))
.padding()
.background(Color.accentColor)
.foregroundColor(.white)
.clipShape(Circle())
.shadow(radius: 4, x: 0, y: 4)
}
.fileImporter(
isPresented: $importing,
allowedContentTypes: [.audio],
allowsMultipleSelection: true
) { result in
switch result {
case .success(let files):
for file in files {
guard file.startAccessingSecurityScopedResource() else {
print("Failed to access the file")
continue
}
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
print("Documents directory: \(documentsDirectory)")
let songFolder = documentsDirectory.appendingPathComponent("tracks")
do {
if !FileManager.default.fileExists(atPath: songFolder.path) {
try FileManager.default.createDirectory(at: songFolder, withIntermediateDirectories: true, attributes: nil)
}
} catch {
print("Error creating song folder: \(error.localizedDescription)")
}
let UUID = UUID()
let fileExt = file.pathExtension
let fileName = UUID.uuidString + "." + fileExt
let destinationURL = songFolder.appendingPathComponent(fileName)
print("Destination URL: \(destinationURL)")
do {
if FileManager.default.fileExists(atPath: destinationURL.path) {
print("EXTREME EDGE CASE: File already exists with the same UUID, this should never happen. File is being removed and replaced.")
try FileManager.default.removeItem(at: destinationURL)
}
try FileManager.default.copyItem(at: file, to: destinationURL)
Task {
do {
let metadata = await extractMetadata(from: destinationURL, id: UUID)
var song = Song(id: UUID,
title: metadata.title,
artist: metadata.artist,
album: metadata.album,
year: metadata.year,
genre: metadata.genre,
duration: metadata.duration,
artwork: metadata.artwork,
trackNumber: metadata.trackNumber,
discNumber: metadata.discNumber,
ext: metadata.ext,
url: destinationURL)
let jsonURL = songFolder.appendingPathComponent("tracks.json")
let jsonDecoder = JSONDecoder()
let jsonEncoder = JSONEncoder()
var songs: [Song] = []
if !FileManager.default.fileExists(atPath: jsonURL.path) {
songs.append(song)
let _jsonData = try jsonEncoder.encode(songs)
try _jsonData.write(to: jsonURL)
}
else {
let jsonData = try Data(contentsOf: jsonURL)
var songs:[Song] = try jsonDecoder.decode([Song].self, from: jsonData)
songs.append(song)
let _jsonData = try jsonEncoder.encode(songs)
try _jsonData.write(to: jsonURL)
}
loadAlbums(song: song)
loadArtist(song: song)
print("Song \(destinationURL.lastPathComponent) has finished doing its last do-task in theory")
}
}
print("Song \(destinationURL.lastPathComponent) this print should be AFTER do-task's")
} catch {
print("Error copying file: \(error.localizedDescription)")
}
file.stopAccessingSecurityScopedResource()
}
loadLocalFiles()
case .failure(let error):
print("Error importing files: \(error.localizedDescription)")
}
importing = false
}
}
private func formatFileSize(file: URL) -> String {
do {
let resourceValues = try file.resourceValues(forKeys: [.fileSizeKey])
let fileSize = resourceValues.fileSize ?? 0
let byteCountFormatter = ByteCountFormatter()
byteCountFormatter.allowedUnits = [.useMB]
byteCountFormatter.countStyle = .file
return byteCountFormatter.string(fromByteCount: Int64(fileSize))
} catch {
return "Unknown size"
}
}
}
func clearDocumentsDirectory() {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try FileManager.default.contentsOfDirectory(at: documentsDirectory,
includingPropertiesForKeys: nil)
for fileURL in fileURLs {
try FileManager.default.removeItem(at: fileURL)
}
} catch {
print("Error clearing documents directory: \(error.localizedDescription)")
}
}
#Preview {
MusicButton()
}