DBManager.swift 19.9 KB
Newer Older
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
/*
 *  Copyright (C) 2017 Savoir-faire Linux Inc.
 *
 *  Author: Kateryna Kostiuk <kateryna.kostiuk@savoirfairelinux.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
 */

import Foundation
import RxSwift

enum ProfileType: String {
    case ring = "RING"
    case sip = "SIP"
}

enum ProfileStatus: String {
    case trusted = "TRUSTED"
    case untrasted = "UNTRUSTED"
}

enum InteractionStatus: String {
    case invalid = "INVALID"
    case unknown = "UNKNOWN"
    case sending = "SENDING"
    case failed = "FAILED"
    case succeed = "SUCCEED"
    case read = "READ"
    case unread = "UNREAD"

    func toMessageStatus() -> MessageStatus {
        switch self {
        case .invalid:
            return MessageStatus.unknown
        case .unknown:
            return MessageStatus.unknown
        case .sending:
            return MessageStatus.sending
        case .failed:
            return MessageStatus.failure
        case .succeed:
            return MessageStatus.sent
        case .read:
            return MessageStatus.read
        case .unread:
            return MessageStatus.unknown
        }
    }

    init(status: MessageStatus) {
        switch status {
        case .unknown:
            self = .unknown
        case .sending:
            self = .sending
        case .sent:
            self = .succeed
        case .read:
            self = .read
        case .failure:
            self = .failed
        }
    }
}

enum DBBridgingError: Error {
    case saveMessageFailed
    case getConversationFailed
    case updateMessageStatusFailed
    case deleteConversationFailed
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
83
    case getProfileFailed
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
}

enum InteractionType: String {
    case invalid = "INVALID"
    case text    = "TEXT"
    case call    = "CALL"
    case contact = "CONTACT"
}

class DBManager {

    let profileHepler: ProfileDataHelper
    let conversationHelper: ConversationDataHelper
    let interactionHepler: InteractionDataHelper

    // used to create object to save to db. When inserting in table defaultID will be replaced by autoincrementedID
    let defaultID: Int64 = 1

    init(profileHepler: ProfileDataHelper, conversationHelper: ConversationDataHelper,
         interactionHepler: InteractionDataHelper) {
        self.profileHepler = profileHepler
        self.conversationHelper = conversationHelper
        self.interactionHepler = interactionHepler
    }

