Remove SQLite

This commit is contained in:
christophhagen 2020-05-25 10:05:16 +02:00
parent 4f53c2e5c8
commit 9abe7d7918
3 changed files with 26 additions and 36 deletions

View File

@ -5,10 +5,9 @@ let package = Package(
name: "CapCollectorServer", name: "CapCollectorServer",
dependencies: [ dependencies: [
.package(url: "https://github.com/vapor/vapor.git", .upToNextMinor(from: "3.3.0")), .package(url: "https://github.com/vapor/vapor.git", .upToNextMinor(from: "3.3.0")),
.package(url: "https://github.com/stephencelis/SQLite.swift", from: "0.12.0"),
], ],
targets: [ targets: [
.target(name: "App", dependencies: ["Vapor", "SQLite"]), .target(name: "App", dependencies: ["Vapor"]),
.target(name: "Run", dependencies: ["App"]), .target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App"]), .testTarget(name: "AppTests", dependencies: ["App"]),
] ]

View File

@ -36,7 +36,7 @@ private func catching<T>(_ path: PathComponentsRepresentable..., request: Reques
log("\(route): Error \(error)") log("\(route): Error \(error)")
return HTTPResponse(status: error.response) return HTTPResponse(status: error.response)
} catch { } catch {
log("\(route): Unhandled error \(error)") log("\(route): Unhandled error: \(error)")
return HTTPResponse(status: .internalServerError) return HTTPResponse(status: .internalServerError)
} }
} }

View File

@ -1,6 +1,5 @@
import Routing import Routing
import Vapor import Vapor
import SQLite
// MARK: Paths // MARK: Paths
@ -12,7 +11,7 @@ private let publicFolder = baseFolder.appendingPathComponent("Public")
private let imageFolder = publicFolder.appendingPathComponent("images") private let imageFolder = publicFolder.appendingPathComponent("images")
private let dbFile = publicFolder.appendingPathComponent("db.sqlite3").path private let nameFile = publicFolder.appendingPathComponent("names.txt")
private let tempImageFile = publicFolder.appendingPathComponent("temp.jpg") private let tempImageFile = publicFolder.appendingPathComponent("temp.jpg")
@ -20,26 +19,18 @@ private let tempImageFile = publicFolder.appendingPathComponent("temp.jpg")
private let fm = FileManager.default private let fm = FileManager.default
private var db: Connection! private var caps = [String]()
// MARK: SQLite // MARK: SQLite
private let id = Expression<Int>("id") func loadCapNames() throws {
let s = try String(contentsOf: nameFile)
private let name = Expression<String>("name") caps = s.components(separatedBy: "\n")
log("\(caps.count) caps loaded")
private let table = Table("caps")
func loadDatabase() throws {
db = try Connection(dbFile)
} }
// MARK: Helper // MARK: Helper
private func select(_ cap: Int) -> Table {
table.filter(id == cap)
}
private func folder(of cap: Int) -> URL { private func folder(of cap: Int) -> URL {
imageFolder.appendingPathComponent(String(format: "%04d", cap)) imageFolder.appendingPathComponent(String(format: "%04d", cap))
} }
@ -68,27 +59,36 @@ private func count(of cap: Int) throws -> Int {
public func routes(_ router: Router) throws { public func routes(_ router: Router) throws {
try Log.set(logFile: logFile) try Log.set(logFile: logFile)
try loadCapNames()
// Get the name of a cap // Get the name of a cap
router.getCatching("name", Int.parameter) { request -> Data in router.getCatching("name", Int.parameter) { request -> Data in
let cap = try request.parameters.next(Int.self) let cap = try request.parameters.next(Int.self)
guard let row = try db.pluck(table.select(name).filter(id == cap)) else { guard cap < caps.count else {
throw CapError.unknownId throw CapError.unknownId
} }
return row[name].data(using: .utf8)! return caps[cap].data(using: .utf8)!
} }
// Set the name of a cap // Set the name of a cap
router.postCatching("name", Int.parameter) { request in router.postCatching("name", Int.parameter) { request in
let cap = try request.parameters.next(Int.self) let cap = try request.parameters.next(Int.self)
guard let data = request.http.body.data, let string = String(data: data, encoding: .utf8) else { guard let data = request.http.body.data, let name = String(data: data, encoding: .utf8) else {
throw CapError.invalidBody throw CapError.invalidBody
} }
guard let _ = try db.pluck(select(cap)) else { guard cap <= caps.count else {
try db.run(select(cap).insert(id <- cap, name <- string)) throw CapError.unknownId
return
} }
try db.run(select(cap).update(name <- string))
if cap == caps.count {
caps.append(name)
// Create image folder
let url = folder(of: cap)
try fm.createDirectory(at: url, withIntermediateDirectories: false)
} else {
caps[cap] = name
}
try caps.joined(separator: "\n").data(using: .utf8)!.write(to: nameFile)
} }
// Upload an image // Upload an image
@ -114,17 +114,8 @@ public func routes(_ router: Router) throws {
} }
// Get the count of all caps // Get the count of all caps
router.getCatching("count", "all") { request -> Data in router.getCatching("counts") { request -> Data in
let counts: [(id: Int, count: Int)] = try fm.contentsOfDirectory(at: imageFolder, includingPropertiesForKeys: nil).compactMap { folder in try (1...caps.count).map { UInt8(try count(of: $0)) }.convertToData()
guard let id = Int(folder.lastPathComponent) else {
return nil
}
guard let count = try? countImages(in: folder) else {
return nil
}
return (id, count)
}
return counts.map { "\($0.id)#\($0.count)"}.joined(separator: ";").data(using: .utf8)!
} }
// Set a different version as the main image // Set a different version as the main image