Skip to content

Commit

Permalink
Fix update system
Browse files Browse the repository at this point in the history
  • Loading branch information
PierreBerger committed Aug 19, 2021
1 parent 4ce05a7 commit 17393c0
Show file tree
Hide file tree
Showing 15 changed files with 119 additions and 317 deletions.
158 changes: 6 additions & 152 deletions LivecamWallpaper.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

48 changes: 30 additions & 18 deletions LivecamWallpaper/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,13 @@ class AppDelegate: NSObject, NSApplicationDelegate {

func applicationDidFinishLaunching(_: Notification) {
Bugsnag.start()
parseArguments()
setup()
if MyApp.isFirstLaunch {
openPreferences()
} else {
resetInterval()
}
setup()
}

func changeWallpaper(savedUrl: URL) {
Expand All @@ -36,25 +39,30 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}
}

func createDirectories() -> URL? {
let wallpaperFolder = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent(".livecamWallpaper")
.appendingPathComponent("wallpapers")

if !FileManager.default.fileExists(atPath: wallpaperFolder.path) {
do {
try FileManager.default.createDirectory(atPath: wallpaperFolder.path, withIntermediateDirectories: true, attributes: nil)

return wallpaperFolder
} catch {
print(error.localizedDescription)
return nil
}
}
return wallpaperFolder
}

