Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Location sharing: Persist beacon info summaries to disk (PSF-1036) #1474

Merged
merged 20 commits into from
May 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
c7b873a
Podfile: Update for Swift compatibility and update Realm version.
SBiOSoftWhare May 24, 2022
40c4ed0
Podspec: Update Realm version to 10.26.0
SBiOSoftWhare May 24, 2022
d723c4b
Realm: Add Swift support file.
SBiOSoftWhare May 24, 2022
d7eaf7d
Realm: Add convenient Swift extension for transactions.
SBiOSoftWhare May 24, 2022
529b95b
MXBeaconAggregationsTests: Fix multiple fulfill issue.
SBiOSoftWhare May 24, 2022
91865cb
Update podfile.lock
SBiOSoftWhare May 24, 2022
e2420e9
MXBeaconInfo: Expose full init.
SBiOSoftWhare May 24, 2022
95f51da
MXBeaconInfoSummaryStoreProtocol: Add a method to get all summaries f…
SBiOSoftWhare May 24, 2022
92489e4
MXBeaconInfoSummaryMemoryStore: Update with new MXBeaconInfoSummarySt…
SBiOSoftWhare May 24, 2022
db0933f
Add equivalent Realm objects to represent MXBeaconInfoSummary in data…
SBiOSoftWhare May 24, 2022
3b004fd
MXBeaconAggregations: Improve beacon info summary updates in the stor…
SBiOSoftWhare May 24, 2022
bd1f56e
Add MXRealmBeaconMapper to convert convert `MXBeaconInfoSummary` to `…
SBiOSoftWhare May 24, 2022
a214418
Implement MXBeaconInfoSummaryRealmStore
SBiOSoftWhare May 24, 2022
9e29006
MXLocationService: Add method to get all beacon info summaries from a…
SBiOSoftWhare May 24, 2022
4994851
MXAggregations: Use MXBeaconInfoSummaryRealmStore.
SBiOSoftWhare May 24, 2022
4abbb2f
Update pbxproj
SBiOSoftWhare May 24, 2022
b0b402e
Update changes
SBiOSoftWhare May 24, 2022
7d25cb5
Realm+MatrixSDK: Remove wrong import.
SBiOSoftWhare May 24, 2022
51403ab
Move extensions to the same folder.
SBiOSoftWhare May 25, 2022
a296c4b
MXBeaconInfoSummaryRealmStore: Use shared container if possible to st…
SBiOSoftWhare May 30, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion MatrixSDK.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Pod::Spec.new do |s|

# Requirements for e2e encryption
ss.dependency 'OLMKit', '~> 3.2.5'
ss.dependency 'Realm', '10.16.0'
ss.dependency 'Realm', '10.26.0'
ss.dependency 'libbase58', '~> 0.1.4'
end

Expand Down
220 changes: 133 additions & 87 deletions MatrixSDK.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ public class MXBeaconAggregations: NSObject {
return self.beaconInfoSummaryStore.getAllBeaconInfoSummaries(inRoomWithId: roomId)
}

/// Get all MXBeaconInfoSummary for a user
public func getBeaconInfoSummaries(for userId: String) -> [MXBeaconInfoSummaryProtocol] {
return self.beaconInfoSummaryStore.getAllBeaconInfoSummaries(forUserId: userId)
}

/// Update a MXBeaconInfoSummary device id that belongs to the current user.
/// Enables to recognize that a beacon info has been started on the device
public func updateBeaconInfoSummary(with eventId: String, deviceId: String, inRoomWithId roomId: String) {
Expand All @@ -62,6 +67,7 @@ public class MXBeaconAggregations: NSObject {
}

if beaconInfoSummary.updateWithDeviceId(deviceId) {
self.beaconInfoSummaryStore.addOrUpdateBeaconInfoSummary(beaconInfoSummary, inRoomWithId: roomId)
self.notifyBeaconInfoSummaryListeners(ofRoomWithId: roomId, beaconInfoSummary: beaconInfoSummary)
}
}
Expand All @@ -87,6 +93,7 @@ public class MXBeaconAggregations: NSObject {
}

if beaconInfoSummary.updateWithLastBeacon(beacon) {
self.beaconInfoSummaryStore.addOrUpdateBeaconInfoSummary(beaconInfoSummary, inRoomWithId: roomId)
self.notifyBeaconInfoSummaryListeners(ofRoomWithId: roomId, beaconInfoSummary: beaconInfoSummary)
}
}
Expand Down Expand Up @@ -164,7 +171,6 @@ public class MXBeaconAggregations: NSObject {

if let beaconInfoSummary = beaconInfoSummary {
self.beaconInfoSummaryStore.addOrUpdateBeaconInfoSummary(beaconInfoSummary, inRoomWithId: roomId)

self.notifyBeaconInfoSummaryListeners(ofRoomWithId: roomId, beaconInfoSummary: beaconInfoSummary)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,22 @@ public class MXBeaconInfoSummaryMemoryStore: NSObject, MXBeaconInfoSummaryStoreP
}
}

public func getAllBeaconInfoSummaries(forUserId userId: String) -> [MXBeaconInfoSummary] {

var userSummaries: [MXBeaconInfoSummary] = []

for (_, roomSummaries) in self.beaconInfoSummaries {

let userRoomSummaries = roomSummaries.filter { summary in
summary.userId == userId
}

userSummaries.append(contentsOf: userRoomSummaries)
}

return userSummaries
}

public func getAllBeaconInfoSummaries(inRoomWithId roomId: String) -> [MXBeaconInfoSummary] {
return self.beaconInfoSummaries[roomId] ?? []
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ import Foundation
/// Get all MXBeaconInfoSummary in a room
func getAllBeaconInfoSummaries(inRoomWithId roomId: String) -> [MXBeaconInfoSummary]

/// Get all MXBeaconInfoSummary for a user
func getAllBeaconInfoSummaries(forUserId userId: String) -> [MXBeaconInfoSummary]

/// Delete all MXBeaconInfoSummary in a room
func deleteAllBeaconInfoSummaries(inRoomWithId roomId: String)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,288 @@
//
// Copyright 2022 The Matrix.org Foundation C.I.C
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import Foundation
import Realm

@objcMembers
public class MXBeaconInfoSummaryRealmStore: NSObject {

// MARK: - Constants

private enum Database {
static let folderName = "BeaconInfoSummaries"
static let filename = "BeaconInfoSummaries"

// TODO: Use a private modulemap to import private Objective-C files in Swift. To be able to use `MXRealmHelper` here.
static let fileExtension = "realm"
}

private enum BeaconInfoSummaryPredicate {

static func identifier(_ identifier: String) -> NSPredicate {
return NSPredicate(format: "%K = %@",
#keyPath(MXRealmBeaconInfoSummary.identifier), identifier)
}

static func room(_ roomId: String) -> NSPredicate {
return NSPredicate(format: "%K = %@",
#keyPath(MXRealmBeaconInfoSummary.roomId), roomId)
}

static func user(_ userId: String) -> NSPredicate {
return NSPredicate(format: "%K = %@",
#keyPath(MXRealmBeaconInfoSummary.userId), userId)
}
}

// MARK: - Properties

private unowned let session: MXSession
private let mapper: MXRealmBeaconMapper

private var realm: RLMRealm? {
guard let userId = self.session.myUserId else {
return nil
}
return self.realmStore(for: userId)
}

// MARK: - Setup

public init(session: MXSession) {
self.session = session
self.mapper = MXRealmBeaconMapper(session: session)

super.init()
}

// MARK: - Private

private func realmStore(for userId: String) -> RLMRealm? {
do {
let configuration = try self.realmConfiguration(for: userId)

let realm = try RLMRealm(configuration: configuration)

return realm
} catch {

MXLog.error("[MXBeaconInfoSummaryRealmStore] failed to create Realm store with error: \(error)")
return nil
}
}

private func realmConfiguration(for userId: String) throws -> RLMRealmConfiguration {
let realmConfiguration = RLMRealmConfiguration.default()

let realmFileURL = try self.getStoreURL(for: userId)

realmConfiguration.fileURL = realmFileURL
realmConfiguration.deleteRealmIfMigrationNeeded = true

// Manage only our objects in this realm
realmConfiguration.objectClasses = [
MXRealmBeaconInfoSummary.self,
MXRealmBeaconInfo.self,
MXRealmBeacon.self
]

return realmConfiguration
}

private func getStoreURL(for userId: String) throws -> URL {

let userDirectoryURL: URL

do {

let rootDirectoryURL: URL

// Store the Realm file in the shared container if possible
if let containerURL = FileManager.default.applicationGroupContainerURL() {
rootDirectoryURL = containerURL
} else {
rootDirectoryURL = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
}

userDirectoryURL = rootDirectoryURL.appendingPathComponent(userId)

} catch {
MXLog.error("[MXBeaconInfoSummaryRealmStore] Fail to get user directory")

throw error
}

let realmFileFolderURL = userDirectoryURL.appendingPathComponent(Database.folderName, isDirectory: true)
let realmFileURL = realmFileFolderURL.appendingPathComponent(Database.filename, isDirectory: false).appendingPathExtension(Database.fileExtension)

do {
try FileManager.default.createDirectory(at: realmFileFolderURL, withIntermediateDirectories: true, attributes: nil)
} catch {
MXLog.error("[MXBeaconInfoSummaryRealmStore] Fail to create Realm folder \(realmFileFolderURL) with error: \(error)")
throw error
}

return realmFileURL
}

private func realmBeaconInfoSummaryResults(in realm: RLMRealm, with roomId: String) -> RLMResults<MXRealmBeaconInfoSummary> {
let roomPredicate = BeaconInfoSummaryPredicate.room(roomId)
return self.realmBeaconInfoSummaryResults(in: realm, with: roomPredicate)
}

private func realmBeaconInfoSummaryResults(in realm: RLMRealm, with predicate: NSPredicate) -> RLMResults<MXRealmBeaconInfoSummary> {

guard let realmSummaries = MXRealmBeaconInfoSummary.objects(in: realm, with: predicate) as? RLMResults<MXRealmBeaconInfoSummary> else {
fatalError()
}
return realmSummaries
}

private func beaconInfoSummaries(from realmBeaconInfoSummaryResults: RLMResults<MXRealmBeaconInfoSummary>) -> [MXBeaconInfoSummary] {

var summaries: [MXBeaconInfoSummary] = []

for realmSummary in realmBeaconInfoSummaryResults {

if let realmBeaconInfoSummary = realmSummary as? MXRealmBeaconInfoSummary, let summary = self.mapper.beaconInfoSummary(from: realmBeaconInfoSummary) {
summaries.append(summary)
}
}

return summaries
}
}

// MARK: - MXBeaconInfoSummaryStoreProtocol
extension MXBeaconInfoSummaryRealmStore: MXBeaconInfoSummaryStoreProtocol {

public func addOrUpdateBeaconInfoSummary(_ beaconInfoSummary: MXBeaconInfoSummary, inRoomWithId roomId: String) {

guard let realm = self.realm else {
return
}

do {
try realm.mx_transaction(name: "[MXBeaconInfoSummaryRealmStore] addOrUpdateBeaconInfoSummary") {
let realmBeaconInfoSummary = self.mapper.realmBeaconInfoSummary(from: beaconInfoSummary)
realm.addOrUpdate(realmBeaconInfoSummary)
}
} catch {
MXLog.error("[MXBeaconInfoSummaryRealmStore] addOrUpdateBeaconInfoSummary failed with error: \(error)")
}
}

public func getBeaconInfoSummary(withIdentifier identifier: String, inRoomWithId roomId: String) -> MXBeaconInfoSummary? {

guard let realm = self.realm else {
return nil
}

let identifierPredicate = BeaconInfoSummaryPredicate.identifier(identifier)
let roomPredicate = BeaconInfoSummaryPredicate.room(roomId)

let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [identifierPredicate, roomPredicate])

guard let realmBeaconInfoSummary = self.realmBeaconInfoSummaryResults(in: realm, with: predicate).firstObject() else {
return nil
}

return self.mapper.beaconInfoSummary(from: realmBeaconInfoSummary)
}

public func getBeaconInfoSummary(withUserId userId: String, description: String?, timeout: UInt64, timestamp: UInt64, inRoomWithId roomId: String) -> MXBeaconInfoSummary? {

guard let realm = self.realm else {
return nil
}

let roomPredicate = BeaconInfoSummaryPredicate.room(roomId)

let userPredicate = BeaconInfoSummaryPredicate.user(userId)

let timeoutPredicate = NSPredicate(format: "%K = %ld",
#keyPath(MXRealmBeaconInfoSummary.beaconInfo.timeout), Int(timeout))

let timestampPredicate = NSPredicate(format: "%K = %ld", #keyPath(MXRealmBeaconInfoSummary.beaconInfo.timestamp), Int(timestamp))

let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [roomPredicate, userPredicate, timeoutPredicate, timestampPredicate])

let summaries = self.realmBeaconInfoSummaryResults(in: realm, with: predicate)


guard let realmBeaconInfoSummary = summaries.firstObject() else {
return nil
}

return self.mapper.beaconInfoSummary(from: realmBeaconInfoSummary)
}

public func getAllBeaconInfoSummaries(forUserId userId: String) -> [MXBeaconInfoSummary] {

guard let realm = self.realm else {
return []
}

let userPredicate = BeaconInfoSummaryPredicate.user(userId)

let realmSummaries = self.realmBeaconInfoSummaryResults(in: realm, with: userPredicate)

return self.beaconInfoSummaries(from: realmSummaries)
}

public func getAllBeaconInfoSummaries(inRoomWithId roomId: String) -> [MXBeaconInfoSummary] {

guard let realm = self.realm else {
return []
}

let realmSummaries = self.realmBeaconInfoSummaryResults(in: realm, with: roomId)

return self.beaconInfoSummaries(from: realmSummaries)
}

public func deleteAllBeaconInfoSummaries(inRoomWithId roomId: String) {

guard let realm = self.realm else {
return
}

do {
try realm.mx_transaction(name: "[MXBeaconInfoSummaryRealmStore] deleteAllBeaconInfoSummaries inRoomWithId") {
let realmBeaconInfoSummaries = self.realmBeaconInfoSummaryResults(in: realm, with: roomId)
realm.deleteObjects(realmBeaconInfoSummaries)
}
} catch {
MXLog.error("[MXBeaconInfoSummaryRealmStore] deleteAllBeaconInfoSummaries failed with error: \(error)")
}
}

public func deleteAllBeaconInfoSummaries() {

guard let realm = self.realm else {
return
}

do {
try realm.mx_transaction(name: "[MXBeaconInfoSummaryRealmStore] deleteAllBeaconInfoSummaries") {
realm.deleteAllObjects()
}
} catch {
MXLog.error("[MXBeaconInfoSummaryRealmStore] Failed to delete all objects: \(error)")
}
}
}
Loading