Skip to content

Commit

Permalink
Implement periodic update checking
Browse files Browse the repository at this point in the history
The app now checks for updates every 8 hours.
  • Loading branch information
frannyfx committed Nov 5, 2018
1 parent f700fde commit 58e6720
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 8 deletions.
2 changes: 1 addition & 1 deletion kingsapp/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
<key>CFBundleShortVersionString</key>
<string>1.1.2</string>
<key>CFBundleVersion</key>
<string>2</string>
<string>34</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>LSUIElement</key>
Expand Down
40 changes: 37 additions & 3 deletions kingsapp/StatusMenuController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ class StatusMenuController: NSObject, PreferencesWindowDelegate {
let kingsAPI = KingsAPI()
var currentCalendar: KingsAPI.KCLCalendarResponse? = nil
var calendarLastRefresh: Date? = nil
var lastUpdateCheck: Date? = nil
var username: String? = nil
var password: String? = nil

Expand All @@ -65,8 +66,13 @@ class StatusMenuController: NSObject, PreferencesWindowDelegate {
button.image = icon
}

// Get identifier
print(self.utils.getIdentifier())

// Check for updates
self.checkForUpdatesAndPrompt(promptIfUnavailable: false)
if needsToCheckForUpdate() {
self.checkForUpdatesAndPrompt(promptIfUnavailable: false)
}

// Grab calendar from cache
currentCalendar = loadCachedCalendar()
Expand All @@ -91,6 +97,12 @@ class StatusMenuController: NSObject, PreferencesWindowDelegate {

func checkForUpdatesAndPrompt(promptIfUnavailable: Bool) {
self.utils.checkForUpdates() { (updateAvailable) -> () in
// Save that we updated now
self.lastUpdateCheck = Date()
self.userDefaults.set(self.dateFormatter.string(from: self.lastUpdateCheck!), forKey: "lastUpdateCheck")
self.userDefaults.synchronize()

// Handle UI on main queue
DispatchQueue.main.async { [unowned self] in
print("Update available:", updateAvailable)
let alert = NSAlert()
Expand Down Expand Up @@ -136,12 +148,16 @@ class StatusMenuController: NSObject, PreferencesWindowDelegate {
} else {
self.lastRefreshItem.title = "Not yet refreshed."
}

if self.needsToCheckForUpdate() {
print("Need to check for update...")
self.checkForUpdatesAndPrompt(promptIfUnavailable: false)
}
}

if self.uiTimer == nil {
self.uiTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateUI), userInfo: nil, repeats: true)
self.uiTimer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(self.updateUI), userInfo: nil, repeats: true)
}

}

func preferencesDidUpdate() {
Expand Down Expand Up @@ -177,6 +193,24 @@ class StatusMenuController: NSObject, PreferencesWindowDelegate {
return nil
}

func needsToCheckForUpdate() -> Bool {
// Don't load it from disk if it's cached
if self.lastUpdateCheck == nil {
self.lastUpdateCheck = dateFormatter.date(from: userDefaults.object(forKey: "lastUpdateCheck") as! String)
if lastUpdateCheck == nil {
return true
}
}

// Create threshold date
let currentDate = Date()
let hoursThreshold = 8
var components = DateComponents()
components.hour = -1 * hoursThreshold
let thresholdDate = NSCalendar.current.date(byAdding: components, to: currentDate)
return !(self.lastUpdateCheck! > thresholdDate!)
}

func loadCredentials() {
if let u = userDefaults.object(forKey: "username") {
username = u as! String
Expand Down
29 changes: 25 additions & 4 deletions kingsapp/Utils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,34 @@ import Foundation
class Utils {
let LATEST_VERSION_URL = "https://versions.scuf.me/kingsapp.txt"

func getIdentifier() -> String {
let task = Process()
task.launchPath = "/usr/sbin/ioreg"
task.arguments = ["-rd1", "-c", "IOPlatformExpertDevice"]

let pipe = Pipe()
task.standardOutput = pipe

// Launch and read
task.launch()
task.waitUntilExit()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: .utf8) {
return output.components(separatedBy: "\"IOPlatformUUID\" = \"")[1].components(separatedBy: "\"")[0]
}

return ""
}

func checkForUpdates(completion: @escaping (Bool)->()) {
let session = URLSession.shared
let url = URL(string: LATEST_VERSION_URL)
let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String

// Setup the request
// Setup the request and send unique token
var request = URLRequest(url: url!)
request.addValue("KingsApp " + currentVersion + " | " + getIdentifier(), forHTTPHeaderField: "User-Agent")

// Add body
request.httpMethod = "GET"
Expand All @@ -32,7 +54,6 @@ class Utils {
let newVersionNumbers = newVersion.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: ".")

// Split current version
let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
let currentVersionNumbers = currentVersion.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: ".")

// For loop from 0 to maximum length
Expand Down Expand Up @@ -124,9 +145,9 @@ class Utils {
} else {
return "A minute ago"
}
} else if (components.second! >= 3) {
} /* else if (components.second! >= 3) {
return "\(components.second!) seconds ago"
} else {
} */ else {
return "Just now"
}
}
Expand Down

0 comments on commit 58e6720

Please sign in to comment.