Skip to content

Commit

Permalink
Standardize indentation
Browse files Browse the repository at this point in the history
  • Loading branch information
ZekeSnider committed Aug 5, 2020
1 parent 1b1e311 commit 466e2d4
Show file tree
Hide file tree
Showing 17 changed files with 204 additions and 204 deletions.
6 changes: 3 additions & 3 deletions Jared/ContactHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ class ContactHelper {
}

let contacts = try! store.unifiedContacts(matching: searchPredicate, keysToFetch:[CNContactFamilyNameKey as CNKeyDescriptor,
CNContactGivenNameKey as CNKeyDescriptor,
CNContactEmailAddressesKey as CNKeyDescriptor,
CNContactPhoneNumbersKey as CNKeyDescriptor])
CNContactGivenNameKey as CNKeyDescriptor,
CNContactEmailAddressesKey as CNKeyDescriptor,
CNContactPhoneNumbersKey as CNKeyDescriptor])

if (contacts.count == 1) {
return contacts[0]
Expand Down
20 changes: 10 additions & 10 deletions Jared/CoreModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class CoreModule: RoutingModule {
required public init() {
let appsupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Jared").appendingPathComponent("CoreModule")
let realmLocation = appsupport.appendingPathComponent("database.realm")

try! FileManager.default.createDirectory(at: appsupport, withIntermediateDirectories: true, attributes: nil)

let config = Realm.Configuration(
Expand All @@ -51,7 +51,7 @@ class CoreModule: RoutingModule {
let schedule = Route(name: "/schedule", comparisons: [.startsWith: ["/schedule"]], call: self.schedule, description: NSLocalizedString("scheduleDescription"), parameterSyntax: "/schedule")

let barf = Route(name: "/barf", comparisons: [.startsWith: ["/barf"]], call: self.barf, description: NSLocalizedString("barfDescription"))

routes = [ping, thankYou, version, send, whoami, name, schedule, barf]

//Launch background thread that will check for scheduled messages to send
Expand Down Expand Up @@ -153,7 +153,7 @@ class CoreModule: RoutingModule {
//Check to see if we are within the re-send period for this scheduled message
//values should converge on the number of send interval if we're supposed to send.
if (roundedHigher - roundedLower == Double(post.sendIntervalNumber)) {

//Check to make sure the last time we sent this scheduled message it was not within this send interval
if (nowDate - post.lastSendDate.timeIntervalSinceReferenceDate) > (Double(post.sendIntervalNumber) * intervalSeconds[post.sendIntervalTypeEnum]!) {

Expand All @@ -166,7 +166,7 @@ class CoreModule: RoutingModule {
}
}
}
//We've gone over when the last message for the schedule would have sent. We should delete it from the database
//We've gone over when the last message for the schedule would have sent. We should delete it from the database
else if Int(roundedLower) > post.sendNumberTimes {
try! realm.write {
realm.delete(post)
Expand Down Expand Up @@ -220,13 +220,13 @@ class CoreModule: RoutingModule {
"handle": message.RespondTo().handle,
"sendNumberTimes": sendTimes,
"startDate": Date(),
])
])

let realm = try! Realm()
try! realm.write {
realm.add(newPost)
}

Jared.Send("Your post has been succesfully scheduled.", to: message.RespondTo())
break
case "delete":
Expand Down Expand Up @@ -300,7 +300,7 @@ class CoreModule: RoutingModule {

let peopleFound = try! store.unifiedContacts(matching: searchPredicate, keysToFetch:[CNContactFamilyNameKey as CNKeyDescriptor, CNContactGivenNameKey as CNKeyDescriptor])


//We need to create the contact
if (peopleFound.count == 0) {
// Creating a new contact
Expand All @@ -317,18 +317,18 @@ class CoreModule: RoutingModule {
let iPhonePhone = CNLabeledValue(label: "iPhone", value: CNPhoneNumber(stringValue:message.sender.handle))
newContact.phoneNumbers = [iPhonePhone]
}

let saveRequest = CNSaveRequest()
saveRequest.add(newContact, toContainerWithIdentifier:nil)
do {
try store.execute(saveRequest)
} catch {
return Jared.Send("There was an error saving your contact..", to: message.RespondTo())
return Jared.Send("There was an error saving your contact..", to: message.RespondTo())
}

Jared.Send("Ok, I'll call you \(parsedMessage[1]) from now on.", to: message.RespondTo())
}
//The contact already exists, modify the value
//The contact already exists, modify the value
else {
let mutableContact = peopleFound[0].mutableCopy() as! CNMutableContact
mutableContact.givenName = parsedMessage[1]
Expand Down
12 changes: 6 additions & 6 deletions Jared/CoreModuleRealm.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ enum IntervalType: String {
}

let intervalSeconds: [IntervalType: Double] =
[
.Minute: 60.0,
.Hour: 3600.0,
.Day: 86400.0,
.Week: 604800.0,
.Month: 2592000.0
[
.Minute: 60.0,
.Hour: 3600.0,
.Day: 86400.0,
.Week: 604800.0,
.Month: 2592000.0
]

class SchedulePost: Object {
Expand Down
120 changes: 60 additions & 60 deletions Jared/DatabaseHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ import SQLite3
import Contacts

class DatabaseHandler {
private static let groupQuery = """
private static let groupQuery = """
SELECT handle.id
FROM chat_handle_join INNER JOIN handle ON chat_handle_join.handle_id = handle.ROWID
INNER JOIN chat ON chat_handle_join.chat_id = chat.ROWID
WHERE chat_handle_join.chat_id = ?
"""
private static let attachmentQuery = """
private static let attachmentQuery = """
SELECT ROWID,
filename,
mime_type,
Expand All @@ -33,7 +33,7 @@ class DatabaseHandler {
ON attachment.ROWID = message_attachment_join.attachment_id
WHERE message_id = ?
"""
private static let newRecordquery = """
private static let newRecordquery = """
SELECT handle.id, message.text, message.ROWID, message.cache_roomnames, message.is_from_me, message.destination_caller_id,
message.date/1000000000 + strftime("%s", "2001-01-01"),
message.cache_has_attachments,
Expand All @@ -44,18 +44,18 @@ class DatabaseHandler {
ON message.handle_id = handle.ROWID
WHERE message.ROWID > ? ORDER BY message.ROWID DESC
"""
private static let maxRecordIDQuery = "SELECT MAX(rowID) FROM message"
private static let maxRecordIDQuery = "SELECT MAX(rowID) FROM message"
var db: OpaquePointer?
var querySinceID: String?
var shouldExitThread = false
var refreshSeconds = 5.0
var authorizationError = false
var statement: OpaquePointer? = nil
var router: RouterDelegate?
var router: RouterDelegate?

init(router: RouterDelegate, databaseLocation: URL, diskAccessDelegate: DiskAccessDelegate?) {
self.router = router
self.router = router

if sqlite3_open(databaseLocation.path, &db) != SQLITE_OK {
NSLog("Error opening SQLite database. Likely Full disk access error.")
Expand Down Expand Up @@ -92,7 +92,7 @@ class DatabaseHandler {
var id: String?
var statement: OpaquePointer?

if sqlite3_prepare_v2(db, DatabaseHandler.maxRecordIDQuery, -1, &statement, nil) != SQLITE_OK {
if sqlite3_prepare_v2(db, DatabaseHandler.maxRecordIDQuery, -1, &statement, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing select: \(errmsg)")
}
Expand Down Expand Up @@ -120,7 +120,7 @@ class DatabaseHandler {

var statement: OpaquePointer?

if sqlite3_prepare_v2(db, DatabaseHandler.groupQuery, -1, &statement, nil) != SQLITE_OK {
if sqlite3_prepare_v2(db, DatabaseHandler.groupQuery, -1, &statement, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing select: \(errmsg)")
}
Expand All @@ -145,54 +145,54 @@ class DatabaseHandler {
return Group(name: "", handle: handle, participants: People)
}

private func unwrapStringColumn(for sqlStatement: OpaquePointer?, at column: Int32) -> String? {
private func unwrapStringColumn(for sqlStatement: OpaquePointer?, at column: Int32) -> String? {
if let cString = sqlite3_column_text(sqlStatement, column) {
return String(cString: cString)
} else {
return nil
}
}
private func retrieveAttachments(forMessage messageID: String) -> [Attachment] {
var attachmentStatement: OpaquePointer? = nil
defer { attachmentStatement = nil }
if sqlite3_prepare_v2(db, DatabaseHandler.attachmentQuery, -1, &attachmentStatement, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing select: \(errmsg)")
}
if sqlite3_bind_text(attachmentStatement, 1, messageID, -1, SQLITE_TRANSIENT) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("failure binding: \(errmsg)")
}
var attachments = [Attachment]()
while sqlite3_step(attachmentStatement) == SQLITE_ROW {
guard let rowID = unwrapStringColumn(for: attachmentStatement, at: 0) else { continue }
guard let fileName = unwrapStringColumn(for: attachmentStatement, at: 1) else { continue }
guard let mimeType = unwrapStringColumn(for: attachmentStatement, at: 2) else { continue }
guard let transferName = unwrapStringColumn(for: attachmentStatement, at: 3) else { continue }
private func retrieveAttachments(forMessage messageID: String) -> [Attachment] {
var attachmentStatement: OpaquePointer? = nil
defer { attachmentStatement = nil }
if sqlite3_prepare_v2(db, DatabaseHandler.attachmentQuery, -1, &attachmentStatement, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing select: \(errmsg)")
}
if sqlite3_bind_text(attachmentStatement, 1, messageID, -1, SQLITE_TRANSIENT) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("failure binding: \(errmsg)")
}
var attachments = [Attachment]()
while sqlite3_step(attachmentStatement) == SQLITE_ROW {
guard let rowID = unwrapStringColumn(for: attachmentStatement, at: 0) else { continue }
guard let fileName = unwrapStringColumn(for: attachmentStatement, at: 1) else { continue }
guard let mimeType = unwrapStringColumn(for: attachmentStatement, at: 2) else { continue }
guard let transferName = unwrapStringColumn(for: attachmentStatement, at: 3) else { continue }
let isSticker = sqlite3_column_int(attachmentStatement, 4) == 1
attachments.append(Attachment(id: Int(rowID)!, filePath: fileName, mimeType: mimeType, fileName: transferName, isSticker: isSticker))
attachments.append(Attachment(id: Int(rowID)!, filePath: fileName, mimeType: mimeType, fileName: transferName, isSticker: isSticker))
}

if sqlite3_finalize(attachmentStatement) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error finalizing prepared statement: \(errmsg)")
}
return attachments
}
return attachments
}

private func queryNewRecords() -> Double {
let start = Date()
defer { statement = nil }

if sqlite3_prepare_v2(db, DatabaseHandler.newRecordquery, -1, &statement, nil) != SQLITE_OK {
if sqlite3_prepare_v2(db, DatabaseHandler.newRecordquery, -1, &statement, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing select: \(errmsg)")
}
Expand All @@ -208,12 +208,12 @@ class DatabaseHandler {
let rowID = unwrapStringColumn(for: statement, at: 2)
let roomName = unwrapStringColumn(for: statement, at: 3)
let isFromMe = sqlite3_column_int(statement, 4) == 1
let destinationOptional = unwrapStringColumn(for: statement, at: 5)
let destinationOptional = unwrapStringColumn(for: statement, at: 5)
let epochDate = TimeInterval(sqlite3_column_int64(statement, 6))
let hasAttachment = sqlite3_column_int(statement, 7) == 1
let sendStyle = unwrapStringColumn(for: statement, at: 8)
let associatedMessageType = sqlite3_column_int(statement, 9)
let associatedMessageGUID = unwrapStringColumn(for: statement, at: 10)
let hasAttachment = sqlite3_column_int(statement, 7) == 1
let sendStyle = unwrapStringColumn(for: statement, at: 8)
let associatedMessageType = sqlite3_column_int(statement, 9)
let associatedMessageGUID = unwrapStringColumn(for: statement, at: 10)

querySinceID = rowID;

Expand All @@ -223,22 +223,22 @@ class DatabaseHandler {

let buddyName = ContactHelper.RetreiveContact(handle: senderHandle)?.givenName
let myName = ContactHelper.RetreiveContact(handle: destination)?.givenName
let sender: Person
let recipient: RecipientEntity
let group = retrieveGroupInfo(chatID: roomName)
if (isFromMe) {
sender = Person(givenName: myName, handle: destination, isMe: true)
recipient = group ?? Person(givenName: buddyName, handle: senderHandle, isMe: false)
} else {
sender = Person(givenName: buddyName, handle: senderHandle, isMe: false)
recipient = group ?? Person(givenName: myName, handle: destination, isMe: true)
}
let message = Message(body: TextBody(text), date: Date(timeIntervalSince1970: epochDate), sender: sender, recipient: recipient, attachments: hasAttachment ? retrieveAttachments(forMessage: rowID ?? "") : [],
sendStyle: sendStyle, associatedMessageType: Int(associatedMessageType), associatedMessageGUID: associatedMessageGUID)
router?.route(message: message)
let sender: Person
let recipient: RecipientEntity
let group = retrieveGroupInfo(chatID: roomName)
if (isFromMe) {
sender = Person(givenName: myName, handle: destination, isMe: true)
recipient = group ?? Person(givenName: buddyName, handle: senderHandle, isMe: false)
} else {
sender = Person(givenName: buddyName, handle: senderHandle, isMe: false)
recipient = group ?? Person(givenName: myName, handle: destination, isMe: true)
}
let message = Message(body: TextBody(text), date: Date(timeIntervalSince1970: epochDate), sender: sender, recipient: recipient, attachments: hasAttachment ? retrieveAttachments(forMessage: rowID ?? "") : [],
sendStyle: sendStyle, associatedMessageType: Int(associatedMessageType), associatedMessageGUID: associatedMessageGUID)
router?.route(message: message)
}

if sqlite3_finalize(statement) != SQLITE_OK {
Expand Down
2 changes: 1 addition & 1 deletion Jared/InternalModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ class InternalModule: RoutingModule {
let documentation = pluginManager!.getAllModules()
.map{ module in module.fullDescription }
.joined(separator: "\n\n")

Jared.Send(documentation, to: message.RespondTo())
}

Expand Down
38 changes: 19 additions & 19 deletions Jared/Message.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,18 @@ public struct Message: Encodable {
public var date: Date?
public var sender: SenderEntity
public var recipient: RecipientEntity
public var attachments: [Attachment]
public var sendStyle: SendStyle
public var action: Action?
public var attachments: [Attachment]
public var sendStyle: SendStyle
public var action: Action?

enum CodingKeys : String, CodingKey{
case date
case body
case sender
case recipient
case attachments
case sendStyle
case action
case attachments
case sendStyle
case action
}

public func encode(to encoder: Encoder) throws {
Expand Down Expand Up @@ -54,26 +54,26 @@ public struct Message: Encodable {

try container.encode(formatter.string(from: notOptionalDate), forKey: .date)
}
try container.encode(sendStyle.rawValue, forKey: .sendStyle)
try container.encode(attachments, forKey: .attachments)
if (action != nil) {
try container.encode(action, forKey: .action)
}
try container.encode(sendStyle.rawValue, forKey: .sendStyle)
try container.encode(attachments, forKey: .attachments)
if (action != nil) {
try container.encode(action, forKey: .action)
}
}

public init (body: MessageBody, date: Date, sender: SenderEntity, recipient: RecipientEntity, attachments: [Attachment] = [], sendStyle: String? = nil, associatedMessageType: Int? = nil, associatedMessageGUID: String? = nil) {
public init (body: MessageBody, date: Date, sender: SenderEntity, recipient: RecipientEntity, attachments: [Attachment] = [], sendStyle: String? = nil, associatedMessageType: Int? = nil, associatedMessageGUID: String? = nil) {
self.body = body
self.recipient = recipient
self.sender = sender
self.date = date
self.attachments = attachments
self.sendStyle = SendStyle(fromIdentifier: sendStyle)
if (associatedMessageType != 0 && associatedMessageGUID != nil) {
self.attachments = attachments
self.sendStyle = SendStyle(fromIdentifier: sendStyle)
if (associatedMessageType != 0 && associatedMessageGUID != nil) {
self.action = Action(actionTypeInt: associatedMessageType!, targetGUID: associatedMessageGUID!.replacingOccurrences(of: "p:0/", with: ""))
}
}
}

public func RespondTo() -> RecipientEntity {
Expand Down
Loading

0 comments on commit 466e2d4

Please sign in to comment.