DBManager.swift 23.9 KB
Newer Older
1
/*
2
 *  Copyright (C) 2017-2019 Savoir-faire Linux Inc.
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
 *
 *  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"
42 43 44 45 46 47
    case transferCreated = "TRANSFER_CREATED"
    case transferAwaiting = "TRANSFER_AWAITING"
    case transferCanceled = "TRANSFER_CANCELED"
    case transferOngoing = "TRANSFER_ONGOING"
    case transferSuccess = "TRANSFER_FINISHED"
    case transferError = "TRANSFER_ERROR"
48 49 50

    func toMessageStatus() -> MessageStatus {
        switch self {
51 52 53 54 55 56 57 58
        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
        default: return MessageStatus.unknown
59 60 61 62 63
        }
    }

    init(status: MessageStatus) {
        switch status {
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
        case .unknown: self = .unknown
        case .sending: self = .sending
        case .sent: self = .succeed
        case .read: self = .read
        case .failure: self = .failed
        }
    }

    func toDataTransferStatus() -> DataTransferStatus {
        switch self {
        case .transferCreated: return DataTransferStatus.created
        case .transferAwaiting: return DataTransferStatus.awaiting
        case .transferCanceled: return DataTransferStatus.canceled
        case .transferOngoing: return DataTransferStatus.ongoing
        case .transferSuccess: return DataTransferStatus.success
        case .transferError: return DataTransferStatus.error
        default: return DataTransferStatus.unknown
        }
    }

    init(status: DataTransferStatus) {
        switch status {
        case .created: self = .transferCreated
        case .awaiting: self = .transferAwaiting
        case .canceled: self = .transferCanceled
        case .ongoing: self = .transferOngoing
        case .success: self = .transferSuccess
        case .error: self = .transferError
        case .unknown: self = .unknown
93 94 95 96 97 98 99 100 101
        }
    }
}

enum DBBridgingError: Error {
    case saveMessageFailed
    case getConversationFailed
    case updateMessageStatusFailed
    case deleteConversationFailed
102
    case getProfileFailed
103 104 105
}

enum InteractionType: String {
106 107 108 109 110 111
    case invalid    = "INVALID"
    case text       = "TEXT"
    case call       = "CALL"
    case contact    = "CONTACT"
    case iTransfer  = "INCOMING_DATA_TRANSFER"
    case oTransfer  = "OUTGOING_DATA_TRANSFER"
112 113
}

114
typealias SavedMessageForConversation = (messageID: Int64, conversationID: Int64)
115

116 117 118 119 120 121 122 123 124 125
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,
126
         interactionHepler: InteractionDataHelper) {
127 128 129 130 131 132
        self.profileHepler = profileHepler
        self.conversationHelper = conversationHelper
        self.interactionHepler = interactionHepler
    }

    func start() throws {
133 134 135
        try profileHepler.createTable()
        try conversationHelper.createTable()
        try interactionHepler.createTable()
136 137
    }

138
    func saveMessage(for accountUri: String, with contactUri: String, message: MessageModel, incoming: Bool, interactionType: InteractionType) -> Observable<SavedMessageForConversation> {
139 140

        //create completable which will be executed on background thread
141
        return Observable.create { [weak self] observable in
142 143 144 145 146 147 148 149
            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 {

150
                    guard let accountProfile = try self?.getProfile(for: accountUri, createIfNotExists: true) else {
151 152 153
                        throw DBBridgingError.saveMessageFailed
                    }

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

                    var author: Int64
159 160 161 162 163

                    if incoming {
                       author = contactProfile.id
                    } else {
                       author = accountProfile.id
164 165 166 167 168 169 170 171 172 173 174 175
                    }

                    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
                    }
176
                    var result: Int64?
177 178 179
                    switch interactionType {
                    case .contact:
                        result = self?.addInteractionContactTo(conversation: conversationID, account: accountProfile.id, author: author, message: message)
180 181 182
                    case .text, .call, .iTransfer, .oTransfer:
                        // 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, interactionType: interactionType, message: message)
183 184 185
                    default:
                        result = nil
                    }
186
                    if let messageID = result {
187
                        let savedMessage = SavedMessageForConversation(messageID, conversationID)
188
                        observable.onNext(savedMessage)
189
                        observable.on(.completed)
190
                    } else {
191
                        observable.on(.error(DBBridgingError.saveMessageFailed))
192 193 194
                    }
                }
            } catch {
195
                observable.on(.error(DBBridgingError.saveMessageFailed))
196 197 198 199 200
            }
            return Disposables.create { }
            }
    }

201
    func getConversationsObservable(for accountID: String, accountURI: String) -> Observable<[ConversationModel]> {
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

        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 { }
            }
    }

236 237 238 239 240 241 242 243 244 245 246 247 248 249
    func updateFileName(interactionID: Int64, name: String) -> Completable {
        return Completable.create { [unowned self] completable in
            let success = self.interactionHepler
                .updateInteractionWithID(interactionID: interactionID, content: name)
            if success {
                completable(.completed)
            } else {
                completable(.error(DBBridgingError.updateMessageStatusFailed))
            }

            return Disposables.create { }
        }
    }

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    func updateTransferStatus(daemonID: String, withStatus transferStatus: DataTransferStatus) -> Completable {
        return Completable.create { [unowned self] completable in
            let success = self.interactionHepler
                .updateInteractionWithDaemonID(interactionDaemonID: daemonID,
                                               interactionStatus: InteractionStatus(status: transferStatus).rawValue)
            if success {
                completable(.completed)
            } else {
                completable(.error(DBBridgingError.updateMessageStatusFailed))
            }

            return Disposables.create { }
        }
    }

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    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 { }
            }
    }

286 287 288
    func clearHistoryBetween(accountUri: String,
                             and participantUri: String,
                             keepConversation: Bool) -> Completable {
289 290 291 292 293 294 295
        return Completable.create { [unowned self] completable in
            do {
                guard let dataBase = RingDB.instance.ringDB else {
                    throw DBBridgingError.deleteConversationFailed
                }
                try dataBase.transaction {

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

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

                    guard let conversationsID = try self.getConversationsIDBetween(accountProfileID: accountProfile.id, contactProfileID: contactProfile.id, createIfNotExists: true),
305
                        let conversationID =  conversationsID.first else {
306 307 308
                            throw DBBridgingError.deleteConversationFailed
                    }

309 310 311 312 313 314 315 316 317 318
                    guard let interactions = try self.interactionHepler
                        .selectConversationInteractions(
                            conversationID: conversationsID.first!,
                            accountProfileID: accountProfile.id) else {
                                throw DBBridgingError.deleteConversationFailed
                    }
                    if !interactions.isEmpty {
                        if !self.interactionHepler
                            .deleteAllIntercations(convID: conversationID) {
                            completable(.error(DBBridgingError.deleteConversationFailed))
319
                        }
320 321 322
                    }
                    if keepConversation {
                        completable(.completed)
323
                    } else {
324 325 326 327
                        let successConversations = self.conversationHelper
                            .deleteConversations(conversationID: conversationsID.first!)
                        if successConversations {
                            completable(.completed)
328 329 330
                        } else {
                            completable(.error(DBBridgingError.deleteConversationFailed))
                        }
331
                        // }
332 333 334 335 336 337
                    }
                }
            } catch {
                completable(.error(DBBridgingError.deleteConversationFailed))
            }
            return Disposables.create { }
338
        }
339 340
    }

341
    func profileObservable(for profileUri: String, createIfNotExists: Bool) -> Observable<Profile> {
342 343
        return Observable.create { observable in
            do {
344
                if let profile = try self.getProfile(for: profileUri, createIfNotExists: createIfNotExists) {
345 346 347 348 349 350 351 352 353 354
                    observable.onNext(profile)
                    observable.on(.completed)
                }
            } catch {
                observable.on(.error(DBBridgingError.getProfileFailed))
            }
            return Disposables.create { }
        }
    }

355 356
    // MARK: Private functions

357
    private func buildConversationsForAccount(accountUri: String, accountID: String) throws -> [ConversationModel] {
358

359
        var conversationsToReturn = [ConversationModel]()
360

361
        guard let accountProfile = try self.getProfile(for: accountUri, createIfNotExists: false) else {
362 363 364 365 366 367 368 369 370 371
            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
372
                    continue
373 374 375
            }
            guard let participant =
                self.filterParticipantsFor(account: accountProfile.id,
376
                                           participants: participants) else {
377 378 379
                                            throw DBBridgingError.getConversationFailed
            }
            guard let participantProfile = try self.profileHepler.selectProfile(profileId: participant) else {
Kateryna Kostiuk's avatar
Kateryna Kostiuk committed
380
                continue
381
            }
382
            let conversationModel = ConversationModel(withRecipientRingId: participantProfile.uri,
383
                                                      accountId: accountID, accountUri: accountUri)
384
            conversationModel.participantProfile = participantProfile
385
            conversationModel.conversationId = String(conversationID)
386 387
            var messages = [MessageModel]()
            guard let interactions = try self.interactionHepler
388 389 390 391
                .selectConversationInteractions(
                    conversationID: conversationID,
                    accountProfileID: accountProfile.id) else {
                        continue
392 393
            }
            for interaction in interactions {
394 395 396 397 398
                var author = accountProfile.uri
                if interaction.authorID == participantProfile.id {
                    author = participantProfile.uri
                }
                if let message = self.convertToMessage(interaction: interaction, author: author) {
399 400 401
                    messages.append(message)
                }
            }
402 403
            conversationModel.messages = messages
            conversationsToReturn.append(conversationModel)
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
        }
        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
    }

435
    private func convertToMessage(interaction: Interaction, author: String) -> MessageModel? {
436
        if interaction.type != InteractionType.text.rawValue &&
437
            interaction.type != InteractionType.contact.rawValue &&
438 439 440
            interaction.type != InteractionType.call.rawValue &&
            interaction.type != InteractionType.iTransfer.rawValue &&
            interaction.type != InteractionType.oTransfer.rawValue {
441 442
            return nil
        }
443 444 445 446
        let date = Date(timeIntervalSince1970: TimeInterval(interaction.timestamp))
        let message = MessageModel(withId: interaction.daemonID,
                                   receivedDate: date,
                                   content: interaction.body,
447 448
                                   author: author,
                                   incoming: interaction.incoming)
449 450 451 452
        let isTransfer =    interaction.type == InteractionType.iTransfer.rawValue ||
                            interaction.type == InteractionType.oTransfer.rawValue
        if  interaction.type == InteractionType.contact.rawValue ||
            interaction.type == InteractionType.call.rawValue {
453
            message.isGenerated = true
454 455 456
        } else if isTransfer {
            message.isGenerated = false
            message.isTransfer = true
457
        }
458
        if let status: InteractionStatus = InteractionStatus(rawValue: interaction.status) {
459 460 461 462 463
            if isTransfer {
                message.transferStatus = status.toDataTransferStatus()
            } else {
                message.status = status.toMessageStatus()
            }
464
        }
465
        message.messageId = interaction.id
466 467 468 469 470 471
        return message
    }

    private func addMessageTo(conversation conversationID: Int64,
                              account accountProfileID: Int64,
                              author authorProfileID: Int64,
472
                              interactionType: InteractionType,
473
                              message: MessageModel) -> Int64? {
474 475 476
        let timeInterval = message.receivedDate.timeIntervalSince1970
        let interaction = Interaction(defaultID, accountProfileID, authorProfileID,
                                      conversationID, Int64(timeInterval),
477
                                      message.content, interactionType.rawValue,
478 479
                                      InteractionStatus.unknown.rawValue, message.daemonId,
                                      message.incoming)
480 481 482
        return self.interactionHepler.insert(item: interaction)
    }

483 484 485
    private func addInteractionContactTo(conversation conversationID: Int64,
                                         account accountProfileID: Int64,
                                         author authorProfileID: Int64,
486
                                         message: MessageModel) -> Int64? {
487 488 489 490 491 492 493 494 495
        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)
    }

496
    func createOrUpdateRingProfile(profileUri: String, alias: String?, image: String?, status: ProfileStatus) -> Bool {
497 498 499 500 501 502 503 504 505 506
        let profile = Profile(defaultID, profileUri, alias, image, ProfileType.ring.rawValue,
                              status.rawValue)
        do {
            try self.profileHepler.insertOrUpdateProfile(item: profile)
        } catch {
            return  false
        }
        return true
    }

507
    private func getProfile(for profileUri: String, createIfNotExists: Bool) throws -> Profile? {
508 509 510
        if let profile = try self.profileHepler.selectProfile(accountURI: profileUri) {
            return profile
        }
511 512 513 514
        if !createIfNotExists {
            return nil
        }
        // for now we use template profile
515
        let profile = self.createTemplateRingProfile(account: profileUri)
516
        if self.profileHepler.insert(item: profile) {
517
            return try self.profileHepler.selectProfile(accountURI: profileUri)
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
        }
        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}))))
    }
}