Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Record the location in the metadata #16

Merged
merged 2 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 83 additions & 5 deletions Thoughts.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1520"
LastUpgradeVersion = "1530"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
Expand Down
104 changes: 100 additions & 4 deletions Thoughts/ApplicationModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,19 @@
// SOFTWARE.

import AppKit
import CoreLocation
import Foundation

import Interact

class ApplicationModel: ObservableObject {
@Observable
class ApplicationModel: NSObject {

enum SettingsKey: String {
case rootURL
}

@Published var rootURL: URL? {
var rootURL: URL? {
didSet {
do {
try keyedDefaults.set(securityScopedURL: rootURL, forKey: .rootURL)
Expand All @@ -39,17 +41,43 @@ class ApplicationModel: ObservableObject {
}
}

@Published var document = Document()
var document = Document() {
didSet {
guard let url = rootURL else {
return
}
do {
try document.sync(to: url)
} catch {
print("Failed to save file with error \(error).")
}
}
}

let keyedDefaults = KeyedDefaults<SettingsKey>()
let locationManager = CLLocationManager()
var lastKnownLocation: Location? = nil

init() {
override init() {
rootURL = try? keyedDefaults.securityScopedURL(forKey: .rootURL)
super.init()
locationManager.delegate = self
}

func new() {
dispatchPrecondition(condition: .onQueue(.main))
document = Document()
document.location = lastKnownLocation
}

func userLocation() {
guard locationManager.authorizationStatus != .notDetermined else {
print("Requesting location authorization...")
locationManager.requestWhenInUseAuthorization()
return
}
print("Requsting location...")
locationManager.requestLocation()
}

func setRootURL() {
Expand All @@ -63,6 +91,74 @@ class ApplicationModel: ObservableObject {
return
}
rootURL = url
document = Document()
}

}

extension ApplicationModel: CLLocationManagerDelegate {

func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
print("Location authorization status = \(manager.authorizationStatus.name)")
guard manager.authorizationStatus == .authorized else {
return
}
print("Requsting location...")
manager.requestLocation()
}

func resolveLocation(_ location: CLLocation) async -> Location {
let geocoder = CLGeocoder()
do {
guard let placemark = try await geocoder.reverseGeocodeLocation(location).first else {
return Location(location)
}
return Location(placemark)
} catch {
print("Failed to geocode location with error \(error).")
return Location(location)
}
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
Task {
guard let location = locations.first else {
return
}
let lastKnownLocation = await resolveLocation(location)
print(lastKnownLocation)
await MainActor.run {
self.lastKnownLocation = lastKnownLocation
}
}
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) {
print("Location manager did fail with error \(error).")
}

func locationManager(_ manager: CLLocationManager,
monitoringDidFailFor region: CLRegion?, withError error: any Error) {
print("Location manager monitoring did fail with error \(error).")
}

}

extension CLAuthorizationStatus {

var name: String {
switch self {
case .notDetermined:
return "not determined"
case .restricted:
return "restricted"
case .denied:
return "denied"
case .authorizedAlways:
return "authorized always"
@unknown default:
return "unknown (\(self.rawValue))"
}
}

}
49 changes: 49 additions & 0 deletions Thoughts/Extensions/TimeZone.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import CoreLocation
import Foundation

// https://stackoverflow.com/questions/50384494/swift-retrieve-timezone-from-iso8601-date-string
extension TimeZone {
/// Pattern that grabs the time zone from iso8601 strings
/// This needs to handle the following cases:
/// `<time>Z`
/// `<time>±hh`
/// `<time>±hhmm`
/// `<time>±hh:mm`
/// See https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators .
private static let iso8601TzPattern = /T[\d:.,]+([\+±−-])(\d\d):?(\d\d)?$/

/// Extracts the time zone from an iso8601 formatted date string.
init?(iso8601: String) {
if iso8601.hasSuffix("Z") { // Zulu (UTC)
self.init(secondsFromGMT: 0)
return
}

guard let matches = try? Self.iso8601TzPattern.firstMatch(in: iso8601),
let hours = Int(matches.2) else {
return nil
}

// offset from GMT in seconds
var offset = hours * 3600

if let minutesString = matches.3, let minutes = Int(minutesString) {
offset += minutes * 60
}

// sign
switch matches.1 {
// minus sign and hyphen-minus (not the same)
case "−", "-":
offset = -offset
case "±":
if offset != 0 {
// only allowed for zero offset
return nil
}
default: break
}

self.init(secondsFromGMT: offset)
}
}
21 changes: 21 additions & 0 deletions Thoughts/Licenses/yams-license
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 JP Simard.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
32 changes: 0 additions & 32 deletions Thoughts/Model/ComposeModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,36 +33,4 @@ class ComposeModel: ObservableObject {
self.applicationModel = applicationModel
}

func start() {
dispatchPrecondition(condition: .onQueue(.main))

// Create a new document if the root url changes.
applicationModel
.$rootURL
.receive(on: DispatchQueue.main)
.sink { _ in
self.applicationModel.document = Document()
}
.store(in: &cancellables)

// Save the current document when it changes.
applicationModel
.$document
.combineLatest(applicationModel.$rootURL.compactMap { $0 })
.debounce(for: .seconds(0.1), scheduler: DispatchQueue.main)
.sink { document, rootURL in
do {
try document.sync(to: rootURL)
} catch {
self.error = error
}
}
.store(in: &cancellables)
}

func stop() {
dispatchPrecondition(condition: .onQueue(.main))
cancellables.removeAll()
}

}
36 changes: 22 additions & 14 deletions Thoughts/Model/Document.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,17 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import CoreLocation
import Foundation

struct Document {
import Yams

static func header(date: Date, tags: [String]) -> String {
let dateFormatter = ISO8601DateFormatter()
dateFormatter.timeZone = Calendar.current.timeZone
let dateString = dateFormatter.string(from: date)
let tagsString = tags
.map { "- " + $0 }
.joined(separator: "\n")
return "---\ndate: \(dateString)\ntags:\n\(tagsString)\n---\n\n"
}
struct Document {

var date: Date
var content: String
var tags: String
var location: Location? = nil

var isEmpty: Bool {
return content.isEmpty
Expand All @@ -46,6 +40,23 @@ struct Document {
self.tags = ""
}

func header() -> String {
do {
let tags = tags
.split(separator: /\s+/)
.map { String($0)}
let metadata = Metadata(date: RegionalDate(date, timeZone: .current),
tags: tags,
location: location)
let encoder = YAMLEncoder()
let frontmatter = try encoder.encode(metadata)
return "---\n\(frontmatter)\n---\n"
} catch {
print("Failed to encode metadata with error \(error).")
return ""
}
}

func sync(to rootURL: URL) throws {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss"
Expand All @@ -58,10 +69,7 @@ struct Document {
try fileManager.removeItem(at: url)
}
} else {
let tags = tags
.split(separator: /\s+/)
.map { String($0)}
let content = Self.header(date: date, tags: tags) + self.content
let content = header() + self.content
try content.write(to: url, atomically: true, encoding: .utf8)
}
}
Expand Down
42 changes: 42 additions & 0 deletions Thoughts/Model/Location.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright (c) 2024 Jason Morley
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import CoreLocation
import Foundation

struct Location: Codable {

var latitude: CLLocationDegrees?
var longitude: CLLocationDegrees?
var locality: String?

init(_ location: CLLocation) {
self.latitude = location.coordinate.latitude
self.longitude = location.coordinate.longitude
self.locality = nil
}

init(_ placemark: CLPlacemark) {
self.latitude = placemark.location?.coordinate.latitude
self.longitude = placemark.location?.coordinate.longitude
self.locality = placemark.locality
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,13 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import XCTest
@testable import Thoughts
import CoreLocation
import Foundation

final class ThoughtsTests: XCTestCase {
struct Metadata: Codable {

override func setUpWithError() throws {
}

override func tearDownWithError() throws {
}
let date: RegionalDate
let tags: [String]
let location: Location?

}
Loading