Skip to content

Commit

Permalink
refresh currencies every day
Browse files Browse the repository at this point in the history
  • Loading branch information
cprecioso committed Jul 14, 2021
1 parent e27953c commit b263006
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 1 deletion.
7 changes: 6 additions & 1 deletion Sources/alfred-soulvercore/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@

import SoulverCore

print(calc() ?? "")
refreshIfNeeded {
print(calc() ?? "")
exit(0)
}

RunLoop.current.run()

func calc() -> String? {
let input = CommandLine.arguments.dropFirst().joined(separator: " ")
Expand Down
13 changes: 13 additions & 0 deletions Sources/alfred-soulvercore/prefs.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import Foundation

let BundleIdentifier = "design.precioso.alfred-soulvercore"

let userDefaults = UserDefaults(suiteName: BundleIdentifier)!

let cacheFolder = try? FileManager.default.url(
for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true
).appendingPathComponent(BundleIdentifier)

let LastRefreshKey = "last-refresh"
let UpdatePeriod: TimeInterval = 60 * 60 * 24 // 1 day in seconds
let CurrencyDataURL = cacheFolder?.appendingPathComponent("currencies.json")
44 changes: 44 additions & 0 deletions Sources/alfred-soulvercore/refresh.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import Foundation
import SoulverCore

func refreshIfNeeded(completionHandler: @escaping (() -> Void)) {
let lastRefresh = loadData()
let nextRefresh = lastRefresh.addingTimeInterval(UpdatePeriod)
let currentDate = Date()

if nextRefresh < currentDate {
refresh { result in
if result {
saveData()
}
completionHandler()
}
} else {
completionHandler()
}
}

func refresh(completionHandler: @escaping ((Bool) -> Void)) {
CurrencyList.shared.defaultCurrencySet = .popular
CurrencyList.shared.refreshRates(completionHandler: completionHandler)
}

func loadData() -> Date {
var returnDate: Date? = nil

if let url = CurrencyDataURL,
(try? CurrencyList.shared.loadCurrenciesFrom(url: url)) != nil
{
returnDate = userDefaults.object(forKey: LastRefreshKey) as? Date
}

return returnDate ?? Date.distantPast
}

func saveData() {
if let url = CurrencyDataURL,
(try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)) != nil {
CurrencyList.shared.saveCurrenciesTo(url: url)
userDefaults.set(Date(), forKey: LastRefreshKey)
}
}

0 comments on commit b263006

Please sign in to comment.