Commit 0ea39d4d authored by Kateryna Kostiuk's avatar Kateryna Kostiuk

Revert "database: migrate to version 1"

This reverts commit e48a0f55.

Reason for revert: This migration is not in production yet. New migration to database per account will be performed.

Change-Id: I3f5777fe0346c3da2f816393ae8b118b3ec281fb
parent 9deaa8e9
......@@ -122,7 +122,6 @@
0E4909751FEAC943005CAA50 /* CallViewController.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 0E4909741FEAC943005CAA50 /* CallViewController.storyboard */; };
0E49097A1FEAC9E1005CAA50 /* CallViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E4909791FEAC9E1005CAA50 /* CallViewController.swift */; };
0E49097C1FEACA4B005CAA50 /* CallViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E49097B1FEACA4B005CAA50 /* CallViewModel.swift */; };
0E67B5D62218E0FB001790D9 /* AccountProfileHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E67B5D52218E0FB001790D9 /* AccountProfileHelper.swift */; };
0E68571120238546008B0717 /* ConversationNavigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E68571020238546008B0717 /* ConversationNavigation.swift */; };
0E6949791FA7E71C0029B60A /* BaseViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E6949781FA7E71C0029B60A /* BaseViewController.swift */; };
0E72374A20460320006B0C7D /* ProfileHeaderView.xib in Resources */ = {isa = PBXBuildFile; fileRef = 0E72374920460320006B0C7D /* ProfileHeaderView.xib */; };
......@@ -434,7 +433,6 @@
0E4909791FEAC9E1005CAA50 /* CallViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CallViewController.swift; sourceTree = "<group>"; };
0E49097B1FEACA4B005CAA50 /* CallViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CallViewModel.swift; sourceTree = "<group>"; };
0E63F1F3202907090001F248 /* Ring.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Ring.entitlements; sourceTree = "<group>"; };
0E67B5D52218E0FB001790D9 /* AccountProfileHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountProfileHelper.swift; sourceTree = "<group>"; };
0E68571020238546008B0717 /* ConversationNavigation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationNavigation.swift; sourceTree = "<group>"; };
0E6949781FA7E71C0029B60A /* BaseViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BaseViewController.swift; sourceTree = "<group>"; };
0E72374920460320006B0C7D /* ProfileHeaderView.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = ProfileHeaderView.xib; sourceTree = "<group>"; };
......@@ -1063,7 +1061,6 @@
0E0FF1AE1FC38CBC003898C2 /* ProfileDataHelper.swift */,
0E0FF1B61FC398B3003898C2 /* ConversationDataHepler.swift */,
0E0FF1B81FC398C5003898C2 /* InteractionDataHelper.swift */,
0E67B5D52218E0FB001790D9 /* AccountProfileHelper.swift */,
);
path = DBHelpers;
sourceTree = "<group>";
......@@ -1986,7 +1983,6 @@
0EE1B5501F75AD4700BA98EE /* VCardUtils.swift in Sources */,
0E49096E1FEAC0DE005CAA50 /* CallsService.swift in Sources */,
0273C2FF1E0C438F00CF00BA /* AccountAdapterDelegate.swift in Sources */,
0E67B5D62218E0FB001790D9 /* AccountProfileHelper.swift in Sources */,
1A2D19011F29353A00B2C785 /* MeDetailViewModel.swift in Sources */,
1A2D18A41F27EF5200B2C785 /* AppCoordinator.swift in Sources */,
1A2D18C31F29180700B2C785 /* AccountModel.swift in Sources */,
......
......@@ -47,10 +47,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
private let profileService = ProfilesService()
private var conversationManager: ConversationsManager?
private var interactionsManager: GeneratedInteractionsManager?
private let dbManager: DBManager = DBManager(profileHepler: ProfileDataHelper(),
conversationHelper: ConversationDataHelper(),
interactionHepler: InteractionDataHelper(),
accountProfileHelper: AccountProfileHelper())
private let voipRegistry = PKPushRegistry(queue: DispatchQueue.main)
......@@ -179,14 +175,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
self.conversationManager?
.prepareConversationsForAccount(accountId: currentAccount.id, accountUri: ringID)
}
do {
try self.dbManager.performMigrationIfNeeded()
} catch {
let time = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: time) {
self.appCoordinator.showDatabaseError()
}
}
}.disposed(by: self.disposeBag)
self.window?.rootViewController = self.appCoordinator.rootViewController
......@@ -250,6 +238,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
private func startDB() {
do {
let dbManager = DBManager(profileHepler: ProfileDataHelper(),
conversationHelper: ConversationDataHelper(),
interactionHepler: InteractionDataHelper())
try dbManager.start()
} catch {
let time = DispatchTime.now() + 1
......
......@@ -64,9 +64,8 @@ class CallViewModel: Stateable, ViewModel {
guard let call = self.call else {
return nil
}
return self.profileService.addAndGetProfile(ringId: call.participantRingId,
accountId: call.accountId,
isAccount: false)
return self.profileService.getProfile(ringId: call.participantRingId,
createIfNotexists: true)
.filter({ profile in
guard let photo = profile.photo else {
return false
......
......@@ -96,7 +96,8 @@ class ContactViewModel: ViewModel, Stateable {
self.profileImageData.value = imageData
})
.disposed(by: self.disposeBag)
self.profileService.getProfile(ringId: conversation.recipientRingId)
self.profileService.getProfile(ringId: conversation.recipientRingId,
createIfNotexists: false)
.subscribe(onNext: { [unowned self] profile in
if let alias = profile.alias, !alias.isEmpty {
self.displayName.value = alias
......
/*
* Copyright (C) 2017-2019 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 SQLite
typealias ProfileAccount = (
profileId: Int64,
accountId: String,
isAccount: Bool?
)
let table = RingDB.instance.tableAccountProfiles
let profileId = Expression<Int64>("profile_id")
let accountId = Expression<String>("account_id")
let isAccount = Expression<String?>("is_account")
final class AccountProfileHelper {
func createTable() throws {
guard let dataBase = RingDB.instance.ringDB else {
throw DataAccessError.datastoreConnectionError
}
do {
try dataBase.run(table.create(ifNotExists: true) { table in
table.column(profileId)
table.column(accountId)
table.column(isAccount)
table.foreignKey(profileId, references: RingDB.instance.tableProfiles, Expression<Int64>("id"), delete: .noAction)
})
} catch _ {
print("Table already exists")
}
}
func insert(item: ProfileAccount) {
guard let dataBase = RingDB.instance.ringDB else {
return
}
let isAccountString = item.isAccount.map { "\($0)" } ?? nil
let getQuery = table.filter((profileId == item.profileId) &&
(accountId == item.accountId) &&
(isAccount == isAccountString))
let insertQuery = table.insert(profileId <- item.profileId,
accountId <- item.accountId,
isAccount <- isAccountString)
do {
let rows = try dataBase.scalar(getQuery.count)
if rows > 0 {
return
}
try dataBase.run(insertQuery)
} catch _ {
}
}
}
This diff is collapsed.
......@@ -31,13 +31,11 @@ final class RingDB {
let ringDB: Connection?
private let log = SwiftyBeaver.self
private let dbName = "ring.db"
let dbVersion = 1
//tables
var tableProfiles = Table("profiles")
var tableConversations = Table("conversations")
var tableInteractionss = Table("interactions")
var tableAccountProfiles = Table("profiles_accounts")
private init() {
let path = NSSearchPathForDirectoriesInDomains(
......@@ -52,16 +50,3 @@ final class RingDB {
}
}
}
extension Connection {
public var userVersion: Int? {
get {
if let version = try? scalar("PRAGMA user_version"),
let intVersion = version as? Int64 {return Int(intVersion)}
return nil
}
set {
if let version = newValue {_ = try? run("PRAGMA user_version = \(version)")}
}
}
}
......@@ -48,7 +48,7 @@ class ContactRequestItem {
self.userName.value = contactRequest.ringId
self.profileImageData.value = self.contactRequest.vCard?.imageData
self.profileName.value = VCardUtils.getName(from: self.contactRequest.vCard)
profileService.getProfile(ringId: contactRequest.ringId)
profileService.getProfile(ringId: contactRequest.ringId, createIfNotexists: false)
.subscribe(onNext: { [weak self] profile in
if let photo = profile.photo,
let data = NSData(base64Encoded: photo,
......
......@@ -134,7 +134,8 @@ class ConversationViewModel: Stateable, ViewModel {
})
.disposed(by: disposeBag)
self.profileService.getProfile(ringId: contactRingId)
self.profileService.getProfile(ringId: contactRingId,
createIfNotexists: false)
.subscribe(onNext: { [unowned self] profile in
self.displayName.value = profile.alias
if let photo = profile.photo,
......
......@@ -87,8 +87,7 @@ class AccountsService: AccountAdapterDelegate {
fileprivate let responseStream = PublishSubject<ServiceEvent>()
let dbManager = DBManager(profileHepler: ProfileDataHelper(),
conversationHelper: ConversationDataHelper(),
interactionHepler: InteractionDataHelper(),
accountProfileHelper: AccountProfileHelper())
interactionHepler: InteractionDataHelper())
// MARK: - Public members
/**
......@@ -485,13 +484,8 @@ class AccountsService: AccountAdapterDelegate {
func registrationStateChanged(with response: RegistrationResponse) {
log.debug("RegistrationStateChanged.")
if let state = response.state,
state == Registered,
let account = self.getAccount(fromAccountId: response.accountId),
let jamiId = AccountModelHelper.init(withAccount: account).ringId {
dbManager.addAndGetProfileObservable(for: jamiId,
accountId: response.accountId,
isAccount: true)
if let state = response.state, state == Registered {
dbManager.profileObservable(for: response.accountId, createIfNotExists: true)
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.subscribe()
.disposed(by: self.disposeBag)
......
......@@ -271,25 +271,24 @@ class CallsService: CallsAdapterDelegate {
}
func didReceiveMessage(withCallId callId: String, fromURI uri: String, message: [String: String]) {
guard let call = self.call(callID: callId) else {return}
if message.keys.filter({ $0.hasPrefix(self.ringVCardMIMEType) }).first != nil {
var data = [String: Any]()
data[ProfileNotificationsKeys.ringID.rawValue] = uri
data[ProfileNotificationsKeys.accountId.rawValue] = call.accountId
data[ProfileNotificationsKeys.message.rawValue] = message
NotificationCenter.default.post(name: NSNotification.Name(ProfileNotifications.messageReceived.rawValue), object: nil, userInfo: data)
return
} else if let call = self.call(callID: callId) {
let accountId = call.accountId
let displayName = call.displayName
let registeredName = call.registeredName
let name = !displayName.isEmpty ? displayName : registeredName
var event = ServiceEvent(withEventType: .newIncomingMessage)
event.addEventInput(.content, value: message.values.first)
event.addEventInput(.peerUri, value: uri.replacingOccurrences(of: "@ring.dht", with: ""))
event.addEventInput(.name, value: name)
event.addEventInput(.accountId, value: accountId)
self.newMessagesStream.onNext(event)
}
let accountId = call.accountId
let displayName = call.displayName
let registeredName = call.registeredName
let name = !displayName.isEmpty ? displayName : registeredName
var event = ServiceEvent(withEventType: .newIncomingMessage)
event.addEventInput(.content, value: message.values.first)
event.addEventInput(.peerUri, value: uri.replacingOccurrences(of: "@ring.dht", with: ""))
event.addEventInput(.name, value: name)
event.addEventInput(.accountId, value: accountId)
self.newMessagesStream.onNext(event)
}
// swiftlint:enable cyclomatic_complexity
......
......@@ -43,7 +43,7 @@ class ContactsService {
fileprivate let responseStream = PublishSubject<ServiceEvent>()
var sharedResponseStream: Observable<ServiceEvent>
let dbManager = DBManager(profileHepler: ProfileDataHelper(), conversationHelper: ConversationDataHelper(), interactionHepler: InteractionDataHelper(), accountProfileHelper: AccountProfileHelper())
let dbManager = DBManager(profileHepler: ProfileDataHelper(), conversationHelper: ConversationDataHelper(), interactionHepler: InteractionDataHelper())
init(withContactsAdapter contactsAdapter: ContactsAdapter) {
self.contactsAdapter = contactsAdapter
......@@ -115,9 +115,7 @@ class ContactsService {
.createOrUpdateRingProfile(profileUri: contactRequest.ringId,
alias: name,
image: stringImage,
status: ProfileStatus.trusted,
accountId: account.id,
isAccount: false)
status: ProfileStatus.trusted)
var event = ServiceEvent(withEventType: .contactAdded)
event.addEventInput(.accountId, value: account.id)
event.addEventInput(.uri, value: contactRequest.ringId)
......@@ -322,7 +320,7 @@ extension ContactsService: ContactsAdapterDelegate {
}
func getProfileForUri(uri: String) ->Observable<Profile> {
return self.dbManager.getProfileObservable(for: uri)
return self.dbManager.profileObservable(for: uri, createIfNotExists: false)
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
}
}
......@@ -48,7 +48,7 @@ class ConversationsService {
return self.conversations.asObservable()
}()
let dbManager = DBManager(profileHepler: ProfileDataHelper(), conversationHelper: ConversationDataHelper(), interactionHepler: InteractionDataHelper(), accountProfileHelper: AccountProfileHelper())
let dbManager = DBManager(profileHepler: ProfileDataHelper(), conversationHelper: ConversationDataHelper(), interactionHepler: InteractionDataHelper())
init(withMessageAdapter adapter: MessagesAdapter) {
self.responseStream.disposed(by: disposeBag)
......@@ -155,7 +155,6 @@ class ConversationsService {
return Completable.create(subscribe: { [unowned self] completable in
self.messagesSemaphore.wait()
self.dbManager.saveMessage(for: toAccountUri,
accountId: toAccountId,
with: recipientRingId,
message: message,
incoming: message.incoming,
......@@ -206,7 +205,7 @@ class ConversationsService {
let message = MessageModel(withId: "", receivedDate: date, content: messageContent, author: accountRingId, incoming: false)
message.isGenerated = true
self.dbManager.saveMessage(for: accountRingId, accountId: accountId, with: contactRingId, message: message, incoming: false, interactionType: interactionType)
self.dbManager.saveMessage(for: accountRingId, with: contactRingId, message: message, incoming: false, interactionType: interactionType)
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.subscribe(onNext: { [unowned self] _ in
if shouldUpdateConversation {
......@@ -245,7 +244,7 @@ class ConversationsService {
message.isTransfer = true
self.messagesSemaphore.wait()
self.dbManager.saveMessage(for: accountRingId, accountId: accountId, with: contactRingId, message: message, incoming: isIncoming, interactionType: interactionType)
self.dbManager.saveMessage(for: accountRingId, with: contactRingId, message: message, incoming: isIncoming, interactionType: interactionType)
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.subscribe(onNext: { [unowned self] message in
self.dataTransferMessageMap[transferId] = message
......@@ -303,7 +302,7 @@ class ConversationsService {
}
func getProfile(uri: String) -> Observable<Profile> {
return self.dbManager.getProfileObservable(for: uri)
return self.dbManager.profileObservable(for: uri, createIfNotExists: false)
}
func clearHistory(conversation: ConversationModel, keepConversation: Bool) {
......
......@@ -94,7 +94,7 @@ public final class DataTransferService: DataTransferAdapterDelegate {
DataTransferAdapter.delegate = self
}
let dbManager = DBManager(profileHepler: ProfileDataHelper(), conversationHelper: ConversationDataHelper(), interactionHepler: InteractionDataHelper(), accountProfileHelper: AccountProfileHelper())
let dbManager = DBManager(profileHepler: ProfileDataHelper(), conversationHelper: ConversationDataHelper(), interactionHepler: InteractionDataHelper())
// MARK: public
......
......@@ -30,7 +30,6 @@ enum ProfileNotifications: String {
enum ProfileNotificationsKeys: String {
case ringID
case accountId
case message
}
......@@ -49,8 +48,7 @@ class ProfilesService {
let dbManager = DBManager(profileHepler: ProfileDataHelper(),
conversationHelper: ConversationDataHelper(),
interactionHepler: InteractionDataHelper(),
accountProfileHelper: AccountProfileHelper())
interactionHepler: InteractionDataHelper())
let disposeBag = DisposeBag()
......@@ -67,7 +65,7 @@ class ProfilesService {
guard let ringId = notification.userInfo?[ProfileNotificationsKeys.ringID.rawValue] as? String else {
return
}
self.updateProfileFor(ringId: ringId)
self.updateProfileFor(ringId: ringId, createIfNotexists: false)
}
// swiftlint:disable cyclomatic_complexity
......@@ -80,10 +78,6 @@ class ProfilesService {
return
}
guard let accountId = notification.userInfo?[ProfileNotificationsKeys.accountId.rawValue] as? String else {
return
}
if let vCardKey = message.keys.filter({ $0.hasPrefix(self.ringVCardMIMEType) }).first {
//Parse the key to get the number of parts and the current part number
......@@ -127,12 +121,12 @@ class ProfilesService {
//Build the vCard when all data are appended
if of == numberOfReceivedChunk {
self.buildVCardFromChunks(cardID: id, ringID: ringId, accountId: accountId)
self.buildVCardFromChunks(cardID: id, ringID: ringId)
}
}
}
private func buildVCardFromChunks(cardID: Int, ringID: String, accountId: String) {
private func buildVCardFromChunks(cardID: Int, ringID: String) {
guard let vcard = self.base64VCards[cardID] else {
return
}
......@@ -159,57 +153,30 @@ class ProfilesService {
.createOrUpdateRingProfile(profileUri: uri,
alias: name,
image: stringImage,
status: ProfileStatus.untrasted,
accountId: accountId,
isAccount: false)
self.updateProfileFor(ringId: uri)
status: ProfileStatus.untrasted)
self.updateProfileFor(ringId: uri, createIfNotexists: false)
}
}
private func addOrUpdatePrifileFor(ringId: String, accountId: String, isAccount: Bool) {
guard let profileObservable = self.profiles[ringId] else {
return
}
self.dbManager
.addAndGetProfileObservable(for: ringId, accountId: accountId, isAccount: isAccount)
.subscribe(onNext: {profile in
profileObservable.onNext(profile)
}).disposed(by: self.disposeBag)
}
private func updateProfileFor(ringId: String) {
private func updateProfileFor(ringId: String, createIfNotexists: Bool) {
guard let profileObservable = self.profiles[ringId] else {
return
}
self.dbManager
.getProfileObservable(for: ringId)
.profileObservable(for: ringId, createIfNotExists: createIfNotexists)
.subscribe(onNext: {profile in
profileObservable.onNext(profile)
}).disposed(by: self.disposeBag)
}
func addAndGetProfile(ringId: String,
accountId: String,
isAccount: Bool) -> Observable<Profile> {
if let profile = self.profiles[ringId] {
return profile.asObservable().share()
}
let profileObservable = ReplaySubject<Profile>.create(bufferSize: 1)
self.profiles[ringId] = profileObservable
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.addOrUpdatePrifileFor(ringId: ringId, accountId: accountId, isAccount: isAccount)
}
return profileObservable.share()
}
func getProfile(ringId: String) -> Observable<Profile> {
func getProfile(ringId: String, createIfNotexists: Bool) -> Observable<Profile> {
if let profile = self.profiles[ringId] {
return profile.asObservable().share()
}
let profileObservable = ReplaySubject<Profile>.create(bufferSize: 1)
self.profiles[ringId] = profileObservable
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.updateProfileFor(ringId: ringId)
self.updateProfileFor(ringId: ringId, createIfNotexists: createIfNotexists)
}
return profileObservable.share()
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment