84 lines
1.7 KiB
Swift
84 lines
1.7 KiB
Swift
//
|
|
// NotesStorage.swift
|
|
// Peered
|
|
//
|
|
// Created by Oskar Chybowski on 25/09/2025.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
protocol StorageProvider {
|
|
func contentsOfDirectory(atPath path: String) throws -> [String]
|
|
|
|
@discardableResult
|
|
func createFile(
|
|
atPath path: String, contents data: Data?, attributes attr: [FileAttributeKey: Any]?
|
|
) -> Bool
|
|
}
|
|
|
|
extension FileManager: StorageProvider {}
|
|
|
|
struct NotesStorage {
|
|
let storageProvider: StorageProvider
|
|
let rootDirectory: URL
|
|
|
|
init(
|
|
storageProvider: StorageProvider = FileManager.default,
|
|
rootDirectory: URL = .documentsDirectory
|
|
) {
|
|
self.storageProvider = storageProvider
|
|
self.rootDirectory = rootDirectory
|
|
}
|
|
|
|
func loadNotes() -> [Note] {
|
|
let files =
|
|
try! storageProvider
|
|
.contentsOfDirectory(atPath: rootDirectory.path)
|
|
var notes = [Note]()
|
|
|
|
for file in files.compactMap({
|
|
URL(
|
|
filePath: $0,
|
|
directoryHint: .notDirectory,
|
|
relativeTo: rootDirectory
|
|
)
|
|
}) {
|
|
let name = file.lastPathComponent
|
|
let note = Note(
|
|
name: name,
|
|
path: file
|
|
)
|
|
notes.append(note)
|
|
}
|
|
|
|
return notes
|
|
}
|
|
|
|
func createNote(name: String) {
|
|
let currentNotes = loadNotes()
|
|
var index: Int? = nil
|
|
var proposedName: String {
|
|
index.map { name + " \($0)" } ?? name
|
|
}
|
|
|
|
while currentNotes.contains(where: { $0.name == proposedName }) {
|
|
if let _index = index {
|
|
index = _index + 1
|
|
} else {
|
|
index = 1
|
|
}
|
|
}
|
|
|
|
let pathToWrite =
|
|
rootDirectory
|
|
.appendingPathComponent(proposedName)
|
|
.appendingPathExtension(for: .text)
|
|
|
|
storageProvider.createFile(
|
|
atPath: pathToWrite.path,
|
|
contents: Data(),
|
|
attributes: nil
|
|
)
|
|
}
|
|
}
|