    func start() throws {
        try profileHepler.createTable()
        try conversationHelper.createTable()
        try interactionHepler.createTable()
    }

115
    func saveMessage(for accountUri: String, with contactUri: String, message: MessageModel, incoming: Bool, interactionType: InteractionType) -> Completable {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
116 117 118 119 120 121 122 123 124 125 126

        //create completable which will be executed on background thread
        return Completable.create { [weak self] completable in
            do {
                guard let dataBase = RingDB.instance.ringDB else {
                    throw DataAccessError.datastoreConnectionError
                }

                //use transaction to lock access to db from other threads while the following queries are executed
                try dataBase.transaction {

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
127
                    guard let accountProfile = try self?.getProfile(for: accountUri, createIfNotExists: true) else {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
128 129 130 131 132 133 134 135
                        throw DBBridgingError.saveMessageFailed
                    }

                    guard let contactProfile = try self?.getProfile(for: contactUri, createIfNotExists: true) else {
                        throw DBBridgingError.saveMessageFailed
                    }

                    var author: Int64
136 137 138 139 140

                    if incoming {
                       author = contactProfile.id
                    } else {
                       author = accountProfile.id
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
141 142 143 144 145 146 147 148 149 150 151 152
                    }

                    guard let conversationsID = try self?.getConversationsIDBetween(accountProfileID: accountProfile.id,
                                                                                    contactProfileID: contactProfile.id,
                                                                                    createIfNotExists: true),
                        !conversationsID.isEmpty else {
                            throw DBBridgingError.saveMessageFailed
                    }

                    guard let conversationID = conversationsID.first else {
                            throw DBBridgingError.saveMessageFailed
                    }
153 154 155 156 157 158 159 160 161 162 163
                    var result: Bool?
                    switch interactionType {
                    case .text:
                        // for now we have only one conversation between two persons(with group chat could be many)
                        result = self?.addMessageTo(conversation: conversationID, account: accountProfile.id, author: author, message: message)
                    case .contact:
                        result = self?.addInteractionContactTo(conversation: conversationID, account: accountProfile.id, author: author, message: message)
                    default:
                        result = nil
                    }
                    if let success = result, success {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
164 165 166 167 168 169 170 171 172 173 174 175
                        completable(.completed)
                    } else {
                        completable(.error(DBBridgingError.saveMessageFailed))
                    }
                }
            } catch {
                completable(.error(DBBridgingError.saveMessageFailed))
            }
            return Disposables.create { }
            }
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
176
    func getConversationsObservable(for accountID: String, accountURI: String) -> Observable<[ConversationModel]> {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274

        return Observable.create { observable in

            do {
                guard let dataBase = RingDB.instance.ringDB else {
                    throw DBBridgingError.getConversationFailed
                }
                try dataBase.transaction {
                    let conversations = try self.buildConversationsForAccount(accountUri: accountURI, accountID: accountID)
                    observable.onNext(conversations)
                    observable.on(.completed)
                }
            } catch {
                observable.on(.error(DBBridgingError.getConversationFailed))
            }
            return Disposables.create { }
            }
    }

    func updateMessageStatus(daemonID: String, withStatus status: MessageStatus) -> Completable {
        return Completable.create { [unowned self] completable in
            let success = self.interactionHepler
                .updateInteractionWithDaemonID(interactionDaemonID: daemonID,
                                         interactionStatus: InteractionStatus(status: status).rawValue)
            if success {
                completable(.completed)
            } else {
                completable(.error(DBBridgingError.updateMessageStatusFailed))
            }

            return Disposables.create { }
            }
    }

    func setMessagesAsRead(messagesIDs: [Int64], withStatus status: MessageStatus) -> Completable {
        return Completable.create { [unowned self] completable in
            var success = true
            for messageId in messagesIDs {
                if !self.interactionHepler
                    .updateInteractionWithID(interactionID: messageId,
                                             interactionStatus: InteractionStatus(status: status).rawValue) {
                    success = false
                }

            }
            if success {
                completable(.completed)
            } else {
                completable(.error(DBBridgingError.saveMessageFailed))
            }

            return Disposables.create { }
            }
    }

    func removeConversationBetween(accountUri: String, and participantUri: String) -> Completable {
        return Completable.create { [unowned self] completable in
            do {
                guard let dataBase = RingDB.instance.ringDB else {
                    throw DBBridgingError.deleteConversationFailed
                }
                try dataBase.transaction {

                    guard let accountProfile = try self.getProfile(for: accountUri, createIfNotExists: false) else {
                        throw DBBridgingError.deleteConversationFailed
                    }

                    guard let contactProfile = try self.getProfile(for: participantUri, createIfNotExists: false) else {
                        throw DBBridgingError.deleteConversationFailed
                    }

                    guard let conversationsID = try self.getConversationsIDBetween(accountProfileID: accountProfile.id, contactProfileID: contactProfile.id, createIfNotExists: true),
                        !conversationsID.isEmpty else {
                            throw DBBridgingError.deleteConversationFailed
                    }

                    let successInteraction = self.interactionHepler
                        .deleteInteractionsForConversation(convID: conversationsID.first!)
                    if successInteraction {
                        let successConversations = self.conversationHelper
                            .deleteConversations(conversationID: conversationsID.first!)
                        if successConversations {
                            completable(.completed)
                        } else {
                            completable(.error(DBBridgingError.deleteConversationFailed))
                        }
                    } else {
                        completable(.error(DBBridgingError.deleteConversationFailed))
                    }
                }
            } catch {
                completable(.error(DBBridgingError.deleteConversationFailed))
            }
            return Disposables.create { }

            }
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
275 276 277 278 279 280 281 282 283 284 285 286 287 288
    func profileObservable(for profileUri: String, createIfNotExists: Bool) -> Observable<Profile> {
        return Observable.create { observable in
            do {
                if let profile = try self.getProfile(for: profileUri, createIfNotExists: createIfNotExists) {
                    observable.onNext(profile)
                    observable.on(.completed)
                }
            } catch {
                observable.on(.error(DBBridgingError.getProfileFailed))
            }
            return Disposables.create { }
        }
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
289 290
    // MARK: Private functions

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
291
    private func buildConversationsForAccount(accountUri: String, accountID: String) throws -> [ConversationModel] {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
292

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
293
        var conversationsToReturn = [ConversationModel]()
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
294 295 296 297 298 299 300 301 302 303 304 305

        guard let accountProfile = try self.getProfile(for: accountUri, createIfNotExists: false) else {
            throw DBBridgingError.getConversationFailed
        }
        guard let conversationsID = try self.selectConversationsForAccount(accountProfile: accountProfile.id),
            !conversationsID.isEmpty else {
                // if there is no conversation for account return empty list
                return conversationsToReturn
        }
        for conversationID in conversationsID {
            guard let participants = try self.getParticipantsForConversation(conversationID: conversationID),
                !participants.isEmpty else {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
306
                    continue
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
307 308 309 310 311 312 313
            }
            guard let participant =
                self.filterParticipantsFor(account: accountProfile.id,
                                          participants: participants) else {
                                            throw DBBridgingError.getConversationFailed
            }
            guard let participantProfile = try self.profileHepler.selectProfile(profileId: participant) else {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
314
                continue
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
315
            }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
316 317 318
            let conversationModel = ConversationModel(withRecipientRingId: participantProfile.uri,
                                                       accountId: accountID, accountUri: accountUri)
            conversationModel.participantProfile = participantProfile
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
319 320 321 322 323
            var messages = [MessageModel]()
            guard let interactions = try self.interactionHepler
                .selectInteractionsForConversationWithAccount(conversationID: conversationID,
                                                              accountProfileID: accountProfile.id),
                !interactions.isEmpty else {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
324
                    continue
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
325 326
            }
            for interaction in interactions {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
327 328 329 330 331
                var author = accountProfile.uri
                if interaction.authorID == participantProfile.id {
                    author = participantProfile.uri
                }
                if let message = self.convertToMessage(interaction: interaction, author: author) {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
332 333 334 335
                    messages.append(message)
                }

            }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
336 337
            conversationModel.messages = messages
            conversationsToReturn.append(conversationModel)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
        }
        return conversationsToReturn
    }

    private func selectConversationsForAccount(accountProfile: Int64)throws -> [Int64]? {
        guard let accountConversations = try self.conversationHelper.selectConversationsForProfile(profileId: accountProfile) else {
            return nil
        }
        return accountConversations.map({$0.id})
    }

    private func getParticipantsForConversation(conversationID: Int64) throws -> [Int64]? {
        guard let conversations = try self.conversationHelper.selectConversations(conversationId: conversationID) else {
            return nil
        }
        return conversations.map({$0.participantID})
    }

    private func filterParticipantsFor(account profileID: Int64, participants: [Int64]) -> Int64? {
        var participants = participants
        guard let accountProfileIndex = participants.index(of: profileID) else {
            return nil
        }
        participants.remove(at: accountProfileIndex)
        if participants.isEmpty {
            return nil
        }
        // for now we does not support group chat, so we have only two participant for each conversation
        return participants.first
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
369
    private func convertToMessage(interaction: Interaction, author: String) -> MessageModel? {
370 371 372 373
        if interaction.type != InteractionType.text.rawValue &&
            interaction.type != InteractionType.contact.rawValue {
            return nil
        }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
374 375 376 377
        let date = Date(timeIntervalSince1970: TimeInterval(interaction.timestamp))
        let message = MessageModel(withId: interaction.daemonID,
                                   receivedDate: date,
                                   content: interaction.body,
378 379
                                   author: author,
                                   incoming: interaction.incoming)
380 381 382
        if interaction.type == InteractionType.contact.rawValue {
            message.isGenerated = true
        }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
383 384 385
        if let status: InteractionStatus = InteractionStatus(rawValue: interaction.status) {
            message.status = status.toMessageStatus()
        }
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
386
        message.messageId = interaction.id
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
387 388 389 390 391 392 393 394 395 396 397
        return message
    }

    private func addMessageTo(conversation conversationID: Int64,
                              account accountProfileID: Int64,
                              author authorProfileID: Int64,
                              message: MessageModel) -> Bool {
        let timeInterval = message.receivedDate.timeIntervalSince1970
        let interaction = Interaction(defaultID, accountProfileID, authorProfileID,
                                      conversationID, Int64(timeInterval),
                                      message.content, InteractionType.text.rawValue,
398 399
                                      InteractionStatus.unknown.rawValue, message.daemonId,
                                      message.incoming)
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
400 401 402
        return self.interactionHepler.insert(item: interaction)
    }

403 404 405 406 407 408 409 410 411 412 413 414 415
    private func addInteractionContactTo(conversation conversationID: Int64,
                                         account accountProfileID: Int64,
                                         author authorProfileID: Int64,
                                         message: MessageModel) -> Bool {
        let timeInterval = message.receivedDate.timeIntervalSince1970
        let interaction = Interaction(defaultID, accountProfileID, authorProfileID,
                                      conversationID, Int64(timeInterval),
                                      message.content, InteractionType.contact.rawValue,
                                      InteractionStatus.read.rawValue, message.daemonId,
                                      message.incoming)
        return self.interactionHepler.insertIfNotExist(item: interaction)
    }

416 417 418 419 420 421 422 423 424 425 426
    func createOrUpdateRingProfile(profileUri: String, alias: String?, image: String?, status: ProfileStatus) -> Bool {
        let profile = Profile(defaultID, profileUri, alias, image, ProfileType.ring.rawValue,
                              status.rawValue)
        do {
            try self.profileHepler.insertOrUpdateProfile(item: profile)
        } catch {
            return  false
        }
        return true
    }

Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    private func getProfile(for profileUri: String, createIfNotExists: Bool) throws -> Profile? {
        if let profile = try self.profileHepler.selectProfile(accountURI: profileUri) {
            return profile
        }
        if !createIfNotExists {
            return nil
        }
        // for now we use template profile
        let profile = self.createTemplateRingProfile(account: profileUri)
        if self.profileHepler.insert(item: profile) {
            return try self.profileHepler.selectProfile(accountURI: profileUri)
        }
        return nil
    }

    private func createTemplateRingProfile(account uri: String) -> Profile {
        return Profile(defaultID, uri, nil, nil, ProfileType.ring.rawValue,
                       ProfileStatus.untrasted.rawValue)
    }

    private func getConversationsIDBetween(accountProfileID: Int64,
                                           contactProfileID: Int64,
                                           createIfNotExists: Bool) throws -> [Int64]? {
        if let accountConversations = try self.conversationHelper
            .selectConversationsForProfile(profileId: accountProfileID) {
            if let contactConversations = try self.conversationHelper
                .selectConversationsForProfile(profileId: contactProfileID) {

                let result = Array(Set(accountConversations.map({$0.id}))
                    .intersection(Set(contactConversations.map({$0.id}))))
                if !result.isEmpty {
                    return result
                }
            }
        }
        if !createIfNotExists {
            return nil
        }
        let conversationID = Int64(arc4random_uniform(10000000))
        let conversationForAccount = Conversation(conversationID, accountProfileID)
        let conversationForContact = Conversation(conversationID, contactProfileID)

        if !self.conversationHelper.insert(item: conversationForAccount) {
            return nil
        }
        if !self.conversationHelper.insert(item: conversationForContact) {
            return nil
        }

        guard let accountConversations = try self.conversationHelper
            .selectConversationsForProfile(profileId: accountProfileID) else {
                return nil
        }
        guard let contactConversations = try self.conversationHelper
            .selectConversationsForProfile(profileId: contactProfileID) else {
                return nil
        }
        return Array(Set(accountConversations.map({$0.id}))
            .intersection(Set(contactConversations.map({$0.id}))))
    }
}