subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

DivePhotos.swift (6227B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import CoreLocation
      3 import Foundation
      4 import Observation
      5 import Photos
      6 import SubsurfaceLog
      7 
      8 /// A photo or video from the photo library, linked to a dive by the time it was taken.
      9 struct DivePhoto: Identifiable {
     10     let asset: PHAsset
     11     /// Seconds since the start of the dive when the photo was taken during the dive; nil otherwise.
     12     let offset: Int?
     13     var id: String { asset.localIdentifier }
     14 }
     15 
     16 /// Photo library access: the app only reads, and only once permission is granted.
     17 @MainActor
     18 @Observable
     19 final class PhotoAccess {
     20     var status = PHPhotoLibrary.authorizationStatus(for: .readWrite)
     21 
     22     var granted: Bool { status == .authorized || status == .limited }
     23 
     24     func request() async {
     25         status = await PHPhotoLibrary.requestAuthorization(for: .readWrite)
     26     }
     27 }
     28 
     29 /// Time zone of a dive site. The logbook keeps the local time of the site, photos an absolute instant: to match
     30 /// them, we need to know which time zone the dive was in. It is requested from Apple once (reverse geocoding of
     31 /// the site position), then cached.
     32 enum SiteTimeZone {
     33     private static func key(_ site: DiveSite) -> String {
     34         String(format: "tz-%.2f,%.2f", site.latitude ?? 0, site.longitude ?? 0)
     35     }
     36 
     37     static func cached(for site: DiveSite?) -> TimeZone? {
     38         guard let site, site.hasLocation, let name = UserDefaults.standard.string(forKey: key(site)) else { return nil }
     39         return TimeZone(identifier: name)
     40     }
     41 
     42     /// Time zone estimated offline: the one of the longitude (standard time), accurate to within an hour.
     43     static func estimated(for site: DiveSite?) -> TimeZone {
     44         guard let longitude = site?.longitude else { return .current }
     45         return TimeZone(secondsFromGMT: Int((longitude / 15).rounded()) * 3600) ?? .current
     46     }
     47 
     48     /// Without a position, or if the lookup fails: the time zone of the iPhone.
     49     static func zone(for site: DiveSite?) async -> TimeZone {
     50         guard let site, let latitude = site.latitude, let longitude = site.longitude else { return .current }
     51         if let known = cached(for: site) { return known }
     52         let placemarks = try? await CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude))
     53         if let zone = placemarks?.first?.timeZone {
     54             UserDefaults.standard.set(zone.identifier, forKey: key(site))
     55             return zone
     56         }
     57         // At sea, far from everything: the "nautical" time zone of the longitude beats the one of the iPhone.
     58         return TimeZone(secondsFromGMT: Int((longitude / 15).rounded()) * 3600) ?? .current
     59     }
     60 }
     61 
     62 enum DivePhotoFinder {
     63     /// True when the time of the dive was not written in the paper logbook: it is then a guess.
     64     ///
     65     /// The marker is DATA, not interface text: it was written into the notes of existing logbooks in French, so
     66     /// the French literal must stay as is. The English marker is accepted as well.
     67     static func timeIsGuessed(_ dive: Dive) -> Bool {
     68         dive.notes.contains("Heure non écrite sur la fiche") || dive.notes.contains("Time not written on the log page")
     69     }
     70 
     71     /// Absolute instant of a "naive" logbook time, in the time zone of the site.
     72     static func absolute(_ when: Int, in zone: TimeZone) -> Date {
     73         let naive = Date(timeIntervalSince1970: TimeInterval(when))
     74         return naive.addingTimeInterval(-TimeInterval(zone.secondsFromGMT(for: naive)))
     75     }
     76 
     77     /// Window in which to look for photos: the dive with a margin (20 min before, 30 min after), or the whole
     78     /// day at the site when the time is not known.
     79     static func window(for dive: Dive, elapsed: Int, zone: TimeZone) -> DateInterval {
     80         if timeIsGuessed(dive) {
     81             let dayStart = dive.when - dive.when % 86_400
     82             return DateInterval(start: absolute(dayStart, in: zone), duration: 86_400)
     83         }
     84         let start = absolute(dive.when, in: zone)
     85         return DateInterval(start: start.addingTimeInterval(-20 * 60), duration: TimeInterval(elapsed + 50 * 60))
     86     }
     87 
     88     /// What the photo library holds for a dive.
     89     struct Presence: Equatable {
     90         var photos = false
     91         var videos = false
     92         var any: Bool { photos || videos }
     93     }
     94 
     95     /// Are there photos or videos in the window of the dive? `slack` widens the window when the time zone of
     96     /// the site is only estimated (within an hour, because of daylight saving time).
     97     static func presence(for dive: Dive, zone: TimeZone, slack: TimeInterval = 0) -> Presence {
     98         let window = window(for: dive, elapsed: dive.durationSeconds, zone: zone)
     99         func exists(_ type: PHAssetMediaType) -> Bool {
    100             let options = PHFetchOptions()
    101             options.predicate = NSPredicate(format: "creationDate >= %@ AND creationDate <= %@",
    102                                             window.start.addingTimeInterval(-slack) as NSDate, window.end.addingTimeInterval(slack) as NSDate)
    103             options.fetchLimit = 1
    104             return PHAsset.fetchAssets(with: type, options: options).count > 0
    105         }
    106         return Presence(photos: exists(.image), videos: exists(.video))
    107     }
    108 
    109     /// Photos and videos in the window, in the order they were taken.
    110     static func photos(for dive: Dive, elapsed: Int, zone: TimeZone, limit: Int = 300) -> [DivePhoto] {
    111         let window = window(for: dive, elapsed: elapsed, zone: zone)
    112         let options = PHFetchOptions()
    113         options.predicate = NSPredicate(format: "creationDate >= %@ AND creationDate <= %@", window.start as NSDate, window.end as NSDate)
    114         options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
    115         options.fetchLimit = limit
    116         let start = absolute(dive.when, in: zone)
    117         var out = [DivePhoto]()
    118         PHAsset.fetchAssets(with: options).enumerateObjects { asset, _, _ in
    119             var offset: Int?
    120             if !timeIsGuessed(dive), let taken = asset.creationDate {
    121                 let seconds = Int(taken.timeIntervalSince(start))
    122                 if seconds >= 0, seconds <= elapsed { offset = seconds }
    123             }
    124             out.append(DivePhoto(asset: asset, offset: offset))
    125         }
    126         return out
    127     }
    128 }