DOCSIS-Toolkit/Logger4/AppDelegate.swift
2020-06-11 16:24:01 +02:00

141 lines
5.3 KiB
Swift

//
// AppDelegate.swift
// Logger4
//
// Created by Kilian Hofmann on 15.06.17.
// Copyright © 2017 Kilian Hofmann. All rights reserved.
//
// Folder Structure "~/KDLog/YEAR.docsisplist2/MONTH/DAY/FILE"
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: - Things that have to be kept alive for the application lifetime
// lock for mutex access to files
var lock: pthread_mutex_t = pthread_mutex_t()
// Date formaters
let justDate: DateFormatter = DateFormatter()
let justTime: DateFormatter = DateFormatter()
// Status Item
var statusItem: NSStatusItem = NSStatusItem()
// URL Session for DOCSIS data and Internet check
let urlSession: URLSession = URLSession(configuration: .default)
// Preferences
let pref: NSWindowController = NSWindowController(windowNibName: "SettingsWindowController")
// Timers
var timerFreqs: Timer = Timer()
var timerFails: Timer = Timer()
// MARK: - Application Lifecycle
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Show Preferneces if defaults are empty
UserDefaults.standard.register(defaults: ["upstream" : "", "downstream" : ""])
if UserDefaults.standard.string(forKey: "upstream") == nil || UserDefaults.standard.string(forKey: "downstream") == nil {
pref.showWindow(nil)
}
// Init lock
pthread_mutex_init(&((NSApp.delegate as! AppDelegate).lock), nil)
// Setup date formatters
justDate.dateStyle = DateFormatter.Style.medium
justDate.timeStyle = DateFormatter.Style.none
justDate.locale = Locale(identifier: "de_DE")
justTime.dateStyle = .none
justTime.timeStyle = .medium
justTime.timeZone = NSTimeZone.local
justTime.locale = Locale(identifier: "de_DE")
// Set status item
statusItem = NSStatusBar.system.statusItem(withLength: -2)
statusItem.title = "AL"
// Create status item menu
let menu: NSMenu = NSMenu.init()
menu.autoenablesItems = false
let menuAbout: NSMenuItem = NSMenuItem(title: "About Logger", action: #selector(NSApp.orderFrontStandardAboutPanel(_:)), keyEquivalent: "")
let menuQuit: NSMenuItem = NSMenuItem.init(title: "Quit", action: #selector(NSApp.terminate(_:)), keyEquivalent: "q")
let menuPref: NSMenuItem = NSMenuItem(title: "Preferences", action: #selector(self.preferences(_:)), keyEquivalent: "")
menuPref.image = NSImage(named: NSImage.actionTemplateName)
// Layout menu
menu.addItem(menuAbout)
menu.addItem(NSMenuItem.separator())
menu.addItem(menuPref)
menu.addItem(NSMenuItem.separator())
menu.addItem(menuQuit)
// Add menu
statusItem.menu = menu
// Check if directory exists, create or exit
let fileManager = FileManager.default
var directory: ObjCBool = ObjCBool(false)
pthread_mutex_lock(&((NSApp.delegate as! AppDelegate).lock))
let exists: Bool = fileManager.fileExists(atPath: ("~/KDLog" as NSString).expandingTildeInPath, isDirectory: &directory)
if exists && directory.boolValue {
} else if exists {
NSLog("FILE WITH NAME KDLog EXISTS, REMOVE IT")
exit(1);
}
else {
do {
try fileManager.createDirectory(atPath: ("~/KDLog" as NSString).expandingTildeInPath, withIntermediateDirectories: false, attributes: nil)
}
catch let error as NSError {
NSLog("ERROR ON DIRECTORY CREATION: \(error.localizedDescription)")
exit(1);
}
}
pthread_mutex_unlock(&((NSApp.delegate as! AppDelegate).lock))
// Init timers
if UserDefaults.standard.string(forKey: "upstream") != nil || UserDefaults.standard.string(forKey: "downstream") != nil {
initTimers()
}
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
urlSession.invalidateAndCancel()
return .terminateNow
}
// MARK: - Logging Functions
@objc func logFreqs(_: Timer) {
let frequencyOperation: FrequencyOperation = FrequencyOperation()
OperationQueue.main.addOperation(frequencyOperation)
}
@objc func logFails(_: Timer) {
let connectionLossOperation: ConnectionLossOperation = ConnectionLossOperation()
OperationQueue.main.addOperation(connectionLossOperation)
}
// MARK: - General functions
@objc func preferences(_ sender: NSMenuItem) {
timerFreqs.invalidate()
timerFails.invalidate()
pref.showWindow(sender)
pref.window?.makeKeyAndOrderFront(self)
}
func initTimers() {
timerFreqs.invalidate()
timerFails.invalidate()
timerFreqs = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(logFreqs), userInfo: nil, repeats: true)
timerFails = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(logFails), userInfo: nil, repeats: true)
}
@IBAction func close(_ sender: NSButton){
initTimers()
sender.superview?.window?.close()
}
}