Skip to content

Commit

Permalink
Add SwiftLint and autocorrect
Browse files Browse the repository at this point in the history
  • Loading branch information
robbiet480 committed Jan 7, 2017
1 parent 4b9bdb7 commit 9bc995c
Show file tree
Hide file tree
Showing 57 changed files with 780 additions and 771 deletions.
5 changes: 5 additions & 0 deletions .swiftlint.yml
@@ -0,0 +1,5 @@
excluded:
- fastlane
- HomeAssistantTests
- HomeAssistantUITests
- Pods
44 changes: 22 additions & 22 deletions APNSAttachmentService/NotificationService.swift
Expand Up @@ -10,41 +10,41 @@ import UserNotifications
import MobileCoreServices

final class NotificationService: UNNotificationServiceExtension {

private var contentHandler: ((UNNotificationContent) -> Void)?
private var bestAttemptContent: UNMutableNotificationContent?

private var baseURL: String = ""
private var apiPassword: String = ""
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void){

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
print("APNSAttachmentService started!")
print("Received userInfo", request.content.userInfo)
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

let prefs = UserDefaults(suiteName: "group.io.robbie.homeassistant")!
if let url = prefs.string(forKey: "baseURL") {
baseURL = url
}
if let pass = prefs.string(forKey: "apiPassword") {
apiPassword = pass
}

func failEarly() {
contentHandler(request.content)
}

guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else {
return failEarly()
}

var incomingAttachment: [String:Any] = [:]

if let iAttachment = content.userInfo["attachment"] as? [String:Any] {
incomingAttachment = iAttachment
}

if content.categoryIdentifier == "camera" && incomingAttachment["url"] == nil {
guard let entityId = content.userInfo["entity_id"] as? String else {
return failEarly()
Expand All @@ -57,18 +57,18 @@ final class NotificationService: UNNotificationServiceExtension {
return failEarly()
}
}

guard let attachmentString = incomingAttachment["url"] as? String else {
return failEarly()
}

guard let attachmentURL = URL(string: attachmentString) else {
return failEarly()
}
var attachmentOptions:[String:Any] = [:]

var attachmentOptions: [String:Any] = [:]
if let attachmentContentType = incomingAttachment["content-type"] as? String {
var contentType:CFString = attachmentContentType as CFString
var contentType: CFString = attachmentContentType as CFString
switch attachmentContentType.lowercased() {
case "aiff":
contentType = kUTTypeAudioInterchangeFileFormat
Expand Down Expand Up @@ -102,30 +102,30 @@ final class NotificationService: UNNotificationServiceExtension {
}
guard let attachmentData = NSData(contentsOf:attachmentURL) else { return failEarly() }
guard let attachment = UNNotificationAttachment.create(fileIdentifier: attachmentURL.lastPathComponent, data: attachmentData, options: attachmentOptions) else { return failEarly() }

content.attachments.append(attachment)

contentHandler(content.copy() as! UNNotificationContent)
}

override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}

}

extension UNNotificationAttachment {

/// Save the attachment URL to disk
static func create(fileIdentifier: String, data: NSData, options: [AnyHashable : Any]?) -> UNNotificationAttachment? {
let fileManager = FileManager.default
let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
let tmpSubFolderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true)

do {
try fileManager.createDirectory(at: tmpSubFolderURL!, withIntermediateDirectories: true, attributes: nil)
let fileURL = tmpSubFolderURL?.appendingPathComponent(fileIdentifier)
Expand All @@ -134,7 +134,7 @@ extension UNNotificationAttachment {
} catch let error {
print("Error when saving attachment: \(error)")
}

return nil
}
}
17 changes: 16 additions & 1 deletion HomeAssistant.xcodeproj/project.pbxproj
Expand Up @@ -935,14 +935,15 @@
buildConfigurationList = B657A9101CA646EB00121384 /* Build configuration list for PBXNativeTarget "HomeAssistant" */;
buildPhases = (
EE918EC7744FD53B5836AC00 /* [CP] Check Pods Manifest.lock */,
B641BC261E20BAF3002CCBC1 /* Swiftlint */,
B657A8E21CA646EB00121384 /* Sources */,
B657A8E31CA646EB00121384 /* Frameworks */,
B657A8E41CA646EB00121384 /* Resources */,
B6E8579C1CB1167200F96925 /* ShellScript */,
B6E47E861CB9FD350027F6CA /* ShellScript */,
D458061599D246B74530F402 /* [CP] Embed Pods Frameworks */,
EB3BEB157867EEEFE3AFD2F3 /* [CP] Copy Pods Resources */,
B6AAD7AC1D827DD40090B220 /* Embed App Extensions */,
B6E8579C1CB1167200F96925 /* ShellScript */,
);
buildRules = (
);
Expand Down Expand Up @@ -1336,6 +1337,20 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-HomeAssistantTests/Pods-HomeAssistantTests-resources.sh\"\n";
showEnvVarsInLog = 0;
};
B641BC261E20BAF3002CCBC1 /* Swiftlint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = Swiftlint;
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi";
};
B6E47E861CB9FD350027F6CA /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
Expand Down
52 changes: 26 additions & 26 deletions HomeAssistant/AppDelegate.swift
Expand Up @@ -16,8 +16,8 @@ import AlamofireNetworkActivityIndicator

let realmConfig = Realm.Configuration(
schemaVersion: 2,
migrationBlock: { migration, oldSchemaVersion in

migrationBlock: { _, oldSchemaVersion in
if (oldSchemaVersion < 1) {
}
})
Expand All @@ -28,30 +28,30 @@ let realm = try! Realm(configuration: realmConfig)
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

let prefs = UserDefaults(suiteName: "group.io.robbie.homeassistant")!

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
migrateUserDefaultsToAppGroups()
Realm.Configuration.defaultConfiguration = realmConfig
print("Realm file path", Realm.Configuration.defaultConfiguration.fileURL!.path)
Fabric.with([Crashlytics.self])

NetworkActivityIndicatorManager.shared.isEnabled = true

if #available(iOS 10, *) {
UNUserNotificationCenter.current().delegate = self
}

Crashlytics.sharedInstance().setObjectValue(prefs.integer(forKey: "lastInstalledVersion"), forKey: "lastInstalledVersion")
let buildNumber = Int(string: Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")! as! String)
prefs.set(buildNumber, forKey: "lastInstalledVersion")

initAPI()

return true
}

func initAPI() {
if let baseURL = prefs.string(forKey: "baseURL") {
print("Base URL is", baseURL)
Expand All @@ -61,7 +61,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
firstly {
HomeAssistantAPI.sharedInstance.Setup(baseAPIUrl: baseURL, APIPassword: apiPass)
}.then {_ in
}.then {_ in
HomeAssistantAPI.sharedInstance.Connect()
}.then { _ -> Void in
if HomeAssistantAPI.sharedInstance.notificationsEnabled {
Expand All @@ -80,7 +80,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
}
}

func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
Expand All @@ -106,30 +106,30 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

self.prefs.setValue(deviceTokenString, forKey: "deviceToken")

print("Registering push with deviceTokenString: \(deviceTokenString)")

_ = HomeAssistantAPI.sharedInstance.registerDeviceForPush(deviceToken: deviceTokenString).then { pushId -> Void in
print("Registered for push. PushID:", pushId)
CLSLogv("Registered for push:", getVaList([pushId]))
Crashlytics.sharedInstance().setUserIdentifier(pushId)
self.prefs.setValue(pushId, forKey: "pushID")
}

}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Swift.Error) {
print("Error when trying to register for push", error)
Crashlytics.sharedInstance().recordError(error)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("Received remote notification in completion handler!")

let userInfoDict = userInfo as! [String:Any]

if let hadict = userInfoDict["homeassistant"] as? [String:String] {
if let command = hadict["command"] {
switch command {
Expand All @@ -150,17 +150,17 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
}
}

func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], withResponseInfo responseInfo: [AnyHashable : Any], completionHandler: @escaping () -> Void) {
var userInput:String? = nil
var userInput: String? = nil
if let userText = responseInfo[UIUserNotificationActionResponseTypedTextKey] as? String {
userInput = userText
}
let _ = HomeAssistantAPI.sharedInstance.handlePushAction(identifier: identifier!, userInfo: userInfo, userInput: userInput)
}

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
var serviceData : [String:String] = url.queryItems!
var serviceData: [String:String] = url.queryItems!
serviceData["sourceApplication"] = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String
switch url.host! {
case "call_service": // homeassistant://call_service/device_tracker.see?entity_id=device_tracker.entity
Expand All @@ -182,7 +182,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
@available(iOS 10, *)
extension AppDelegate: UNUserNotificationCenterDelegate {
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
var userText : String? = nil
var userText: String? = nil
if let textInput = response as? UNTextInputNotificationResponse {
userText = textInput.userText
}
Expand All @@ -194,7 +194,7 @@ extension AppDelegate: UNUserNotificationCenterDelegate {
completionHandler()
}
}

public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
Expand Down
8 changes: 4 additions & 4 deletions HomeAssistant/Classes/Components/AutomationComponent.swift
Expand Up @@ -10,15 +10,15 @@ import Foundation
import ObjectMapper

class Automation: Entity {

dynamic var LastTriggered: Date? = nil

override func mapping(map: Map) {
super.mapping(map: map)

LastTriggered <- (map["attributes.last_triggered"], HomeAssistantTimestampTransform())
}

override var ComponentIcon: String {
return "mdi:playlist-play"
}
Expand Down
12 changes: 6 additions & 6 deletions HomeAssistant/Classes/Components/BinarySensorComponent.swift
Expand Up @@ -10,23 +10,23 @@ import Foundation
import ObjectMapper

class BinarySensor: SwitchableEntity {

dynamic var SensorClass: String? = nil

override func mapping(map: Map) {
super.mapping(map: map)

SensorClass <- map["attributes.sensor_class"]
}

override var ComponentIcon: String {
return "mdi:radiobox-blank"
}

override func StateIcon() -> String {
if self.MobileIcon != nil { return self.MobileIcon! }
if self.Icon != nil { return self.Icon! }

let activated = (self.IsOn == false)
if let sensorClass = self.SensorClass {
switch (sensorClass) {
Expand Down

0 comments on commit 9bc995c

Please sign in to comment.