func downloadImage(url: URL) {
URLSession.shared.downloadTask(with: url) { urlOrNil, _, _ in
guard let fileURL = urlOrNil else { return }
do {
guard let dataPath = self.createDirectories() else { return }

let documentsURL = try
FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)

let dataPath = documentsURL.appendingPathComponent("wallpaper")
if !FileManager.default.fileExists(atPath: dataPath.path) {
do {
try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error.localizedDescription)
}
}
do {

let savedURL = dataPath.appendingPathComponent(String(NSDate().timeIntervalSince1970))
try FileManager.default.moveItem(at: fileURL, to: savedURL)
Expand Down Expand Up @@ -88,8 +96,10 @@ class AppDelegate: NSObject, NSApplicationDelegate {

func clearFolder() {
let fileManager = FileManager.default
let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let wallpaperDir = documentsUrl.appendingPathComponent("wallpaper")
let wallpaperDir = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent(".livecamWallpaper")
.appendingPathComponent("wallpapers")

guard var filePaths = try?
fileManager.contentsOfDirectory(at: wallpaperDir, includingPropertiesForKeys: nil, options: [])
else { return }
Expand Down Expand Up @@ -193,6 +203,8 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}

func setup() {
_ = createDirectories()

menu = NSMenu()
setupMenu()
statusBarItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))
Expand Down
4 changes: 1 addition & 3 deletions LivecamWallpaper/LivecamWallpaper.entitlements
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.files.user-selected.read-only</key>
<true/>
<false/>
<key>com.apple.security.network.client</key>
<true/>
</dict>
Expand Down
4 changes: 1 addition & 3 deletions LivecamWallpaper/LivecamWallpaperRelease.entitlements
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<false/>
<key>com.apple.security.network.client</key>
<true/>
</dict>
Expand Down
55 changes: 27 additions & 28 deletions LivecamWallpaper/Updater/updater.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Cocoa
import SystemConfiguration
import LivecamWallpaperUpdaterService

// see https://github.com/exelban/stats/blob/4351d25a222d00bfe8d74b5a169998c9aa6d4dfc/Kit/plugins/Updater.swift

Expand Down Expand Up @@ -82,21 +81,11 @@ public class Updater {
NSLog(fileURL.debugDescription)
do {
let downloadsURL = try
FileManager.default.url(for: .documentDirectory,
FileManager.default.url(for: .downloadsDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
let updateFolder = downloadsURL.appendingPathComponent("updates")

if !FileManager.default.fileExists(atPath: updateFolder.path) {
do {
try FileManager.default.createDirectory(atPath: updateFolder.path, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error.localizedDescription)
}
}

let destinationURL = updateFolder.appendingPathComponent(url.lastPathComponent)
let destinationURL = downloadsURL.appendingPathComponent(url.lastPathComponent)

self.copyFile(from: fileURL, to: destinationURL) { (path, error) in
if error != nil {
Expand Down Expand Up @@ -150,22 +139,32 @@ public class Updater {
.replacingOccurrences(of: "LivecamWallpaper.app", with: "")
.replacingOccurrences(of: "//", with: "/")

let connection = NSXPCConnection(serviceName: "fr.pierreberger.LivecamWallpaperUpdaterService")
connection.remoteObjectInterface = NSXPCInterface(with: LivecamWallpaperUpdaterServiceProtocol.self)
connection.resume()

let service = connection.remoteObjectProxyWithErrorHandler { error in
print("Received error:", error)
} as? LivecamWallpaperUpdaterServiceProtocol

service?.installNewVersion(
path,
tmpDir: NSTemporaryDirectory(),
pwd: pwd
) { response in
print("Response from XPC service:", response)
guard response != "OK" else { exit(0) }
NSLog("Started new version installation...")

_ = syncShell("mkdir /tmp/LivecamWallpaper") // make sure that directory exist
let res = syncShell("/usr/bin/hdiutil attach \(path) -mountpoint /tmp/LivecamWallpaper -noverify -nobrowse -noautoopen") // mount the dmg

NSLog("DMG is mounted")

let tmpDir = NSTemporaryDirectory()

if res.contains("is busy") { // dmg can be busy, if yes, unmount it and mount again
print("DMG is busy, remounting")

_ = syncShell("/usr/bin/hdiutil detach \(tmpDir)/LivecamWallpaper")
_ = syncShell("/usr/bin/hdiutil attach \(path) -mountpoint /tmp/LivecamWallpaper -noverify -nobrowse -noautoopen")
}

_ = syncShell("cp -rf /tmp/LivecamWallpaper/LivecamWallpaper.app/Contents/Resources/Scripts/updater.sh \(tmpDir)/updater.sh")

NSLog("Script is copied to $TMPDIR/updater.sh")

let dmg = path.replacingOccurrences(of: "file://", with: "")

asyncShell("sh \(tmpDir)/updater.sh --app \(pwd) --dmg \(dmg) >/dev/null &") // run updater script in in background

NSLog("Run updater.sh with app: \(pwd) and dmg: \(dmg)")

exit(0)
}
}
25 changes: 25 additions & 0 deletions LivecamWallpaper/Utils/Utilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,28 @@ enum MyApp {
extension AppDelegate {
static let shared = NSApp.delegate as! AppDelegate
}

public func asyncShell(_ args: String) {
let task = Process()
let pipe = Pipe()
task.launchPath = "/bin/sh"
task.arguments = ["-c", args]
task.standardOutput = pipe
task.launch()
}

public func syncShell(_ args: String) -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
// task.standardError = pipe
task.arguments = ["-c", args]
task.launchPath = "/bin/sh"
task.launch()
task.waitUntilExit()

let data = pipe.fileHandleForReading.readDataToEndOfFile()

let output = String(data: data, encoding: .utf8)!
return output
}
4 changes: 3 additions & 1 deletion LivecamWallpaper/Views/Update.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import SwiftUI
import Cocoa

// see https://github.com/exelban/stats/blob/bf5b4c406e86e8ddf301e7b2c25d557c6e97c842/Stats/Views/Update.swift

class UpdateWindow: NSWindow, NSWindowDelegate {
private let viewController: UpdateViewController = UpdateViewController()
init() {
Expand Down Expand Up @@ -106,7 +108,7 @@ private class UpdateView: NSView {
let latestVersion: NSTextView = NSTextView(frame: NSRect(
x: (view.frame.width-currentVersionWidth)/2,
y: currentVersion.frame.origin.y - 22,
width: latestVersionWidth,
width: latestVersionWidth + 5,
height: 16
))
latestVersion.string = latestVersionString
Expand Down
26 changes: 26 additions & 0 deletions LivecamWallpaper/helpers.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import Foundation
import os.log

extension AppDelegate {
internal func parseArguments() {
let args = CommandLine.arguments

if let mountIndex = args.firstIndex(of: "--mount-path") {
if args.indices.contains(mountIndex+1) {
let mountPath = args[mountIndex+1]
asyncShell("/usr/bin/hdiutil detach \(mountPath)")
asyncShell("/bin/rm -rf \(mountPath)")

os_log(.debug, log: log, "DMG was unmounted and mountPath deleted")
}
}

if let dmgIndex = args.firstIndex(of: "--dmg-path") {
if args.indices.contains(dmgIndex+1) {
asyncShell("/bin/rm -rf \(args[dmgIndex+1])")

os_log(.debug, log: log, "DMG was deleted")
}
}
}
}
29 changes: 0 additions & 29 deletions LivecamWallpaperUpdaterService/Info.plist

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

26 changes: 0 additions & 26 deletions LivecamWallpaperUpdaterService/Utils.swift

This file was deleted.

6 changes: 0 additions & 6 deletions LivecamWallpaperUpdaterService/main.swift

This file was deleted.

0 comments on commit 17393c0

Please sign in to comment.