Renamed GRDBStorage to Storage (no use having the prefix anymore since the old DB is deprecated)

This commit is contained in:
Morgan Pretty 2022-07-01 13:08:45 +10:00
parent eb0118ac10
commit 8cf2a57fcc
101 changed files with 358 additions and 358 deletions

View File

@ -596,7 +596,7 @@
FD17D79927F40AB800122BE0 /* _003_YDBToGRDBMigration.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD17D79827F40AB800122BE0 /* _003_YDBToGRDBMigration.swift */; };
FD17D79C27F40B2E00122BE0 /* SMKLegacy.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD17D79B27F40B2E00122BE0 /* SMKLegacy.swift */; };
FD17D7A027F40CC800122BE0 /* _001_InitialSetupMigration.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD17D79F27F40CC800122BE0 /* _001_InitialSetupMigration.swift */; };
FD17D7A127F40D2500122BE0 /* GRDBStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD28A4F527EAD44C00FF65E7 /* GRDBStorage.swift */; };
FD17D7A127F40D2500122BE0 /* Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD28A4F527EAD44C00FF65E7 /* Storage.swift */; };
FD17D7A227F40F0500122BE0 /* _001_InitialSetupMigration.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD17D79527F3E04600122BE0 /* _001_InitialSetupMigration.swift */; };
FD17D7A427F40F8100122BE0 /* _003_YDBToGRDBMigration.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD17D7A327F40F8100122BE0 /* _003_YDBToGRDBMigration.swift */; };
FD17D7A727F41AF000122BE0 /* SSKLegacy.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD17D7A627F41AF000122BE0 /* SSKLegacy.swift */; };
@ -1686,7 +1686,7 @@
FD1C98E3282E3C5B00B76F9E /* UINavigationBar+Utilities.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UINavigationBar+Utilities.swift"; sourceTree = "<group>"; };
FD245C612850664300B966DD /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = "<group>"; };
FD28A4F327EA79F800FF65E7 /* BlockListUIUtils.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BlockListUIUtils.swift; sourceTree = "<group>"; };
FD28A4F527EAD44C00FF65E7 /* GRDBStorage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBStorage.swift; sourceTree = "<group>"; };
FD28A4F527EAD44C00FF65E7 /* Storage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Storage.swift; sourceTree = "<group>"; };
FD3AABE828306BBD00E5099A /* ThreadPickerViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThreadPickerViewModel.swift; sourceTree = "<group>"; };
FD3C905B27E3FBEF00CD579F /* BatchRequestInfoSpec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BatchRequestInfoSpec.swift; sourceTree = "<group>"; };
FD3C905F27E410F700CD579F /* FileUploadResponseSpec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileUploadResponseSpec.swift; sourceTree = "<group>"; };
@ -2306,7 +2306,7 @@
FD17D7B427F51E6700122BE0 /* Types */,
FD17D7BB27F51F5C00122BE0 /* Utilities */,
FD848B9928442CE6000E298B /* StorageError.swift */,
FD28A4F527EAD44C00FF65E7 /* GRDBStorage.swift */,
FD28A4F527EAD44C00FF65E7 /* Storage.swift */,
C33FDBAB255A581500E217F9 /* OWSFileSystem.h */,
C33FDA8E255A57FD00E217F9 /* OWSFileSystem.m */,
C33FDBBC255A581600E217F9 /* SSKKeychainStorage.swift */,
@ -5033,7 +5033,7 @@
C33FDEF8255A656D00E217F9 /* Promise+Delaying.swift in Sources */,
7BD477A827EC39F5004E2822 /* Atomic.swift in Sources */,
B8BC00C0257D90E30032E807 /* General.swift in Sources */,
FD17D7A127F40D2500122BE0 /* GRDBStorage.swift in Sources */,
FD17D7A127F40D2500122BE0 /* Storage.swift in Sources */,
FD5D201E27B0D87C00FEA984 /* SessionId.swift in Sources */,
C32C5A24256DB7DB003C73A2 /* SNUserDefaults.swift in Sources */,
C3BBE0A72554D4DE0050F1E3 /* Promise+Retrying.swift in Sources */,

View File

@ -227,7 +227,7 @@ public final class SessionCall: CurrentCallProtocol, WebRTCSessionDelegate {
in: thread
)
.done { [weak self] _ in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
self?.webRTCSession.sendOffer(db, to: sessionId)
}
@ -258,7 +258,7 @@ public final class SessionCall: CurrentCallProtocol, WebRTCSessionDelegate {
webRTCSession.hangUp()
GRDBStorage.shared.writeAsync { [weak self] db in
Storage.shared.writeAsync { [weak self] db in
try self?.webRTCSession.endCall(db, with: sessionId)
}
@ -273,7 +273,7 @@ public final class SessionCall: CurrentCallProtocol, WebRTCSessionDelegate {
let duration: TimeInterval = self.duration
let hasStartedConnecting: Bool = self.hasStartedConnecting
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
guard let interaction: Interaction = try? Interaction.fetchOne(db, id: callInteractionId) else {
return
}
@ -396,7 +396,7 @@ public final class SessionCall: CurrentCallProtocol, WebRTCSessionDelegate {
let sessionId: String = self.sessionId
let webRTCSession: WebRTCSession = self.webRTCSession
GRDBStorage.shared
Storage.shared
.read { db in webRTCSession.sendOffer(db, to: sessionId, isRestartingICEConnection: true) }
.retainUntilComplete()
}

View File

@ -8,7 +8,7 @@ extension SessionCallManager {
public func startCallAction() -> Bool {
guard let call: CurrentCallProtocol = self.currentCall else { return false }
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
call.startSessionCall(db)
}

View File

@ -170,7 +170,7 @@ public final class SessionCallManager: NSObject, CallManagerProtocol {
}
return
}
guard let call: SessionCall = GRDBStorage.shared.read({ db in SessionCall(db, for: caller, uuid: uuid, mode: mode) }) else {
guard let call: SessionCall = Storage.shared.read({ db in SessionCall(db, for: caller, uuid: uuid, mode: mode) }) else {
return
}

View File

@ -92,7 +92,7 @@ final class EditClosedGroupVC: BaseVC, UITableViewDataSource, UITableViewDelegat
let threadId: String = self.threadId
GRDBStorage.shared.read { [weak self] db in
Storage.shared.read { [weak self] db in
self?.userPublicKey = getUserHexEncodedPublicKey(db)
self?.name = try ClosedGroup
.select(.name)
@ -321,7 +321,7 @@ final class EditClosedGroupVC: BaseVC, UITableViewDataSource, UITableViewDelegat
.map { $0.profileId }
.asSet()
) { [weak self] selectedUserIds in
GRDBStorage.shared.read { [weak self] db in
Storage.shared.read { [weak self] db in
let selectedGroupMembers: [GroupMemberDisplayInfo] = try Profile
.filter(selectedUserIds.contains(Profile.Columns.id))
.fetchAll(db)
@ -416,7 +416,7 @@ final class EditClosedGroupVC: BaseVC, UITableViewDataSource, UITableViewDelegat
}
ModalActivityIndicatorViewController.present(fromViewController: navigationController) { _ in
GRDBStorage.shared
Storage.shared
.writeAsync { db in
if !updatedMemberIds.contains(userPublicKey) {
return try MessageSender.leave(db, groupPublicKey: threadId)

View File

@ -196,12 +196,12 @@ final class NewClosedGroupVC: BaseVC, UITableViewDataSource, UITableViewDelegate
let selectedContacts = self.selectedContacts
let message: String? = (selectedContacts.count > 20) ? "Please wait while the group is created..." : nil
ModalActivityIndicatorViewController.present(fromViewController: navigationController!, message: message) { [weak self] _ in
GRDBStorage.shared
Storage.shared
.writeAsync { db in
try MessageSender.createClosedGroup(db, name: name, members: selectedContacts)
}
.done(on: DispatchQueue.main) { thread in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
try? MessageSender.syncConfiguration(db, forceSyncNow: true).retainUntilComplete()
}

View File

@ -57,7 +57,7 @@ extension ConversationSearchController: UISearchResultsUpdating {
}
let threadId: String = self.threadId
let results: [Int64] = GRDBStorage.shared.read { db -> [Int64] in
let results: [Int64] = Storage.shared.read { db -> [Int64] in
try Interaction.idsForTermWithin(
threadId: threadId,
pattern: try SessionThreadViewModel.pattern(db, searchTerm: searchText)

View File

@ -54,7 +54,7 @@ extension ConversationVC:
@objc func startCall(_ sender: Any?) {
guard SessionCall.isEnabled else { return }
guard GRDBStorage.shared[.areCallsEnabled] else {
guard Storage.shared[.areCallsEnabled] else {
let callPermissionRequestModal = CallPermissionRequestModal()
self.navigationController?.present(callPermissionRequestModal, animated: true, completion: nil)
return
@ -67,7 +67,7 @@ extension ConversationVC:
guard AVAudioSession.sharedInstance().recordPermission == .granted else { return }
guard self.viewModel.threadData.threadVariant == .contact else { return }
guard AppEnvironment.shared.callManager.currentCall == nil else { return }
guard let call: SessionCall = GRDBStorage.shared.read({ db in SessionCall(db, for: threadId, uuid: UUID().uuidString.lowercased(), mode: .offer, outgoing: true) }) else {
guard let call: SessionCall = Storage.shared.read({ db in SessionCall(db, for: threadId, uuid: UUID().uuidString.lowercased(), mode: .offer, outgoing: true) }) else {
return
}
@ -92,7 +92,7 @@ extension ConversationVC:
self.blockedBanner.alpha = 0
},
completion: { _ in
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try Contact
.filter(id: publicKey)
.updateAll(db, Contact.Columns.isBlocked.set(to: true))
@ -354,7 +354,7 @@ extension ConversationVC:
timestampMs: (sentTimestampMs - 1) // Set 1ms earlier as this is used for sorting
)
.done { [weak self] _ in
GRDBStorage.shared.writeAsync(
Storage.shared.writeAsync(
updates: { db in
guard let thread: SessionThread = try SessionThread.fetchOne(db, id: threadId) else {
return
@ -451,7 +451,7 @@ extension ConversationVC:
timestampMs: (sentTimestampMs - 1) // Set 1ms earlier as this is used for sorting
)
.done { [weak self] _ in
GRDBStorage.shared.writeAsync(
Storage.shared.writeAsync(
updates: { db in
guard let thread: SessionThread = try SessionThread.fetchOne(db, id: threadId) else {
return
@ -509,14 +509,14 @@ extension ConversationVC:
self?.resetMentions()
}
if GRDBStorage.shared[.playNotificationSoundInForeground] {
if Storage.shared[.playNotificationSoundInForeground] {
let soundID = Preferences.Sound.systemSoundId(for: .messageSent, quiet: true)
AudioServicesPlaySystemSound(soundID)
}
let threadId: String = self.viewModel.threadData.threadId
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
TypingIndicators.didStopTyping(db, threadId: threadId, direction: .outgoing)
_ = try SessionThread
@ -542,7 +542,7 @@ extension ConversationVC:
let threadVariant: SessionThread.Variant = self.viewModel.threadData.threadVariant
let threadIsMessageRequest: Bool = (self.viewModel.threadData.threadIsMessageRequest == true)
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
TypingIndicators.didStartTyping(
db,
threadId: threadId,
@ -760,7 +760,7 @@ extension ConversationVC:
let threadId: String = self.viewModel.threadData.threadId
// Retry downloading the failed attachment
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
JobRunner.add(
db,
job: Job(
@ -845,7 +845,7 @@ extension ConversationVC:
case .textOnlyMessage:
if let quote: Quote = cellViewModel.quote {
// Scroll to the original quoted message
let maybeOriginalInteractionId: Int64? = GRDBStorage.shared.read { db in
let maybeOriginalInteractionId: Int64? = Storage.shared.read { db in
try quote.originalInteraction
.select(.id)
.asRequest(of: Int64.self)
@ -920,7 +920,7 @@ extension ConversationVC:
func startThread(with sessionId: String, openGroupServer: String?, openGroupPublicKey: String?) {
guard SessionId.Prefix(from: sessionId) == .blinded else {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try SessionThread.fetchOrCreate(db, id: sessionId, variant: .contact)
}
@ -936,7 +936,7 @@ extension ConversationVC:
return
}
let targetThreadId: String? = GRDBStorage.shared.write { db in
let targetThreadId: String? = Storage.shared.write { db in
let lookup: BlindedIdLookup = try BlindedIdLookup
.fetchOrCreate(
db,
@ -968,14 +968,14 @@ extension ConversationVC:
let sheet = UIAlertController(title: cellViewModel.mostRecentFailureText, message: nil, preferredStyle: .actionSheet)
sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
sheet.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { _ in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
try Interaction
.filter(id: cellViewModel.id)
.deleteAll(db)
}
}))
sheet.addAction(UIAlertAction(title: "Resend", style: .default, handler: { _ in
GRDBStorage.shared.writeAsync { [weak self] db in
Storage.shared.writeAsync { [weak self] db in
guard
let threadId: String = self?.viewModel.threadData.threadId,
let interaction: Interaction = try? Interaction.fetchOne(db, id: cellViewModel.id),
@ -1094,7 +1094,7 @@ extension ConversationVC:
.then { _ -> Promise<Void> in request }
.done { _ in
// Delete the interaction (and associated data) from the database
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
_ = try Interaction
.filter(id: cellViewModel.id)
.deleteAll(db)
@ -1117,7 +1117,7 @@ extension ConversationVC:
// Handle open group messages the old way
case .openGroup:
// If it's an incoming message the user must have moderator status
let result: (openGroupServerMessageId: Int64?, openGroup: OpenGroup?)? = GRDBStorage.shared.read { db -> (Int64?, OpenGroup?) in
let result: (openGroupServerMessageId: Int64?, openGroup: OpenGroup?)? = Storage.shared.read { db -> (Int64?, OpenGroup?) in
(
try Interaction
.select(.openGroupServerMessageId)
@ -1143,7 +1143,7 @@ extension ConversationVC:
// Delete the message from the open group
deleteRemotely(
from: self,
request: GRDBStorage.shared.read { db in
request: Storage.shared.read { db in
OpenGroupAPI.messageDelete(
db,
id: openGroupServerMessageId,
@ -1157,7 +1157,7 @@ extension ConversationVC:
}
case .contact, .closedGroup:
let serverHash: String? = GRDBStorage.shared.read { db -> String? in
let serverHash: String? = Storage.shared.read { db -> String? in
try Interaction
.select(.serverHash)
.filter(id: cellViewModel.id)
@ -1174,7 +1174,7 @@ extension ConversationVC:
// For incoming interactions or interactions with no serverHash just delete them locally
guard cellViewModel.variant == .standardOutgoing, let serverHash: String = serverHash else {
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
_ = try Interaction
.filter(id: cellViewModel.id)
.deleteAll(db)
@ -1197,7 +1197,7 @@ extension ConversationVC:
let alertVC = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
alertVC.addAction(UIAlertAction(title: "delete_message_for_me".localized(), style: .destructive) { [weak self] _ in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
_ = try Interaction
.filter(id: cellViewModel.id)
.deleteAll(db)
@ -1230,7 +1230,7 @@ extension ConversationVC:
)
.map { _ in () }
) { [weak self] in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
guard let thread: SessionThread = try SessionThread.fetchOne(db, id: threadId) else {
return
}
@ -1302,7 +1302,7 @@ extension ConversationVC:
let threadId: String = self.viewModel.threadData.threadId
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
guard let thread: SessionThread = try SessionThread.fetchOne(db, id: threadId) else { return }
try MessageSender.send(
@ -1326,7 +1326,7 @@ extension ConversationVC:
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak self] _ in
GRDBStorage.shared
Storage.shared
.read { db -> Promise<Void> in
guard let openGroup: OpenGroup = try OpenGroup.fetchOne(db, id: threadId) else {
return Promise(error: StorageError.objectNotFound)
@ -1365,7 +1365,7 @@ extension ConversationVC:
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak self] _ in
GRDBStorage.shared
Storage.shared
.read { db -> Promise<Void> in
guard let openGroup: OpenGroup = try OpenGroup.fetchOne(db, id: threadId) else {
return Promise(error: StorageError.objectNotFound)
@ -1650,7 +1650,7 @@ extension ConversationVC {
// (it'll be updated with correct profile info if they accept the message request so this
// shouldn't cause weird behaviours)
guard
let approvalData: (contact: Contact, thread: SessionThread?) = GRDBStorage.shared.read({ db in
let approvalData: (contact: Contact, thread: SessionThread?) = Storage.shared.read({ db in
return (
Contact.fetchOrCreate(db, id: threadId),
try SessionThread.fetchOne(db, id: threadId)
@ -1683,7 +1683,7 @@ extension ConversationVC {
return promise
.then { _ -> Promise<Void> in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
try MessageSender.sendNonDurably(
db,
message: messageRequestResponse,
@ -1700,7 +1700,7 @@ extension ConversationVC {
}
.map { _ in
// Default 'didApproveMe' to true for the person approving the message request
GRDBStorage.shared.writeAsync(
Storage.shared.writeAsync(
updates: { db in
try approvalData.contact
.with(
@ -1783,7 +1783,7 @@ extension ConversationVC {
)
alertVC.addAction(UIAlertAction(title: "TXT_DELETE_TITLE".localized(), style: .destructive) { _ in
// Delete the request
GRDBStorage.shared.writeAsync(
Storage.shared.writeAsync(
updates: { db in
// Update the contact
_ = try Contact

View File

@ -308,7 +308,7 @@ final class ConversationVC: BaseVC, OWSConversationSettingsViewDelegate, Convers
init(threadId: String, threadVariant: SessionThread.Variant, focusedInteractionId: Int64? = nil) {
self.viewModel = ConversationViewModel(threadId: threadId, threadVariant: threadVariant, focusedInteractionId: focusedInteractionId)
GRDBStorage.shared.addObserver(viewModel.pagedDataObserver)
Storage.shared.addObserver(viewModel.pagedDataObserver)
super.init(nibName: nil, bundle: nil)
}
@ -472,7 +472,7 @@ final class ConversationVC: BaseVC, OWSConversationSettingsViewDelegate, Convers
private func startObservingChanges() {
// Start observing for data changes
dataChangeObservable = GRDBStorage.shared.start(
dataChangeObservable = Storage.shared.start(
viewModel.observableThreadData,
onError: { _ in },
onChange: { [weak self] maybeThreadData in
@ -482,7 +482,7 @@ final class ConversationVC: BaseVC, OWSConversationSettingsViewDelegate, Convers
guard
let sessionId: String = self?.viewModel.threadData.threadId,
SessionId.Prefix(from: sessionId) == .blinded,
let blindedLookup: BlindedIdLookup = GRDBStorage.shared.read({ db in
let blindedLookup: BlindedIdLookup = Storage.shared.read({ db in
try BlindedIdLookup
.filter(id: sessionId)
.fetchOne(db)
@ -496,13 +496,13 @@ final class ConversationVC: BaseVC, OWSConversationSettingsViewDelegate, Convers
// Stop observing changes
self?.stopObservingChanges()
GRDBStorage.shared.removeObserver(self?.viewModel.pagedDataObserver)
Storage.shared.removeObserver(self?.viewModel.pagedDataObserver)
// Swap the observing to the updated thread
self?.viewModel.swapToThread(updatedThreadId: unblindedId)
// Start observing changes again
GRDBStorage.shared.addObserver(self?.viewModel.pagedDataObserver)
Storage.shared.addObserver(self?.viewModel.pagedDataObserver)
self?.startObservingChanges()
return
}

View File

@ -64,7 +64,7 @@ public class ConversationViewModel: OWSAudioPlayerDelegate {
let targetInteractionId: Int64? = {
if let focusedInteractionId: Int64 = focusedInteractionId { return focusedInteractionId }
return GRDBStorage.shared.read { db in
return Storage.shared.read { db in
let interaction: TypedTableAlias<Interaction> = TypedTableAlias()
return try Interaction
@ -109,7 +109,7 @@ public class ConversationViewModel: OWSAudioPlayerDelegate {
threadVariant: self.initialThreadVariant,
currentUserIsClosedGroupMember: (self.initialThreadVariant != .closedGroup ?
nil :
GRDBStorage.shared.read { db in
Storage.shared.read { db in
try GroupMember
.filter(GroupMember.Columns.groupId == self.threadId)
.filter(GroupMember.Columns.profileId == getUserHexEncodedPublicKey(db))
@ -265,7 +265,7 @@ public class ConversationViewModel: OWSAudioPlayerDelegate {
}
if !pendingAttachmentsToDownload.isEmpty {
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
pendingAttachmentsToDownload.forEach { attachment, interactionId in
JobRunner.add(
db,
@ -339,7 +339,7 @@ public class ConversationViewModel: OWSAudioPlayerDelegate {
public func mentions(for query: String = "") -> [MentionInfo] {
let threadData: SessionThreadViewModel = self.threadData
let results: [MentionInfo] = GRDBStorage.shared
let results: [MentionInfo] = Storage.shared
.read { db -> [MentionInfo] in
let userPublicKey: String = getUserHexEncodedPublicKey(db)
@ -447,7 +447,7 @@ public class ConversationViewModel: OWSAudioPlayerDelegate {
// MARK: - Functions
public func updateDraft(to draft: String) {
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
try SessionThread
.filter(id: self.threadId)
.updateAll(db, SessionThread.Columns.messageDraft.set(to: draft))
@ -460,7 +460,7 @@ public class ConversationViewModel: OWSAudioPlayerDelegate {
let threadId: String = self.threadData.threadId
let trySendReadReceipt: Bool = (self.threadData.threadIsMessageRequest == false)
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
try Interaction.markAsRead(
db,
interactionId: lastInteractionId,

View File

@ -250,7 +250,7 @@ final class InputView: UIView, InputViewButtonDelegate, InputTextViewDelegate, M
// Suggest that the user enable link previews if they haven't already and we haven't
// told them about link previews yet
let text = inputTextView.text!
let areLinkPreviewsEnabled: Bool = GRDBStorage.shared[.areLinkPreviewsEnabled]
let areLinkPreviewsEnabled: Bool = Storage.shared[.areLinkPreviewsEnabled]
if
!LinkPreview.allPreviewUrls(forMessageBodyText: text).isEmpty &&

View File

@ -135,7 +135,7 @@ final class CallMessageCell: MessageCell {
let shouldShowInfoIcon: Bool = (
messageInfo.state == .permissionDenied &&
!GRDBStorage.shared[.areCallsEnabled]
!Storage.shared[.areCallsEnabled]
)
infoImageViewWidthConstraint.constant = (shouldShowInfoIcon ? CallMessageCell.iconSize : 0)
infoImageViewHeightConstraint.constant = (shouldShowInfoIcon ? CallMessageCell.iconSize : 0)
@ -159,7 +159,7 @@ final class CallMessageCell: MessageCell {
else { return }
// Should only be tappable if the info icon is visible
guard messageInfo.state == .permissionDenied && !GRDBStorage.shared[.areCallsEnabled] else { return }
guard messageInfo.state == .permissionDenied && !Storage.shared[.areCallsEnabled] else { return }
self.delegate?.handleItemTapped(cellViewModel, gestureRecognizer: gestureRecognizer)
}

View File

@ -78,7 +78,7 @@ final class BlockedModal: Modal {
@objc private func unblock() {
let publicKey: String = self.publicKey
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
try Contact
.filter(id: publicKey)
.updateAll(db, Contact.Columns.isBlocked.set(to: true))

View File

@ -76,7 +76,7 @@ final class CallModal: Modal {
// MARK: - Interaction
@objc private func enable() {
GRDBStorage.shared.writeAsync { db in db[.areCallsEnabled] = true }
Storage.shared.writeAsync { db in db[.areCallsEnabled] = true }
presentingViewController?.dismiss(animated: true, completion: nil)
onCallEnabled()
}

View File

@ -90,7 +90,7 @@ final class DownloadAttachmentModal: Modal {
@objc private func trust() {
guard let profileId: String = profile?.id else { return }
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
try Contact
.filter(id: profileId)
.updateAll(db, Contact.Columns.isTrusted.set(to: true))

View File

@ -92,7 +92,7 @@ final class JoinOpenGroupModal: Modal {
presentingViewController.dismiss(animated: true, completion: nil)
GRDBStorage.shared
Storage.shared
.writeAsync { db in
OpenGroupManager.shared.add(
db,
@ -103,7 +103,7 @@ final class JoinOpenGroupModal: Modal {
)
}
.done(on: DispatchQueue.main) { _ in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
try MessageSender.syncConfiguration(db, forceSyncNow: true).retainUntilComplete() // FIXME: It's probably cleaner to do this inside addOpenGroup(...)
}
}

View File

@ -77,7 +77,7 @@ final class LinkPreviewModal: Modal {
// MARK: - Interaction
@objc private func enable() {
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
db[.areLinkPreviewsEnabled] = true
}

View File

@ -175,7 +175,7 @@ final class NewDMVC : BaseVC, UIPageViewControllerDataSource, UIPageViewControll
}
private func startNewDM(with sessionId: String) {
let maybeThread: SessionThread? = GRDBStorage.shared.write { db in
let maybeThread: SessionThread? = Storage.shared.write { db in
try SessionThread.fetchOrCreate(db, id: sessionId, variant: .contact)
}

View File

@ -22,7 +22,7 @@ class GlobalSearchViewController: BaseVC, UITableViewDelegate, UITableViewDataSo
// MARK: - Variables
private lazy var defaultSearchResults: [SectionModel] = {
let result: SessionThreadViewModel? = GRDBStorage.shared.read { db -> SessionThreadViewModel? in
let result: SessionThreadViewModel? = Storage.shared.read { db -> SessionThreadViewModel? in
try SessionThreadViewModel
.noteToSelfOnlyQuery(userPublicKey: getUserHexEncodedPublicKey(db))
.fetchOne(db)
@ -155,7 +155,7 @@ class GlobalSearchViewController: BaseVC, UITableViewDelegate, UITableViewDataSo
lastSearchText = searchText
let result: Result<[SectionModel], Error>? = GRDBStorage.shared.read { db -> Result<[SectionModel], Error> in
let result: Result<[SectionModel], Error>? = Storage.shared.read { db -> Result<[SectionModel], Error> in
do {
let userPublicKey: String = getUserHexEncodedPublicKey(db)
let contactsAndGroupsResults: [SessionThreadViewModel] = try SessionThreadViewModel

View File

@ -20,7 +20,7 @@ final class HomeVC: BaseVC, UITableViewDataSource, UITableViewDelegate, NewConve
// MARK: - Intialization
init() {
GRDBStorage.shared.addObserver(viewModel.pagedDataObserver)
Storage.shared.addObserver(viewModel.pagedDataObserver)
super.init(nibName: nil, bundle: nil)
}
@ -242,7 +242,7 @@ final class HomeVC: BaseVC, UITableViewDataSource, UITableViewDelegate, NewConve
private func startObservingChanges() {
// Start observing for data changes
dataChangeObservable = GRDBStorage.shared.start(
dataChangeObservable = Storage.shared.start(
viewModel.observableState,
// If we haven't done the initial load the trigger it immediately (blocking the main
// thread so we remain on the launch screen until it completes to be consistent with
@ -537,7 +537,7 @@ final class HomeVC: BaseVC, UITableViewDataSource, UITableViewDelegate, NewConve
switch section.model {
case .messageRequests:
let hide = UITableViewRowAction(style: .destructive, title: "TXT_HIDE_TITLE".localized()) { _, _ in
GRDBStorage.shared.write { db in db[.hasHiddenMessageRequests] = true }
Storage.shared.write { db in db[.hasHiddenMessageRequests] = true }
}
hide.backgroundColor = Colors.destructive
@ -563,7 +563,7 @@ final class HomeVC: BaseVC, UITableViewDataSource, UITableViewDelegate, NewConve
title: "TXT_DELETE_TITLE".localized(),
style: .destructive
) { _ in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
switch threadViewModel.threadVariant {
case .closedGroup:
try MessageSender
@ -597,7 +597,7 @@ final class HomeVC: BaseVC, UITableViewDataSource, UITableViewDelegate, NewConve
"PIN_BUTTON_TEXT".localized()
)
) { _, _ in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
try SessionThread
.filter(id: threadViewModel.threadId)
.updateAll(db, SessionThread.Columns.isPinned.set(to: !threadViewModel.threadIsPinned))
@ -615,7 +615,7 @@ final class HomeVC: BaseVC, UITableViewDataSource, UITableViewDelegate, NewConve
"BLOCK_LIST_BLOCK_BUTTON".localized()
)
) { _, _ in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
try Contact
.filter(id: threadViewModel.threadId)
.updateAll(

View File

@ -28,8 +28,8 @@ public class HomeViewModel {
let userProfile: Profile?
init(
showViewedSeedBanner: Bool = !GRDBStorage.shared[.hasViewedSeed],
hasHiddenMessageRequests: Bool = GRDBStorage.shared[.hasHiddenMessageRequests],
showViewedSeedBanner: Bool = !Storage.shared[.hasViewedSeed],
hasHiddenMessageRequests: Bool = Storage.shared[.hasHiddenMessageRequests],
unreadMessageRequestThreadCount: Int = 0,
userProfile: Profile? = nil
) {
@ -43,7 +43,7 @@ public class HomeViewModel {
// MARK: - Initialization
init() {
self.state = GRDBStorage.shared.read { db in try HomeViewModel.retrieveState(db) }
self.state = Storage.shared.read { db in try HomeViewModel.retrieveState(db) }
.defaulting(to: State())
self.pagedDataObserver = nil

View File

@ -18,7 +18,7 @@ class MessageRequestsViewController: BaseVC, UITableViewDelegate, UITableViewDat
// MARK: - Intialization
init() {
GRDBStorage.shared.addObserver(viewModel.pagedDataObserver)
Storage.shared.addObserver(viewModel.pagedDataObserver)
super.init(nibName: nil, bundle: nil)
}
@ -355,7 +355,7 @@ class MessageRequestsViewController: BaseVC, UITableViewDelegate, UITableViewDat
style: .destructive
) { _ in
// Clear the requests
GRDBStorage.shared.write { db in
Storage.shared.write { db in
_ = try SessionThread
.filter(ids: threadIds)
.deleteAll(db)
@ -388,7 +388,7 @@ class MessageRequestsViewController: BaseVC, UITableViewDelegate, UITableViewDat
title: "TXT_DELETE_TITLE".localized(),
style: .destructive
) { _ in
GRDBStorage.shared.write { db in
Storage.shared.write { db in
_ = try SessionThread
.filter(id: threadId)
.deleteAll(db)

View File

@ -372,41 +372,40 @@ public class MediaGalleryViewModel {
// Note: It's possible we already have cached album data for this interaction
// but to avoid displaying stale data we re-fetch from the database anyway
let maybeAlbumInfo: AlbumInfo? = GRDBStorage.shared
.read { db -> AlbumInfo in
let attachment: TypedTableAlias<Attachment> = TypedTableAlias()
let interaction: TypedTableAlias<Interaction> = TypedTableAlias()
let interactionAttachment: TypedTableAlias<InteractionAttachment> = TypedTableAlias()
let newAlbumData: [Item] = try Item
.baseQuery(
orderSQL: SQL(interactionAttachment[.albumIndex]),
customFilters: SQL("""
\(attachment[.isValid]) = true AND
\(interaction[.id]) = \(interactionId)
""")
)
.fetchAll(db)
guard let albumTimestampMs: Int64 = newAlbumData.first?.interactionTimestampMs else {
return (newAlbumData, nil, nil)
}
let itemBefore: Item? = try Item
.baseQuery(
orderSQL: Item.galleryReverseOrderSQL,
customFilters: SQL("\(interaction[.timestampMs]) > \(albumTimestampMs)")
)
.fetchOne(db)
let itemAfter: Item? = try Item
.baseQuery(
orderSQL: Item.galleryOrderSQL,
customFilters: SQL("\(interaction[.timestampMs]) < \(albumTimestampMs)")
)
.fetchOne(db)
return (newAlbumData, itemBefore?.interactionId, itemAfter?.interactionId)
let maybeAlbumInfo: AlbumInfo? = Storage.shared.read { db -> AlbumInfo in
let attachment: TypedTableAlias<Attachment> = TypedTableAlias()
let interaction: TypedTableAlias<Interaction> = TypedTableAlias()
let interactionAttachment: TypedTableAlias<InteractionAttachment> = TypedTableAlias()
let newAlbumData: [Item] = try Item
.baseQuery(
orderSQL: SQL(interactionAttachment[.albumIndex]),
customFilters: SQL("""
\(attachment[.isValid]) = true AND
\(interaction[.id]) = \(interactionId)
""")
)
.fetchAll(db)
guard let albumTimestampMs: Int64 = newAlbumData.first?.interactionTimestampMs else {
return (newAlbumData, nil, nil)
}
let itemBefore: Item? = try Item
.baseQuery(
orderSQL: Item.galleryReverseOrderSQL,
customFilters: SQL("\(interaction[.timestampMs]) > \(albumTimestampMs)")
)
.fetchOne(db)
let itemAfter: Item? = try Item
.baseQuery(
orderSQL: Item.galleryOrderSQL,
customFilters: SQL("\(interaction[.timestampMs]) < \(albumTimestampMs)")
)
.fetchOne(db)
return (newAlbumData, itemBefore?.interactionId, itemAfter?.interactionId)
}
guard let newAlbumInfo: AlbumInfo = maybeAlbumInfo else { return [] }

View File

@ -384,7 +384,7 @@ class MediaPageViewController: UIPageViewController, UIPageViewControllerDataSou
private func startObservingChanges() {
// Start observing for data changes
dataChangeObservable = GRDBStorage.shared.start(
dataChangeObservable = Storage.shared.start(
viewModel.observableAlbumData,
onError: { _ in },
onChange: { [weak self] albumData in
@ -528,7 +528,7 @@ class MediaPageViewController: UIPageViewController, UIPageViewControllerDataSou
self.viewModel.threadVariant == .contact
else { return }
GRDBStorage.shared.write { db in
Storage.shared.write { db in
guard let thread: SessionThread = try SessionThread.fetchOne(db, id: self.viewModel.threadId) else {
return
}
@ -555,7 +555,7 @@ class MediaPageViewController: UIPageViewController, UIPageViewControllerDataSou
title: "delete_message_for_me".localized(),
style: .destructive
) { _ in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
_ = try Attachment
.filter(id: itemToDelete.attachment.id)
.deleteAll(db)
@ -864,7 +864,7 @@ class MediaPageViewController: UIPageViewController, UIPageViewControllerDataSou
let name: String = {
switch targetItem.interactionVariant {
case .standardIncoming:
return GRDBStorage.shared
return Storage.shared
.read { db in
Profile.displayName(
db,

View File

@ -35,7 +35,7 @@ public class MediaTileViewController: UIViewController, UICollectionViewDataSour
init(viewModel: MediaGalleryViewModel) {
self.viewModel = viewModel
GRDBStorage.shared.addObserver(viewModel.pagedDataObserver)
Storage.shared.addObserver(viewModel.pagedDataObserver)
super.init(nibName: nil, bundle: nil)
}
@ -670,7 +670,7 @@ public class MediaTileViewController: UIViewController, UICollectionViewDataSour
}()
let deleteAction = UIAlertAction(title: confirmationTitle, style: .destructive) { [weak self] _ in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
let interactionIds: Set<Int64> = items
.map { $0.interactionId }
.asSet()

View File

@ -202,7 +202,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
Environment.shared?.audioSession.setup()
Environment.shared?.reachabilityManager.setup()
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
// Disable the SAE until the main app has successfully completed launch process
// at least once in the post-SAE world.
db[.isReadyForAppExtensions] = true
@ -238,7 +238,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
// Remove the legacy database and any message hashes that have been migrated to the new DB
try? SUKLegacy.deleteLegacyDatabaseFilesAndKey()
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try SnodeReceivedMessageInfo.deleteAll(db)
}
@ -272,7 +272,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
private func verifyDBKeysAvailableBeforeBackgroundLaunch() {
guard UIApplication.shared.applicationState == .background else { return }
guard !GRDBStorage.isDatabasePasswordAccessible else { return } // All good
guard !Storage.isDatabasePasswordAccessible else { return } // All good
Logger.info("Exiting because we are in the background and the database password is not accessible.")
@ -320,7 +320,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
}
private func ensureRootViewController(isPreAppReadyCall: Bool = false) {
guard (AppReadiness.isAppReady() || isPreAppReadyCall) && GRDBStorage.shared.isValid && !hasInitialRootViewController else {
guard (AppReadiness.isAppReady() || isPreAppReadyCall) && Storage.shared.isValid && !hasInitialRootViewController else {
return
}
@ -366,7 +366,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
guard CurrentAppContext().isMainApp else { return }
CurrentAppContext().setMainAppBadgeNumber(
GRDBStorage.shared
Storage.shared
.read { db in
let userPublicKey: String = getUserHexEncodedPublicKey(db)
let thread: TypedTableAlias<SessionThread> = TypedTableAlias()
@ -596,7 +596,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
guard Date().timeIntervalSince(lastSync) > (7 * 24 * 60 * 60) else { return } // Sync every 2 days
GRDBStorage.shared
Storage.shared
.writeAsync { db in try MessageSender.syncConfiguration(db, forceSyncNow: false) }
.done {
// Only update the 'lastConfigurationSync' timestamp if we have done the

View File

@ -10,7 +10,7 @@ public struct SessionApp {
// MARK: - View Convenience Methods
public static func presentConversation(for threadId: String, action: ConversationViewModel.Action = .none, animated: Bool) {
let maybeThread: SessionThread? = GRDBStorage.shared.write { db in
let maybeThread: SessionThread? = Storage.shared.write { db in
try SessionThread.fetchOrCreate(db, id: threadId, variant: .contact)
}
@ -61,7 +61,7 @@ public struct SessionApp {
Logger.error("")
DDLog.flushLog()
GRDBStorage.resetAllStorage()
Storage.resetAllStorage()
ProfileManager.resetProfileStorage()
Attachment.resetAttachmentStorage()
AppEnvironment.shared.notificationPresenter.clearAllNotifications()

View File

@ -395,7 +395,7 @@ public class NotificationPresenter: NSObject, NotificationsProtocol {
AssertIsOnMainThread()
guard UIApplication.shared.applicationState == .active else { return true }
guard GRDBStorage.shared[.playNotificationSoundInForeground] else { return false }
guard Storage.shared[.playNotificationSoundInForeground] else { return false }
let nowMs: UInt64 = UInt64(floor(Date().timeIntervalSince1970 * 1000))
let recentThreshold = nowMs - UInt64(kAudioNotificationsThrottleInterval * Double(kSecondInMs))
@ -428,7 +428,7 @@ class NotificationActionHandler {
throw NotificationError.failDebug("threadId was unexpectedly nil")
}
guard let thread: SessionThread = GRDBStorage.shared.read({ db in try SessionThread.fetchOne(db, id: threadId) }) else {
guard let thread: SessionThread = Storage.shared.read({ db in try SessionThread.fetchOne(db, id: threadId) }) else {
throw NotificationError.failDebug("unable to find thread with id: \(threadId)")
}
@ -440,13 +440,13 @@ class NotificationActionHandler {
throw NotificationError.failDebug("threadId was unexpectedly nil")
}
guard let thread: SessionThread = GRDBStorage.shared.read({ db in try SessionThread.fetchOne(db, id: threadId) }) else {
guard let thread: SessionThread = Storage.shared.read({ db in try SessionThread.fetchOne(db, id: threadId) }) else {
throw NotificationError.failDebug("unable to find thread with id: \(threadId)")
}
let (promise, seal) = Promise<Void>.pending()
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
let interaction: Interaction = try Interaction(
threadId: thread.id,
authorId: getUserHexEncodedPublicKey(db),
@ -472,7 +472,7 @@ class NotificationActionHandler {
}
.done { seal.fulfill(()) }
.catch { error in
GRDBStorage.shared.read { [weak self] db in
Storage.shared.read { [weak self] db in
self?.notificationPresenter.notifyForFailedSend(db, in: thread)
}
@ -504,7 +504,7 @@ class NotificationActionHandler {
private func markAsRead(thread: SessionThread) -> Promise<Void> {
let (promise, seal) = Promise<Void>.pending()
GRDBStorage.shared.writeAsync(
Storage.shared.writeAsync(
updates: { db in
try Interaction.markAsRead(
db,

View File

@ -243,7 +243,7 @@ public enum PushRegistrationError: Error {
let payload = payload.dictionaryPayload
if let uuid = payload["uuid"] as? String, let caller = payload["caller"] as? String, let timestampMs = payload["timestamp"] as? Int64 {
let call: SessionCall? = GRDBStorage.shared.write { db in
let call: SessionCall? = Storage.shared.write { db in
let messageInfo: CallMessage.MessageInfo = CallMessage.MessageInfo(
state: (caller == getUserHexEncodedPublicKey(db) ?
.outgoing :

View File

@ -51,8 +51,8 @@ public enum SyncPushTokensJob: JobExecutor {
PushRegistrationManager.shared.requestPushTokens()
.then(on: queue) { (pushToken: String, voipToken: String) -> Promise<Void> in
let lastPushToken: String? = GRDBStorage.shared[.lastRecordedPushToken]
let lastVoipToken: String? = GRDBStorage.shared[.lastRecordedVoipToken]
let lastPushToken: String? = Storage.shared[.lastRecordedPushToken]
let lastVoipToken: String? = Storage.shared[.lastRecordedVoipToken]
let shouldUploadTokens: Bool = (
!uploadOnlyIfStale || (
lastPushToken != pushToken ||
@ -77,7 +77,7 @@ public enum SyncPushTokensJob: JobExecutor {
.done(on: queue) { _ in
Logger.warn("Recording push tokens locally. pushToken: \(redact(pushToken)), voipToken: \(redact(voipToken))")
GRDBStorage.shared.write { db in
Storage.shared.write { db in
db[.lastRecordedPushToken] = pushToken
db[.lastRecordedVoipToken] = voipToken
}

View File

@ -17,7 +17,7 @@ enum Onboarding {
Identity.store(seed: seed, ed25519KeyPair: ed25519KeyPair, x25519KeyPair: x25519KeyPair)
let x25519PublicKey = x25519KeyPair.hexEncodedPublicKey
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try Contact(id: x25519PublicKey)
.with(
isApproved: true,
@ -28,7 +28,7 @@ enum Onboarding {
switch self {
case .register:
GRDBStorage.shared.write { db in db[.hasViewedSeed] = false }
Storage.shared.write { db in db[.hasViewedSeed] = false }
// Set hasSyncedInitialConfiguration to true so that when we hit the
// home screen a configuration sync is triggered (yes, the logic is a
// bit weird). This is needed so that if the user registers and
@ -37,7 +37,7 @@ enum Onboarding {
case .recover, .link:
// No need to show it again if the user is restoring or linking
GRDBStorage.shared.write { db in db[.hasViewedSeed] = true }
Storage.shared.write { db in db[.hasViewedSeed] = true }
userDefaults[.hasSyncedInitialConfiguration] = false
}

View File

@ -171,7 +171,7 @@ final class SeedVC: BaseVC {
}, completion: nil)
seedReminderView.setProgress(1, animated: true)
GRDBStorage.shared.write { db in db[.hasViewedSeed] = true }
Storage.shared.writeAsync { db in db[.hasViewedSeed] = true }
}
@objc private func copyMnemonic() {

View File

@ -162,7 +162,7 @@ final class JoinOpenGroupVC: BaseVC, UIPageViewControllerDataSource, UIPageViewC
isJoining = true
ModalActivityIndicatorViewController.present(fromViewController: navigationController, canCancel: false) { [weak self] _ in
GRDBStorage.shared
Storage.shared
.writeAsync { db in
OpenGroupManager.shared.add(
db,
@ -173,7 +173,7 @@ final class JoinOpenGroupVC: BaseVC, UIPageViewControllerDataSource, UIPageViewC
)
}
.done(on: DispatchQueue.main) { [weak self] _ in
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
try MessageSender.syncConfiguration(db, forceSyncNow: true).retainUntilComplete() // FIXME: It's probably cleaner to do this inside addOpenGroup(...)
}

View File

@ -250,7 +250,7 @@ extension OpenGroupSuggestionGrid {
return
}
let promise = GRDBStorage.shared.read { db in
let promise = Storage.shared.read { db in
OpenGroupManager.roomImage(db, fileId: imageId, for: room.token, on: OpenGroupAPI.defaultServer)
}

View File

@ -35,7 +35,7 @@ class ChatSettingsViewController: OWSTableViewController {
messageTrimming.footerTitle = "MESSAGE_TRIMMING_OPEN_GROUP_DESCRIPTION".localized()
messageTrimming.add(OWSTableItem.switch(
withText: "MESSAGE_TRIMMING_OPEN_GROUP_TITLE".localized(),
isOn: { GRDBStorage.shared[.trimOpenGroupMessagesOlderThanSixMonths] },
isOn: { Storage.shared[.trimOpenGroupMessagesOlderThanSixMonths] },
target: self,
selector: #selector(didToggleTrimOpenGroupsSwitch(_:))
))
@ -47,7 +47,7 @@ class ChatSettingsViewController: OWSTableViewController {
// MARK: - Actions
@objc private func didToggleTrimOpenGroupsSwitch(_ sender: UISwitch) {
GRDBStorage.shared.writeAsync(
Storage.shared.writeAsync(
updates: { db in
db[.trimOpenGroupMessagesOlderThanSixMonths] = !sender.isOn
},

View File

@ -154,7 +154,7 @@ final class NukeDataModal: Modal {
@objc private func clearDeviceOnly() {
ModalActivityIndicatorViewController.present(fromViewController: self, canCancel: false) { [weak self] _ in
GRDBStorage.shared
Storage.shared
.writeAsync { db in try MessageSender.syncConfiguration(db, forceSyncNow: true) }
.ensure(on: DispatchQueue.main) {
self?.deleteAllLocalData()

View File

@ -132,7 +132,7 @@ final class QRCodeVC : BaseVC, UIPageViewControllerDataSource, UIPageViewControl
presentAlert(alert)
}
else {
let maybeThread: SessionThread? = GRDBStorage.shared.write { db in
let maybeThread: SessionThread? = Storage.shared.write { db in
try SessionThread.fetchOrCreate(db, id: hexEncodedPublicKey, variant: .contact)
}

View File

@ -86,7 +86,7 @@ final class SeedModal: Modal {
contentView.pin(.bottom, to: .bottom, of: stackView, withInset: spacing)
// Mark seed as viewed
GRDBStorage.shared.write { db in db[.hasViewedSeed] = true }
Storage.shared.writeAsync { db in db[.hasViewedSeed] = true }
}
// MARK: - Interaction

View File

@ -602,8 +602,8 @@ final class SettingsVC: BaseVC, AvatarViewHelperDelegate {
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "Re-migrate", style: .destructive) { _ in
GRDBStorage.deleteDatabaseFiles()
try? GRDBStorage.deleteDbKeys()
Storage.deleteDatabaseFiles()
try? Storage.deleteDbKeys()
exit(1)
})
alert.addAction(UIAlertAction(title: "Cancel", style: .default))

View File

@ -19,7 +19,7 @@ public final class BackgroundPoller: NSObject {
.appending(pollForMessages())
.appending(contentsOf: pollForClosedGroupMessages())
.appending(
contentsOf: GRDBStorage.shared
contentsOf: Storage.shared
.read { db in
// The default room promise creates an OpenGroup with an empty `roomToken` value,
// we don't want to start a poller for this as the user hasn't actually joined a room
@ -58,7 +58,7 @@ public final class BackgroundPoller: NSObject {
private static func pollForClosedGroupMessages() -> [Promise<Void>] {
// Fetch all closed groups (excluding any don't contain the current user as a
// GroupMemeber as the user is no longer a member of those)
return GRDBStorage.shared
return Storage.shared
.read { db in
try ClosedGroup
.select(.threadId)
@ -92,7 +92,7 @@ public final class BackgroundPoller: NSObject {
var jobsToRun: [Job] = []
GRDBStorage.shared.write { db in
Storage.shared.write { db in
var threadMessages: [String: [MessageReceiveJob.Details.MessageInfo]] = [:]
messages.forEach { message in

View File

@ -170,7 +170,7 @@ public final class WebRTCSession : NSObject, RTCPeerConnectionDelegate {
}
}
GRDBStorage.shared
Storage.shared
.writeAsync { db in
try MessageSender
.sendNonDurably(
@ -203,7 +203,7 @@ public final class WebRTCSession : NSObject, RTCPeerConnectionDelegate {
let uuid: String = self.uuid
let mediaConstraints: RTCMediaConstraints = mediaConstraints(false)
GRDBStorage.shared.writeAsync { [weak self] db in
Storage.shared.writeAsync { [weak self] db in
guard let thread: SessionThread = try? SessionThread.fetchOne(db, id: sessionId) else {
seal.reject(Error.noThread)
return
@ -268,7 +268,7 @@ public final class WebRTCSession : NSObject, RTCPeerConnectionDelegate {
// Empty the queue
self.queuedICECandidates.removeAll()
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
guard let thread: SessionThread = try SessionThread.fetchOne(db, id: contactSessionId) else { return }
SNLog("[Calls] Batch sending \(candidates.count) ICE candidates.")

View File

@ -368,6 +368,6 @@ enum _001_InitialSetupMigration: Migration {
t.column(.timestampMs, .integer).notNull()
}
GRDBStorage.update(progress: 1, for: self, in: target) // In case this is the last migration
Storage.update(progress: 1, for: self, in: target) // In case this is the last migration
}
}

View File

@ -52,6 +52,6 @@ enum _002_SetupStandardJobs: Migration {
).inserted(db)
}
GRDBStorage.update(progress: 1, for: self, in: target) // In case this is the last migration
Storage.update(progress: 1, for: self, in: target) // In case this is the last migration
}
}

View File

@ -80,7 +80,7 @@ enum _003_YDBToGRDBMigration: Migration {
legacyMigrations.insert(legacyMigration)
}
GRDBStorage.update(progress: 0.01, for: self, in: target)
Storage.update(progress: 0.01, for: self, in: target)
// MARK: --Contacts
@ -96,7 +96,7 @@ enum _003_YDBToGRDBMigration: Migration {
forKey: SMKLegacy.blockedPhoneNumbersKey,
inCollection: SMKLegacy.blockListCollection
) as? [String] ?? [])
GRDBStorage.update(progress: 0.02, for: self, in: target)
Storage.update(progress: 0.02, for: self, in: target)
// MARK: --Threads
@ -196,7 +196,7 @@ enum _003_YDBToGRDBMigration: Migration {
openGroupImage[thread.uniqueId] = transaction.object(forKey: openGroup.id, inCollection: SMKLegacy.openGroupImageCollection) as? Data
}
}
GRDBStorage.update(progress: 0.04, for: self, in: target)
Storage.update(progress: 0.04, for: self, in: target)
// MARK: --Interactions
@ -245,7 +245,7 @@ enum _003_YDBToGRDBMigration: Migration {
rowIndex += 1
GRDBStorage.update(
Storage.update(
progress: min(
interactionsCompleteProgress,
((rowIndex / roughNumRows) * (interactionsCompleteProgress - startProgress))
@ -254,7 +254,7 @@ enum _003_YDBToGRDBMigration: Migration {
in: target
)
}
GRDBStorage.update(progress: interactionsCompleteProgress, for: self, in: target)
Storage.update(progress: interactionsCompleteProgress, for: self, in: target)
// MARK: --Attachments
@ -269,7 +269,7 @@ enum _003_YDBToGRDBMigration: Migration {
attachments[key] = attachment
}
GRDBStorage.update(progress: 0.21, for: self, in: target)
Storage.update(progress: 0.21, for: self, in: target)
// MARK: --Read Receipts
@ -328,7 +328,7 @@ enum _003_YDBToGRDBMigration: Migration {
guard let job = object as? SMKLegacy._AttachmentDownloadJob else { return }
attachmentDownloadJobs.insert(job)
}
GRDBStorage.update(progress: 0.22, for: self, in: target)
Storage.update(progress: 0.22, for: self, in: target)
// MARK: --Preferences
@ -387,7 +387,7 @@ enum _003_YDBToGRDBMigration: Migration {
.asType(NSNumber.self)?
.doubleValue)
.defaulting(to: (15 * 60))
GRDBStorage.update(progress: 0.23, for: self, in: target)
Storage.update(progress: 0.23, for: self, in: target)
}
// We can't properly throw within the 'enumerateKeysAndObjects' block so have to throw here
@ -490,7 +490,7 @@ enum _003_YDBToGRDBMigration: Migration {
}
// Increment the progress for each contact
GRDBStorage.update(
Storage.update(
progress: contactStartProgress + (progressPerContact * CGFloat(index + 1)),
for: self,
in: target
@ -1128,7 +1128,7 @@ enum _003_YDBToGRDBMigration: Migration {
}
// Increment the progress for each contact
GRDBStorage.update(
Storage.update(
progress: (
threadInteractionsStartProgress +
(progressPerInteraction * (interactionCounter + 1))
@ -1400,7 +1400,7 @@ enum _003_YDBToGRDBMigration: Migration {
)?.inserted(db)
}
}
GRDBStorage.update(progress: 0.99, for: self, in: target)
Storage.update(progress: 0.99, for: self, in: target)
// MARK: - Preferences
@ -1440,7 +1440,7 @@ enum _003_YDBToGRDBMigration: Migration {
db[.hasSentAMessage] = (legacyPreferences[SMKLegacy.preferencesKeyHasSentAMessageKey] as? Bool == true)
db[.isReadyForAppExtensions] = CurrentAppContext().appUserDefaults().bool(forKey: SMKLegacy.preferencesKeyIsReadyForAppExtensions)
GRDBStorage.update(progress: 1, for: self, in: target) // In case this is the last migration
Storage.update(progress: 1, for: self, in: target) // In case this is the last migration
}
// MARK: - Convenience

View File

@ -960,7 +960,7 @@ extension Attachment {
// Save the final upload info
let uploadedAttachment: Attachment? = {
guard let db: Database = db else {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try? Attachment
.filter(id: attachmentId)
.updateAll(db, Attachment.Columns.state.set(to: Attachment.State.uploaded))
@ -1016,7 +1016,7 @@ extension Attachment {
// Update the attachment to the 'uploading' state
let updatedAttachment: Attachment? = {
guard let db: Database = db else {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try? Attachment
.filter(id: attachmentId)
.updateAll(db, Attachment.Columns.state.set(to: Attachment.State.uploading))
@ -1041,7 +1041,7 @@ extension Attachment {
// Perform the upload
let uploadPromise: Promise<String> = {
guard let db: Database = db else {
return GRDBStorage.shared.read { db in upload(db, data) }
return Storage.shared.read { db in upload(db, data) }
}
return upload(db, data)
@ -1050,7 +1050,7 @@ extension Attachment {
uploadPromise
.done(on: queue) { fileId in
// Save the final upload info
let uploadedAttachment: Attachment? = GRDBStorage.shared.write { db in
let uploadedAttachment: Attachment? = Storage.shared.write { db in
try updatedAttachment?
.with(
serverId: "\(fileId)",
@ -1073,7 +1073,7 @@ extension Attachment {
success?()
}
.catch(on: queue) { error in
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try Attachment
.filter(id: attachmentId)
.updateAll(db, Attachment.Columns.state.set(to: Attachment.State.failedUpload))

View File

@ -117,7 +117,7 @@ public class SMKContact: NSObject {
}
@objc public static func fetchOrCreate(id: String) -> SMKContact {
let existingContact: Contact? = GRDBStorage.shared.read { db in
let existingContact: Contact? = Storage.shared.read { db in
try Contact.fetchOne(db, id: id)
}
@ -130,7 +130,7 @@ public class SMKContact: NSObject {
@objc(isBlockedFor:)
public static func isBlocked(id: String) -> Bool {
return GRDBStorage.shared
return Storage.shared
.read { db in
try Contact
.select(.isBlocked)

View File

@ -140,7 +140,7 @@ public class SMKDisappearingMessagesConfiguration: NSObject {
@objc(isEnabledFor:)
public static func isEnabled(for threadId: String) -> Bool {
return GRDBStorage.shared
return Storage.shared
.read { db in
try DisappearingMessagesConfiguration
.select(.isEnabled)
@ -153,7 +153,7 @@ public class SMKDisappearingMessagesConfiguration: NSObject {
@objc(durationIndexFor:)
public static func durationIndex(for threadId: String) -> Int {
let durationSeconds: TimeInterval = GRDBStorage.shared
let durationSeconds: TimeInterval = Storage.shared
.read { db in
try DisappearingMessagesConfiguration
.select(.durationSeconds)
@ -187,7 +187,7 @@ public class SMKDisappearingMessagesConfiguration: NSObject {
DisappearingMessagesConfiguration.validDurationsSeconds[0]
)
GRDBStorage.shared.write { db in
Storage.shared.write { db in
guard let thread: SessionThread = try SessionThread.fetchOne(db, id: threadId) else {
return
}

View File

@ -65,7 +65,7 @@ public struct GroupMember: Codable, Equatable, FetchableRecord, PersistableRecor
public class SMKGroupMember: NSObject {
@objc(isCurrentUserMemberOf:)
public static func isCurrentUserMember(of groupId: String) -> Bool {
return GRDBStorage.shared.read { db in
return Storage.shared.read { db in
let userPublicKey: String = getUserHexEncodedPublicKey(db)
let numEntries: Int = try GroupMember
.filter(GroupMember.Columns.groupId == groupId)
@ -79,7 +79,7 @@ public class SMKGroupMember: NSObject {
@objc(isCurrentUserAdminOf:)
public static func isCurrentUserAdmin(of groupId: String) -> Bool {
return GRDBStorage.shared.read { db in
return Storage.shared.read { db in
let userPublicKey: String = getUserHexEncodedPublicKey(db)
let numEntries: Int = try GroupMember
.filter(GroupMember.Columns.groupId == groupId)

View File

@ -214,7 +214,7 @@ public extension LinkPreview {
private static var previewUrlCache: Atomic<NSCache<NSString, NSString>> = Atomic(NSCache())
static func previewUrl(for body: String?, selectedRange: NSRange? = nil) -> String? {
guard GRDBStorage.shared[.areLinkPreviewsEnabled] else { return nil }
guard Storage.shared[.areLinkPreviewsEnabled] else { return nil }
guard let body: String = body else { return nil }
if let cachedUrl = previewUrlCache.wrappedValue.object(forKey: body as NSString) as String? {
@ -291,7 +291,7 @@ public extension LinkPreview {
// Exit early if link previews are not enabled in order to avoid
// tainting the cache.
guard GRDBStorage.shared[.areLinkPreviewsEnabled] else { return }
guard Storage.shared[.areLinkPreviewsEnabled] else { return }
serialQueue.sync {
linkPreviewDraftCache = linkPreviewDraft
@ -299,7 +299,7 @@ public extension LinkPreview {
}
static func tryToBuildPreviewInfo(previewUrl: String?) -> Promise<LinkPreviewDraft> {
guard GRDBStorage.shared[.areLinkPreviewsEnabled] else {
guard Storage.shared[.areLinkPreviewsEnabled] else {
return Promise(error: LinkPreviewError.featureDisabled)
}
guard let previewUrl: String = previewUrl else {

View File

@ -205,7 +205,7 @@ extension OpenGroup: CustomStringConvertible, CustomDebugStringConvertible {
public class SMKOpenGroup: NSObject {
@objc(inviteUsers:toOpenGroupFor:)
public static func invite(selectedUsers: Set<String>, openGroupThreadId: String) {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
guard let openGroup: OpenGroup = try OpenGroup.fetchOne(db, id: openGroupThreadId) else { return }
let urlString: String = "\(openGroup.server)/\(openGroup.roomToken)?public_key=\(openGroup.publicKey)"

View File

@ -219,7 +219,7 @@ public extension Profile {
public extension Profile {
static func fetchAllContactProfiles(excluding: Set<String> = [], excludeCurrentUser: Bool = true) -> [Profile] {
return GRDBStorage.shared
return Storage.shared
.read { db in
let idsToExclude: Set<String> = excluding
.inserting(excludeCurrentUser ? getUserHexEncodedPublicKey(db) : nil)
@ -240,7 +240,7 @@ public extension Profile {
static func displayName(_ db: Database? = nil, id: ID, threadVariant: SessionThread.Variant = .contact, customFallback: String? = nil) -> String {
guard let db: Database = db else {
return GRDBStorage.shared
return Storage.shared
.read { db in displayName(db, id: id, threadVariant: threadVariant, customFallback: customFallback) }
.defaulting(to: (customFallback ?? id))
}
@ -253,7 +253,7 @@ public extension Profile {
static func displayNameNoFallback(_ db: Database? = nil, id: ID, threadVariant: SessionThread.Variant = .contact) -> String? {
guard let db: Database = db else {
return GRDBStorage.shared.read { db in displayNameNoFallback(db, id: id, threadVariant: threadVariant) }
return Storage.shared.read { db in displayNameNoFallback(db, id: id, threadVariant: threadVariant) }
}
return (try? Profile.fetchOne(db, id: id))?
@ -280,7 +280,7 @@ public extension Profile {
static func fetchOrCreateCurrentUser() -> Profile {
var userPublicKey: String = ""
let exisingProfile: Profile? = GRDBStorage.shared.read { db in
let exisingProfile: Profile? = Storage.shared.read { db in
userPublicKey = getUserHexEncodedPublicKey(db)
return try Profile.fetchOne(db, id: userPublicKey)
@ -307,7 +307,7 @@ public extension Profile {
/// **Note:** This method intentionally does **not** save the newly created Profile,
/// it will need to be explicitly saved after calling
static func fetchOrCreate(id: String) -> Profile {
let exisingProfile: Profile? = GRDBStorage.shared.read { db in
let exisingProfile: Profile? = Storage.shared.read { db in
try Profile.fetchOne(db, id: id)
}
@ -401,7 +401,7 @@ public class SMKProfile: NSObject {
@objc(displayNameAfterSavingNickname:forProfileId:)
public static func displayNameAfterSaving(nickname: String?, for profileId: String) -> String {
return GRDBStorage.shared.write { db in
return Storage.shared.write { db in
let profile: Profile = Profile.fetchOrCreate(id: profileId)
let targetNickname: String? = ((nickname ?? "").count > 0 ? nickname : nil)

View File

@ -275,14 +275,14 @@ public extension SessionThread {
public class SMKThread: NSObject {
@objc(deleteAll)
public static func deleteAll() {
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
_ = try SessionThread.deleteAll(db)
}
}
@objc(isThreadMuted:)
public static func isThreadMuted(_ threadId: String) -> Bool {
return GRDBStorage.shared.read { db in
return Storage.shared.read { db in
let mutedUntilTimestamp: TimeInterval? = try SessionThread
.select(SessionThread.Columns.mutedUntilTimestamp)
.filter(id: threadId)
@ -296,7 +296,7 @@ public class SMKThread: NSObject {
@objc(isOnlyNotifyingForMentions:)
public static func isOnlyNotifyingForMentions(_ threadId: String) -> Bool {
return GRDBStorage.shared.read { db in
return Storage.shared.read { db in
return try SessionThread
.select(SessionThread.Columns.onlyNotifyForMentions == true)
.filter(id: threadId)
@ -308,7 +308,7 @@ public class SMKThread: NSObject {
@objc(setIsOnlyNotifyingForMentions:to:)
public static func isOnlyNotifyingForMentions(_ threadId: String, isEnabled: Bool) {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try SessionThread
.filter(id: threadId)
.updateAll(db, SessionThread.Columns.onlyNotifyForMentions.set(to: isEnabled))
@ -317,7 +317,7 @@ public class SMKThread: NSObject {
@objc(mutedUntilDateFor:)
public static func mutedUntilDateFor(_ threadId: String) -> Date? {
return GRDBStorage.shared.read { db in
return Storage.shared.read { db in
return try SessionThread
.select(SessionThread.Columns.mutedUntilTimestamp)
.filter(id: threadId)
@ -329,7 +329,7 @@ public class SMKThread: NSObject {
@objc(updateWithMutedUntilDateTo:forThreadId:)
public static func updateWithMutedUntilDate(to date: Date?, threadId: String) {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try SessionThread
.filter(id: threadId)
.updateAll(db, SessionThread.Columns.mutedUntilTimestamp.set(to: date?.timeIntervalSince1970))

View File

@ -22,7 +22,7 @@ public enum AttachmentDownloadJob: JobExecutor {
let threadId: String = job.threadId,
let detailsData: Data = job.details,
let details: Details = try? JSONDecoder().decode(Details.self, from: detailsData),
let attachment: Attachment = GRDBStorage.shared
let attachment: Attachment = Storage.shared
.read({ db in try Attachment.fetchOne(db, id: details.attachmentId) })
else {
failure(job, JobRunnerError.missingRequiredDetails, false)
@ -57,7 +57,7 @@ public enum AttachmentDownloadJob: JobExecutor {
// then we should update the state of the attachment to be failed to avoid having attachments
// appear in an endlessly downloading state
if !otherCurrentJobAttachmentIds.contains(attachment.id) {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
_ = try Attachment
.filter(id: attachment.id)
.updateAll(db, Attachment.Columns.state.set(to: Attachment.State.failedDownload))
@ -75,7 +75,7 @@ public enum AttachmentDownloadJob: JobExecutor {
}
// Update to the 'downloading' state (no need to update the 'attachment' instance)
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try Attachment
.filter(id: attachment.id)
.updateAll(db, Attachment.Columns.state.set(to: Attachment.State.downloading))
@ -93,7 +93,7 @@ public enum AttachmentDownloadJob: JobExecutor {
return Promise(error: AttachmentDownloadError.invalidUrl)
}
let maybeOpenGroupDownloadPromise: Promise<Data>? = GRDBStorage.shared.read({ db in
let maybeOpenGroupDownloadPromise: Promise<Data>? = Storage.shared.read({ db in
guard let openGroup: OpenGroup = try OpenGroup.fetchOne(db, id: threadId) else {
return nil // Not an open group so just use standard FileServer upload
}
@ -142,7 +142,7 @@ public enum AttachmentDownloadJob: JobExecutor {
///
/// **Note:** We **MUST** use the `'with()` function here as it will update the
/// `isValid` and `duration` values based on the downloaded data and the state
GRDBStorage.shared.write { db in
Storage.shared.write { db in
_ = try attachment
.with(
state: .downloaded,
@ -189,7 +189,7 @@ public enum AttachmentDownloadJob: JobExecutor {
///
/// **Note:** We **MUST** use the `'with()` function here as it will update the
/// `isValid` and `duration` values based on the downloaded data and the state
GRDBStorage.shared.write { db in
Storage.shared.write { db in
_ = try Attachment
.filter(id: attachment.id)
.updateAll(db, Attachment.Columns.state.set(to: targetState))

View File

@ -22,7 +22,7 @@ public enum AttachmentUploadJob: JobExecutor {
let threadId: String = job.threadId,
let detailsData: Data = job.details,
let details: Details = try? JSONDecoder().decode(Details.self, from: detailsData),
let (attachment, openGroup): (Attachment, OpenGroup?) = GRDBStorage.shared.read({ db in
let (attachment, openGroup): (Attachment, OpenGroup?) = Storage.shared.read({ db in
guard let attachment: Attachment = try Attachment.fetchOne(db, id: details.attachmentId) else {
return nil
}

View File

@ -20,7 +20,7 @@ public enum DisappearingMessagesJob: JobExecutor {
let timestampNowMs: TimeInterval = (Date().timeIntervalSince1970 * 1000)
var backgroundTask: OWSBackgroundTask? = OWSBackgroundTask(label: #function)
let updatedJob: Job? = GRDBStorage.shared.write { db in
let updatedJob: Job? = Storage.shared.write { db in
_ = try Interaction
.filter(Interaction.Columns.expiresStartedAtMs != nil)
.filter((Interaction.Columns.expiresStartedAtMs + (Interaction.Columns.expiresInSeconds * 1000)) <= timestampNowMs)

View File

@ -18,7 +18,7 @@ public enum FailedAttachmentDownloadsJob: JobExecutor {
deferred: @escaping (Job) -> ()
) {
// Update all 'sending' message states to 'failed'
GRDBStorage.shared.write { db in
Storage.shared.write { db in
let changeCount: Int = try Attachment
.filter(Attachment.Columns.state == Attachment.State.downloading)
.updateAll(db, Attachment.Columns.state.set(to: Attachment.State.failedDownload))

View File

@ -18,7 +18,7 @@ public enum FailedMessageSendsJob: JobExecutor {
deferred: @escaping (Job) -> ()
) {
// Update all 'sending' message states to 'failed'
GRDBStorage.shared.write { db in
Storage.shared.write { db in
let changeCount: Int = try RecipientState
.filter(RecipientState.Columns.state == RecipientState.State.sending)
.updateAll(db, RecipientState.Columns.state.set(to: RecipientState.State.failed))

View File

@ -34,7 +34,7 @@ public enum GarbageCollectionJob: JobExecutor {
.defaulting(to: Types.allCases)
let timestampNow: TimeInterval = Date().timeIntervalSince1970
GRDBStorage.shared.writeAsync(
Storage.shared.writeAsync(
updates: { db in
/// Remove any expired controlMessageProcessRecords
if typesToCollect.contains(.expiredControlMessageProcessRecords) {
@ -229,7 +229,7 @@ public enum GarbageCollectionJob: JobExecutor {
let profileAvatarFilenames: Set<String>
}
let maybeFileInfo: FileInfo? = GRDBStorage.shared.read { db -> FileInfo in
let maybeFileInfo: FileInfo? = Storage.shared.read { db -> FileInfo in
var attachmentLocalRelativePaths: Set<String> = []
var profileAvatarFilenames: Set<String> = []

View File

@ -28,7 +28,7 @@ public enum MessageReceiveJob: JobExecutor {
var updatedJob: Job = job
var leastSevereError: Error?
GRDBStorage.shared.write { db in
Storage.shared.write { db in
var remainingMessagesToProcess: [Details.MessageInfo] = []
for messageInfo in details.messages {

View File

@ -41,7 +41,7 @@ public enum MessageSendJob: JobExecutor {
//
// Note: Normal attachments should be sent in a non-durable way but any
// attachments for LinkPreviews and Quotes will be processed through this mechanism
let attachmentState: (shouldFail: Bool, shouldDefer: Bool)? = GRDBStorage.shared.write { db in
let attachmentState: (shouldFail: Bool, shouldDefer: Bool)? = Storage.shared.write { db in
let allAttachmentStateInfo: [Attachment.StateInfo] = try Attachment
.stateInfo(interactionId: interactionId)
.fetchAll(db)
@ -131,7 +131,7 @@ public enum MessageSendJob: JobExecutor {
details.message.threadId = (details.message.threadId ?? job.threadId)
// Perform the actual message sending
GRDBStorage.shared.writeAsync { db -> Promise<Void> in
Storage.shared.writeAsync { db -> Promise<Void> in
try MessageSender.sendImmediate(
db,
message: details.message,
@ -160,7 +160,7 @@ public enum MessageSendJob: JobExecutor {
if details.message is VisibleMessage {
guard
let interactionId: Int64 = job.interactionId,
GRDBStorage.shared.read({ db in try Interaction.exists(db, id: interactionId) }) == true
Storage.shared.read({ db in try Interaction.exists(db, id: interactionId) }) == true
else {
// The message has been deleted so permanently fail the job
failure(job, error, true)

View File

@ -27,7 +27,7 @@ public enum RetrieveDefaultOpenGroupRoomsJob: JobExecutor {
// in the database so we need to create a dummy one to retrieve the default room data
let defaultGroupId: String = OpenGroup.idFor(roomToken: "", server: OpenGroupAPI.defaultServer)
GRDBStorage.shared.write { db in
Storage.shared.write { db in
guard try OpenGroup.exists(db, id: defaultGroupId) == false else { return }
_ = try OpenGroup(

View File

@ -35,7 +35,7 @@ public enum SendReadReceiptsJob: JobExecutor {
return
}
GRDBStorage.shared
Storage.shared
.writeAsync { db in
try MessageSender.sendImmediate(
db,
@ -53,7 +53,7 @@ public enum SendReadReceiptsJob: JobExecutor {
var shouldFinishCurrentJob: Bool = false
let nextRunTimestamp: TimeInterval = (Date().timeIntervalSince1970 + minRunFrequency)
let updatedJob: Job? = GRDBStorage.shared.write { db in
let updatedJob: Job? = Storage.shared.write { db in
// If another 'sendReadReceipts' job was scheduled then update that one
// to run at 'nextRunTimestamp' and make the current job stop
if

View File

@ -911,7 +911,7 @@ extension OpenGroupManager {
cache: Atomic<OGMCacheType>? = nil,
onionApi: OnionRequestAPIType.Type? = nil,
generalCache: Atomic<GeneralCacheType>? = nil,
storage: GRDBStorage? = nil,
storage: Storage? = nil,
sodium: SodiumType? = nil,
box: BoxType? = nil,
genericHash: GenericHashType? = nil,

View File

@ -178,7 +178,7 @@ extension MessageSender {
)
.done {
/// Store it **after** having sent out the message to the group
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try newKeyPair.insert(db)
distributingKeyPairs.mutate {
@ -514,7 +514,7 @@ extension MessageSender {
// Remove the group from the database and unsubscribe from PNs
ClosedGroupPoller.shared.stopPolling(for: groupPublicKey)
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try closedGroup
.keyPairs
.deleteAll(db)

View File

@ -166,7 +166,7 @@ extension MessageSender {
if let error: Error = errors.first { return Promise(error: error) }
return GRDBStorage.shared.writeAsync { db in
return Storage.shared.writeAsync { db in
try MessageSender.sendImmediate(
db,
message: message,

View File

@ -221,7 +221,7 @@ public final class MessageSender {
guard !isSuccess else { return } // Succeed as soon as the first promise succeeds
isSuccess = true
GRDBStorage.shared.write { db in
Storage.shared.write { db in
let responseJson: JSON? = try? JSONSerialization.jsonObject(with: responseData, options: [ .fragmentsAllowed ]) as? JSON
message.serverHash = (responseJson?["hash"] as? String)
@ -291,7 +291,7 @@ public final class MessageSender {
errorCount += 1
guard errorCount == promiseCount else { return } // Only error out if all promises failed
GRDBStorage.shared.write { db in
Storage.shared.write { db in
handleFailure(db, with: .other(error))
}
}
@ -300,7 +300,7 @@ public final class MessageSender {
.catch(on: DispatchQueue.global(qos: .default)) { error in
SNLog("Couldn't send message due to error: \(error).")
GRDBStorage.shared.write { db in
Storage.shared.write { db in
handleFailure(db, with: .other(error))
}
}
@ -682,7 +682,7 @@ public final class MessageSender {
public class SMKMessageSender: NSObject {
@objc(leaveClosedGroupWithPublicKey:)
public static func objc_leave(_ groupPublicKey: String) -> AnyPromise {
let promise = GRDBStorage.shared.writeAsync { db in
let promise = Storage.shared.writeAsync { db in
try MessageSender.leave(db, groupPublicKey: groupPublicKey)
}
@ -691,7 +691,7 @@ public class SMKMessageSender: NSObject {
@objc(forceSyncConfigurationNow)
public static func objc_forceSyncConfigurationNow() {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try MessageSender.syncConfiguration(db, forceSyncNow: true).retainUntilComplete()
}
}

View File

@ -70,7 +70,7 @@ public final class PushNotificationAPI : NSObject {
}
// Unsubscribe from all closed groups (including ones the user is no longer a member of, just in case)
GRDBStorage.shared.read { db in
Storage.shared.read { db in
let userPublicKey: String = getUserHexEncodedPublicKey(db)
try ClosedGroup
@ -133,7 +133,7 @@ public final class PushNotificationAPI : NSObject {
}
// Subscribe to all closed groups
GRDBStorage.shared.read { db in
Storage.shared.read { db in
try ClosedGroup
.select(.threadId)
.joining(

View File

@ -38,7 +38,7 @@ public final class ClosedGroupPoller {
@objc public func start() {
// Fetch all closed groups (excluding any don't contain the current user as a
// GroupMemeber as the user is no longer a member of those)
GRDBStorage.shared
Storage.shared
.read { db in
try ClosedGroup
.select(.threadId)
@ -66,7 +66,7 @@ public final class ClosedGroupPoller {
}
@objc public func stop() {
GRDBStorage.shared
Storage.shared
.read { db in
try ClosedGroup
.select(.threadId)
@ -102,13 +102,13 @@ public final class ClosedGroupPoller {
private func pollRecursively(_ groupPublicKey: String) {
guard
isPolling.wrappedValue[groupPublicKey] == true,
let thread: SessionThread = GRDBStorage.shared.read({ db in try SessionThread.fetchOne(db, id: groupPublicKey) })
let thread: SessionThread = Storage.shared.read({ db in try SessionThread.fetchOne(db, id: groupPublicKey) })
else { return }
// Get the received date of the last message in the thread. If we don't have any messages yet, pick some
// reasonable fake time interval to use instead
let lastMessageDate: Date = GRDBStorage.shared
let lastMessageDate: Date = Storage.shared
.read { db in
try thread
.interactions
@ -200,7 +200,7 @@ public final class ClosedGroupPoller {
var jobToRun: Job?
GRDBStorage.shared.write { db in
Storage.shared.write { db in
var jobDetailMessages: [MessageReceiveJob.Details.MessageInfo] = []
messages.forEach { message in

View File

@ -135,7 +135,7 @@ public final class Poller {
if !messages.isEmpty {
var messageCount: Int = 0
GRDBStorage.shared.write { db in
Storage.shared.write { db in
var threadMessages: [String: [MessageReceiveJob.Details.MessageInfo]] = [:]
messages.forEach { message in

View File

@ -32,7 +32,7 @@ public class TypingIndicators {
// or show typing indicators for other users
//
// We also don't want to show/send typing indicators for message requests
guard GRDBStorage.shared[.typingIndicatorsEnabled] && !threadIsMessageRequest else {
guard Storage.shared[.typingIndicatorsEnabled] && !threadIsMessageRequest else {
return nil
}
@ -67,7 +67,7 @@ public class TypingIndicators {
withTimeInterval: (direction == .outgoing ? 3 : 5),
repeats: false
) { [weak self] _ in
GRDBStorage.shared.write { db in
Storage.shared.write { db in
self?.stoping(db)
}
}
@ -122,7 +122,7 @@ public class TypingIndicators {
withTimeInterval: 10,
repeats: false
) { [weak self] _ in
GRDBStorage.shared.write { db in
Storage.shared.write { db in
self?.scheduleRefreshCallback(db)
}
}

View File

@ -317,13 +317,13 @@ public class SMKPreferences: NSObject {
}
@objc public static func notificationPreviewType() -> Int {
return GRDBStorage.shared[.preferencesNotificationPreviewType]
return Storage.shared[.preferencesNotificationPreviewType]
.defaulting(to: Preferences.NotificationPreviewType.nameAndPreview)
.rawValue
}
@objc public static func setNotificationPreviewType(_ previewType: Int) {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
db[.preferencesNotificationPreviewType] = Preferences.NotificationPreviewType(rawValue: previewType)
.defaulting(to: .nameAndPreview)
}
@ -342,62 +342,62 @@ public class SMKPreferences: NSObject {
@objc(setPlayNotificationSoundInForeground:)
static func objc_setPlayNotificationSoundInForeground(_ enabled: Bool) {
GRDBStorage.shared.write { db in db[.playNotificationSoundInForeground] = enabled }
Storage.shared.write { db in db[.playNotificationSoundInForeground] = enabled }
}
@objc(playNotificationSoundInForeground)
static func objc_playNotificationSoundInForeground() -> Bool {
return GRDBStorage.shared[.playNotificationSoundInForeground]
return Storage.shared[.playNotificationSoundInForeground]
}
@objc(setScreenSecurity:)
static func objc_setScreenSecurity(_ enabled: Bool) {
GRDBStorage.shared.write { db in db[.appSwitcherPreviewEnabled] = enabled }
Storage.shared.write { db in db[.appSwitcherPreviewEnabled] = enabled }
}
@objc(isScreenSecurityEnabled)
static func objc_isScreenSecurityEnabled() -> Bool {
return GRDBStorage.shared[.appSwitcherPreviewEnabled]
return Storage.shared[.appSwitcherPreviewEnabled]
}
@objc(setAreReadReceiptsEnabled:)
static func objc_setAreReadReceiptsEnabled(_ enabled: Bool) {
GRDBStorage.shared.write { db in db[.areReadReceiptsEnabled] = enabled }
Storage.shared.write { db in db[.areReadReceiptsEnabled] = enabled }
}
@objc(areReadReceiptsEnabled)
static func objc_areReadReceiptsEnabled() -> Bool {
return GRDBStorage.shared[.areReadReceiptsEnabled]
return Storage.shared[.areReadReceiptsEnabled]
}
@objc(setTypingIndicatorsEnabled:)
static func objc_setTypingIndicatorsEnabled(_ enabled: Bool) {
GRDBStorage.shared.write { db in db[.typingIndicatorsEnabled] = enabled }
Storage.shared.write { db in db[.typingIndicatorsEnabled] = enabled }
}
@objc(areTypingIndicatorsEnabled)
static func objc_areTypingIndicatorsEnabled() -> Bool {
return GRDBStorage.shared[.typingIndicatorsEnabled]
return Storage.shared[.typingIndicatorsEnabled]
}
@objc(setLinkPreviewsEnabled:)
static func objc_setLinkPreviewsEnabled(_ enabled: Bool) {
GRDBStorage.shared.write { db in db[.areLinkPreviewsEnabled] = enabled }
Storage.shared.write { db in db[.areLinkPreviewsEnabled] = enabled }
}
@objc(areLinkPreviewsEnabled)
static func objc_areLinkPreviewsEnabled() -> Bool {
return GRDBStorage.shared[.areLinkPreviewsEnabled]
return Storage.shared[.areLinkPreviewsEnabled]
}
@objc(setCallsEnabled:)
static func objc_setCallsEnabled(_ enabled: Bool) {
GRDBStorage.shared.write { db in db[.areCallsEnabled] = enabled }
Storage.shared.write { db in db[.areCallsEnabled] = enabled }
}
@objc(areCallsEnabled)
static func objc_areCallsEnabled() -> Bool {
return GRDBStorage.shared[.areCallsEnabled]
return Storage.shared[.areCallsEnabled]
}
}
@ -420,7 +420,7 @@ public class SMKSound: NSObject {
}
@objc public static var defaultNotificationSound: Int {
return GRDBStorage.shared[.defaultNotificationSound]
return Storage.shared[.defaultNotificationSound]
.defaulting(to: Preferences.Sound.defaultNotificationSound)
.rawValue
}
@ -428,7 +428,7 @@ public class SMKSound: NSObject {
@objc public static func setGlobalNotificationSound(_ sound: Int) {
guard let sound: Preferences.Sound = Preferences.Sound(rawValue: sound) else { return }
GRDBStorage.shared.write { db in
Storage.shared.write { db in
db[.defaultNotificationSound] = sound
}
}
@ -436,7 +436,7 @@ public class SMKSound: NSObject {
@objc public static func notificationSound(for threadId: String?) -> Int {
guard let threadId: String = threadId else { return defaultNotificationSound }
return (GRDBStorage.shared
return (Storage.shared
.read { db in
try Preferences.Sound
.fetchOne(
@ -453,7 +453,7 @@ public class SMKSound: NSObject {
@objc public static func setNotificationSound(_ sound: Int, forThreadId threadId: String) {
guard let sound: Preferences.Sound = Preferences.Sound(rawValue: sound) else { return }
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try SessionThread
.filter(id: threadId)
.updateAll(db, SessionThread.Columns.notificationSound.set(to: sound))

View File

@ -23,7 +23,7 @@ public struct ProfileManager {
public static func profileAvatar(_ db: Database? = nil, id: String) -> UIImage? {
guard let db: Database = db else {
return GRDBStorage.shared.read { db in profileAvatar(db, id: id) }
return Storage.shared.read { db in profileAvatar(db, id: id) }
}
guard let profile: Profile = try? Profile.fetchOne(db, id: id) else { return nil }
@ -145,7 +145,7 @@ public struct ProfileManager {
.done(on: queue) { data in
currentAvatarDownloads.mutate { $0.remove(profile.id) }
GRDBStorage.shared.write { db in
Storage.shared.write { db in
guard let latestProfile: Profile = try Profile.fetchOne(db, id: profile.id) else {
return
}
@ -218,7 +218,7 @@ public struct ProfileManager {
guard let avatarImage: UIImage = avatarImage else {
// If we have no image then we need to make sure to remove it from the profile
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
let existingProfile: Profile = Profile.fetchOrCreateCurrentUser(db)
OWSLogger.verbose(existingProfile.profilePictureUrl != nil ?
@ -309,7 +309,7 @@ public struct ProfileManager {
let downloadUrl: String = "\(FileServerAPI.server)/files/\(fileId)"
UserDefaults.standard[.lastProfilePictureUpload] = Date()
GRDBStorage.shared.writeAsync { db in
Storage.shared.writeAsync { db in
let profile: Profile = try Profile
.fetchOrCreateCurrentUser(db)
.with(

View File

@ -65,7 +65,7 @@ public class SMKDependencies: Dependencies {
public init(
onionApi: OnionRequestAPIType.Type? = nil,
generalCache: Atomic<GeneralCacheType>? = nil,
storage: GRDBStorage? = nil,
storage: Storage? = nil,
sodium: SodiumType? = nil,
box: BoxType? = nil,
genericHash: GenericHashType? = nil,

View File

@ -15,7 +15,7 @@ class OpenGroupAPISpec: QuickSpec {
// MARK: - Spec
override func spec() {
var mockStorage: GRDBStorage!
var mockStorage: Storage!
var mockSodium: MockSodium!
var mockAeadXChaCha20Poly1305Ietf: MockAeadXChaCha20Poly1305Ietf!
var mockSign: MockSign!
@ -33,7 +33,7 @@ class OpenGroupAPISpec: QuickSpec {
// MARK: - Configuration
beforeEach {
mockStorage = GRDBStorage(
mockStorage = Storage(
customWriter: DatabaseQueue(),
customMigrations: [
SNUtilitiesKit.migrations(),

View File

@ -73,7 +73,7 @@ class OpenGroupManagerSpec: QuickSpec {
override func spec() {
var mockOGMCache: MockOGMCache!
var mockGeneralCache: MockGeneralCache!
var mockStorage: GRDBStorage!
var mockStorage: Storage!
var mockSodium: MockSodium!
var mockAeadXChaCha20Poly1305Ietf: MockAeadXChaCha20Poly1305Ietf!
var mockGenericHash: MockGenericHash!
@ -99,7 +99,7 @@ class OpenGroupManagerSpec: QuickSpec {
beforeEach {
mockOGMCache = MockOGMCache()
mockGeneralCache = MockGeneralCache()
mockStorage = GRDBStorage(
mockStorage = Storage(
customWriter: DatabaseQueue(),
customMigrations: [
SNUtilitiesKit.migrations(),

View File

@ -14,7 +14,7 @@ class MessageReceiverDecryptionSpec: QuickSpec {
// MARK: - Spec
override func spec() {
var mockStorage: GRDBStorage!
var mockStorage: Storage!
var mockSodium: MockSodium!
var mockBox: MockBox!
var mockGenericHash: MockGenericHash!
@ -25,7 +25,7 @@ class MessageReceiverDecryptionSpec: QuickSpec {
describe("a MessageReceiver") {
beforeEach {
mockStorage = GRDBStorage(
mockStorage = Storage(
customWriter: DatabaseQueue(),
customMigrations: [
SNUtilitiesKit.migrations(),

View File

@ -14,7 +14,7 @@ class MessageSenderEncryptionSpec: QuickSpec {
// MARK: - Spec
override func spec() {
var mockStorage: GRDBStorage!
var mockStorage: Storage!
var mockBox: MockBox!
var mockSign: MockSign!
var mockNonce24Generator: MockNonce24Generator!
@ -22,7 +22,7 @@ class MessageSenderEncryptionSpec: QuickSpec {
describe("a MessageSender") {
beforeEach {
mockStorage = GRDBStorage(
mockStorage = Storage(
customWriter: DatabaseQueue(),
customMigrations: [
SNUtilitiesKit.migrations(),

View File

@ -10,7 +10,7 @@ extension SMKDependencies {
public func with(
onionApi: OnionRequestAPIType.Type? = nil,
generalCache: Atomic<GeneralCacheType>? = nil,
storage: GRDBStorage? = nil,
storage: Storage? = nil,
sodium: SodiumType? = nil,
box: BoxType? = nil,
genericHash: GenericHashType? = nil,

View File

@ -11,7 +11,7 @@ extension OpenGroupManager.OGMDependencies {
cache: Atomic<OGMCacheType>? = nil,
onionApi: OnionRequestAPIType.Type? = nil,
generalCache: Atomic<GeneralCacheType>? = nil,
storage: GRDBStorage? = nil,
storage: Storage? = nil,
sodium: SodiumType? = nil,
box: BoxType? = nil,
genericHash: GenericHashType? = nil,

View File

@ -60,7 +60,7 @@ public final class NotificationServiceExtension: UNNotificationServiceExtension
// HACK: It is important to use write synchronously here to avoid a race condition
// where the completeSilenty() is called before the local notification request
// is added to notification center
GRDBStorage.shared.write { db in
Storage.shared.write { db in
do {
guard let processedMessage: ProcessedMessage = try Message.processRawReceivedMessageAsNotification(db, envelope: envelope) else {
self.handleFailure(for: notificationContent)
@ -164,7 +164,7 @@ public final class NotificationServiceExtension: UNNotificationServiceExtension
// this path should never occur. However, the service does have our push token
// so it is possible that could change in the future. If it does, do nothing
// and don't disturb the user. Messages will be processed when they open the app.
guard GRDBStorage.shared[.isReadyForAppExtensions] else { return completeSilenty() }
guard Storage.shared[.isReadyForAppExtensions] else { return completeSilenty() }
AppSetup.setupEnvironment(
appSpecificBlock: {
@ -187,7 +187,7 @@ public final class NotificationServiceExtension: UNNotificationServiceExtension
// If we need a config sync then trigger it now
if needsConfigSync {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try MessageSender.syncConfiguration(db, forceSyncNow: true).retainUntilComplete()
}
}
@ -203,7 +203,7 @@ public final class NotificationServiceExtension: UNNotificationServiceExtension
guard !AppReadiness.isAppReady() else { return }
// App isn't ready until storage is ready AND all version migrations are complete.
guard GRDBStorage.shared.isValid && areVersionMigrationsComplete else { return }
guard Storage.shared.isValid && areVersionMigrationsComplete else { return }
SignalUtilitiesKit.Configuration.performMainSetup()
@ -297,7 +297,7 @@ public final class NotificationServiceExtension: UNNotificationServiceExtension
// MARK: - Poll for open groups
private func pollForOpenGroups() -> [Promise<Void>] {
let promises: [Promise<Void>] = GRDBStorage.shared
let promises: [Promise<Void>] = Storage.shared
.read { db in
// The default room promise creates an OpenGroup with an empty `roomToken` value,
// we don't want to start a poller for this as the user hasn't actually joined a room

View File

@ -74,7 +74,7 @@ final class ShareVC : UINavigationController, ShareViewDelegate, AppModeManagerD
// If we need a config sync then trigger it now
if needsConfigSync {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try? MessageSender.syncConfiguration(db, forceSyncNow: true).retainUntilComplete()
}
}
@ -88,7 +88,7 @@ final class ShareVC : UINavigationController, ShareViewDelegate, AppModeManagerD
// App isn't ready until storage is ready AND all version migrations are complete.
guard areVersionMigrationsComplete else { return }
guard GRDBStorage.shared.isValid else { return }
guard Storage.shared.isValid else { return }
guard !AppReadiness.isAppReady() else {
// Only mark the app as ready once.
return

View File

@ -143,7 +143,7 @@ final class ThreadPickerVC: UIViewController, UITableViewDataSource, UITableView
private func startObservingChanges() {
// Start observing for data changes
dataChangeObservable = GRDBStorage.shared.start(
dataChangeObservable = Storage.shared.start(
viewModel.observableViewData,
onError: { _ in },
onChange: { [weak self] viewData in
@ -220,7 +220,7 @@ final class ThreadPickerVC: UIViewController, UITableViewDataSource, UITableView
shareVC?.dismiss(animated: true, completion: nil)
ModalActivityIndicatorViewController.present(fromViewController: shareVC!, canCancel: false, message: "vc_share_sending_message".localized()) { activityIndicator in
GRDBStorage.shared
Storage.shared
.writeAsync { [weak self] db -> Promise<Void> in
guard let thread: SessionThread = try SessionThread.fetchOne(db, id: threadId) else {
activityIndicator.dismiss { }

View File

@ -52,6 +52,6 @@ enum _001_InitialSetupMigration: Migration {
t.uniqueKey([.key, .hash])
}
GRDBStorage.update(progress: 1, for: self, in: target) // In case this is the last migration
Storage.update(progress: 1, for: self, in: target) // In case this is the last migration
}
}

View File

@ -21,6 +21,6 @@ enum _002_SetupStandardJobs: Migration {
).inserted(db)
}
GRDBStorage.update(progress: 1, for: self, in: target) // In case this is the last migration
Storage.update(progress: 1, for: self, in: target) // In case this is the last migration
}
}

View File

@ -67,7 +67,7 @@ enum _003_YDBToGRDBMigration: Migration {
snodeSetResult["\(SnodeSet.onionRequestPathPrefix)1"] = [ path1Snode0, path1Snode1, path1Snode2 ]
}
}
GRDBStorage.update(progress: 0.02, for: self, in: target)
Storage.update(progress: 0.02, for: self, in: target)
// MARK: --SnodePool
@ -100,7 +100,7 @@ enum _003_YDBToGRDBMigration: Migration {
collectionIndex += 1
GRDBStorage.update(
Storage.update(
progress: min(
swarmCompleteProgress,
((collectionIndex / roughNumCollections) * (swarmCompleteProgress - startProgress))
@ -109,7 +109,7 @@ enum _003_YDBToGRDBMigration: Migration {
in: target
)
}
GRDBStorage.update(progress: swarmCompleteProgress, for: self, in: target)
Storage.update(progress: swarmCompleteProgress, for: self, in: target)
for swarmCollection in swarmCollections {
let collection: String = "\(SSKLegacy.swarmCollectionPrefix)\(swarmCollection)"
@ -120,7 +120,7 @@ enum _003_YDBToGRDBMigration: Migration {
snodeSetResult[swarmCollection] = (snodeSetResult[swarmCollection] ?? Set()).inserting(snode)
}
}
GRDBStorage.update(progress: 0.92, for: self, in: target)
Storage.update(progress: 0.92, for: self, in: target)
// MARK: --Received message hashes
@ -128,7 +128,7 @@ enum _003_YDBToGRDBMigration: Migration {
guard let hashSet = object as? Set<String> else { return }
receivedMessageResults[key] = hashSet
}
GRDBStorage.update(progress: 0.93, for: self, in: target)
Storage.update(progress: 0.93, for: self, in: target)
// MARK: --Last message info
@ -141,7 +141,7 @@ enum _003_YDBToGRDBMigration: Migration {
lastMessageResults[key] = (lastMessageHash, lastMessageJson)
receivedMessageResults[key] = receivedMessageResults[key]?.removing(lastMessageHash)
}
GRDBStorage.update(progress: 0.94, for: self, in: target)
Storage.update(progress: 0.94, for: self, in: target)
}
// MARK: - Insert into GRDB
@ -161,7 +161,7 @@ enum _003_YDBToGRDBMigration: Migration {
x25519PublicKey: legacySnode.publicKeySet.x25519Key
).insert(db)
}
GRDBStorage.update(progress: 0.96, for: self, in: target)
Storage.update(progress: 0.96, for: self, in: target)
// MARK: --SnodeSets
@ -176,7 +176,7 @@ enum _003_YDBToGRDBMigration: Migration {
).insert(db)
}
}
GRDBStorage.update(progress: 0.98, for: self, in: target)
Storage.update(progress: 0.98, for: self, in: target)
}
try autoreleasepool {
@ -191,7 +191,7 @@ enum _003_YDBToGRDBMigration: Migration {
).inserted(db)
}
}
GRDBStorage.update(progress: 0.99, for: self, in: target)
Storage.update(progress: 0.99, for: self, in: target)
// MARK: --Last Message Hash
@ -209,6 +209,6 @@ enum _003_YDBToGRDBMigration: Migration {
}
}
GRDBStorage.update(progress: 1, for: self, in: target) // In case this is the last migration
Storage.update(progress: 1, for: self, in: target) // In case this is the last migration
}
}

View File

@ -69,7 +69,7 @@ public extension SnodeReceivedMessageInfo {
public extension SnodeReceivedMessageInfo {
static func pruneExpiredMessageHashInfo(for snode: Snode, namespace: Int, associatedWith publicKey: String) {
// Delete any expired SnodeReceivedMessageInfo values associated to a specific node
GRDBStorage.shared.write { db in
Storage.shared.write { db in
// Only prune the hashes if new hashes exist for this Snode (if they don't then we don't want
// to clear out the legacy hashes)
let hasNonLegacyHash: Bool = try SnodeReceivedMessageInfo
@ -91,7 +91,7 @@ public extension SnodeReceivedMessageInfo {
/// this method to be called after the hash value has been updated but before the various `read` threads have been updated, resulting in a
/// pointless fetch for data the app has already received
static func fetchLastNotExpired(for snode: Snode, namespace: Int, associatedWith publicKey: String) -> SnodeReceivedMessageInfo? {
return GRDBStorage.shared.read { db in
return Storage.shared.read { db in
let nonLegacyHash: SnodeReceivedMessageInfo? = try SnodeReceivedMessageInfo
.filter(SnodeReceivedMessageInfo.Columns.key == key(for: snode, publicKey: publicKey, namespace: namespace))
.filter(SnodeReceivedMessageInfo.Columns.expirationDateMs > (Date().timeIntervalSince1970 * 1000))

View File

@ -36,7 +36,7 @@ public enum OnionRequestAPI: OnionRequestAPIType {
get {
if let paths: [[Snode]] = _paths { return paths }
let results: [[Snode]]? = GRDBStorage.shared.read { db in
let results: [[Snode]]? = Storage.shared.read { db in
try? Snode.fetchAllOnionRequestPaths(db)
}
@ -180,7 +180,7 @@ public enum OnionRequestAPI: OnionRequestAPIType {
.map2 { paths in
OnionRequestAPI.paths = paths + reusablePaths
GRDBStorage.shared.write { db in
Storage.shared.write { db in
SNLog("Persisting onion request paths to database.")
try? paths.save(db)
}
@ -281,7 +281,7 @@ public enum OnionRequestAPI: OnionRequestAPIType {
let newPaths = oldPaths + [ path ]
paths = newPaths
GRDBStorage.shared.write { db in
Storage.shared.write { db in
SNLog("Persisting onion request paths to database.")
try? newPaths.save(db)
}
@ -297,7 +297,7 @@ public enum OnionRequestAPI: OnionRequestAPIType {
paths.remove(at: pathIndex)
OnionRequestAPI.paths = paths
GRDBStorage.shared.write { db in
Storage.shared.write { db in
guard !paths.isEmpty else {
SNLog("Clearing onion request paths.")
try? Snode.clearOnionRequestPaths(db)

View File

@ -53,7 +53,7 @@ public final class SnodeAPI {
private static func loadSnodePoolIfNeeded() {
guard !hasLoadedSnodePool else { return }
GRDBStorage.shared.read { db in
Storage.shared.read { db in
snodePool = ((try? Snode.fetchSet(db)) ?? Set())
}
@ -68,7 +68,7 @@ public final class SnodeAPI {
newValue.forEach { try? $0.save(db) }
}
else {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
_ = try? Snode.deleteAll(db)
newValue.forEach { try? $0.save(db) }
}
@ -96,7 +96,7 @@ public final class SnodeAPI {
private static func loadSwarmIfNeeded(for publicKey: String) {
guard !loadedSwarms.contains(publicKey) else { return }
GRDBStorage.shared.read { db in
Storage.shared.read { db in
swarmCache[publicKey] = ((try? Snode.fetchSet(db, publicKey: publicKey)) ?? [])
}
@ -110,7 +110,7 @@ public final class SnodeAPI {
swarmCache[publicKey] = newValue
guard persist else { return }
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try? newValue.save(db, key: publicKey)
}
}
@ -299,7 +299,7 @@ public final class SnodeAPI {
public static func getSnodePool() -> Promise<Set<Snode>> {
loadSnodePoolIfNeeded()
let now = Date()
let hasSnodePoolExpired = given(GRDBStorage.shared[.lastSnodePoolRefreshDate]) {
let hasSnodePoolExpired = given(Storage.shared[.lastSnodePoolRefreshDate]) {
now.timeIntervalSince($0) > 2 * 60 * 60
}.defaulting(to: true)
let snodePool: Set<Snode> = SnodeAPI.snodePool
@ -327,7 +327,7 @@ public final class SnodeAPI {
promise.then2 { snodePool -> Promise<Set<Snode>> in
let (promise, seal) = Promise<Set<Snode>>.pending()
GRDBStorage.shared.writeAsync(
Storage.shared.writeAsync(
updates: { db in
db[.lastSnodePoolRefreshDate] = now
setSnodePool(to: snodePool, db: db)
@ -537,7 +537,7 @@ public final class SnodeAPI {
private static func getMessagesWithAuthentication(from snode: Snode, associatedWith publicKey: String, namespace: Int) -> Promise<[SnodeReceivedMessage]> {
/// **Note:** All authentication logic is only apply to 1-1 chats, the reason being that we can't currently support it yet for
/// closed groups. The Storage Server requires an ed25519 key pair, but we don't have that for our closed groups.
guard let userED25519KeyPair: Box.KeyPair = GRDBStorage.shared.read({ db in Identity.fetchUserEd25519KeyPair(db) }) else {
guard let userED25519KeyPair: Box.KeyPair = Storage.shared.read({ db in Identity.fetchUserEd25519KeyPair(db) }) else {
return Promise(error: SnodeAPIError.noKeyPair)
}
@ -640,7 +640,7 @@ public final class SnodeAPI {
let messageJson: JSON = try? JSONSerialization.jsonObject(with: messageData, options: [ .fragmentsAllowed ]) as? JSON
else { return Promise(error: HTTP.Error.invalidJSON) }
guard let userED25519KeyPair: Box.KeyPair = GRDBStorage.shared.read({ db in Identity.fetchUserEd25519KeyPair(db) }) else {
guard let userED25519KeyPair: Box.KeyPair = Storage.shared.read({ db in Identity.fetchUserEd25519KeyPair(db) }) else {
return Promise(error: SnodeAPIError.noKeyPair)
}

View File

@ -65,6 +65,6 @@ enum _001_InitialSetupMigration: Migration {
t.column(.value, .blob).notNull()
}
GRDBStorage.update(progress: 1, for: self, in: target) // In case this is the last migration
Storage.update(progress: 1, for: self, in: target) // In case this is the last migration
}
}

View File

@ -21,6 +21,6 @@ enum _002_SetupStandardJobs: Migration {
).inserted(db)
}
GRDBStorage.update(progress: 1, for: self, in: target) // In case this is the last migration
Storage.update(progress: 1, for: self, in: target) // In case this is the last migration
}
}

View File

@ -114,6 +114,6 @@ enum _003_YDBToGRDBMigration: Migration {
).insert(db)
}
GRDBStorage.update(progress: 1, for: self, in: target) // In case this is the last migration
Storage.update(progress: 1, for: self, in: target) // In case this is the last migration
}
}

View File

@ -70,7 +70,7 @@ public extension Identity {
}
static func store(seed: Data, ed25519KeyPair: Sign.KeyPair, x25519KeyPair: ECKeyPair) {
GRDBStorage.shared.write { db in
Storage.shared.write { db in
try Identity(variant: .seed, data: seed).save(db)
try Identity(variant: .ed25519SecretKey, data: Data(ed25519KeyPair.secretKey)).save(db)
try Identity(variant: .ed25519PublicKey, data: Data(ed25519KeyPair.publicKey)).save(db)
@ -85,7 +85,7 @@ public extension Identity {
static func fetchUserPublicKey(_ db: Database? = nil) -> Data? {
guard let db: Database = db else {
return GRDBStorage.shared.read { db in fetchUserPublicKey(db) }
return Storage.shared.read { db in fetchUserPublicKey(db) }
}
return try? Identity.fetchOne(db, id: .x25519PublicKey)?.data
@ -93,7 +93,7 @@ public extension Identity {
static func fetchUserPrivateKey(_ db: Database? = nil) -> Data? {
guard let db: Database = db else {
return GRDBStorage.shared.read { db in fetchUserPrivateKey(db) }
return Storage.shared.read { db in fetchUserPrivateKey(db) }
}
return try? Identity.fetchOne(db, id: .x25519PrivateKey)?.data
@ -101,7 +101,7 @@ public extension Identity {
static func fetchUserKeyPair(_ db: Database? = nil) -> Box.KeyPair? {
guard let db: Database = db else {
return GRDBStorage.shared.read { db in fetchUserKeyPair(db) }
return Storage.shared.read { db in fetchUserKeyPair(db) }
}
guard
let publicKey: Data = fetchUserPublicKey(db),
@ -116,7 +116,7 @@ public extension Identity {
static func fetchUserEd25519KeyPair(_ db: Database? = nil) -> Box.KeyPair? {
guard let db: Database = db else {
return GRDBStorage.shared.read { db in fetchUserEd25519KeyPair(db) }
return Storage.shared.read { db in fetchUserEd25519KeyPair(db) }
}
guard
let publicKey: Data = try? Identity.fetchOne(db, id: .ed25519PublicKey)?.data,
@ -130,7 +130,7 @@ public extension Identity {
}
static func fetchHexEncodedSeed() -> String? {
return GRDBStorage.shared.read { db in
return Storage.shared.read { db in
guard let data: Data = try? Identity.fetchOne(db, id: .seed)?.data else {
return nil
}
@ -159,7 +159,7 @@ public extension Identity {
public class SUKIdentity: NSObject {
@objc(userExists)
public static func userExists() -> Bool {
return GRDBStorage.shared
return Storage.shared
.read { db in Identity.userExists(db) }
.defaulting(to: false)
}

View File

@ -148,7 +148,7 @@ public protocol EnumSetting: RawRepresentable where RawValue == Int {}
// MARK: - GRDB Interactions
public extension GRDBStorage {
public extension Storage {
subscript(key: Setting.BoolKey) -> Bool {
// Default to false if it doesn't exist
return (read { db in db[key] } ?? false)

View File

@ -5,16 +5,16 @@ import GRDB
import PromiseKit
import SignalCoreKit
public final class GRDBStorage {
public final class Storage {
private static let dbFileName: String = "Session.sqlite"
private static let keychainService: String = "TSKeyChainService"
private static let dbCipherKeySpecKey: String = "GRDBDatabaseCipherKeySpec"
private static let kSQLCipherKeySpecLength: Int32 = 48
private static var sharedDatabaseDirectoryPath: String { "\(OWSFileSystem.appSharedDataDirectoryPath())/database" }
private static var databasePath: String { "\(GRDBStorage.sharedDatabaseDirectoryPath)/\(GRDBStorage.dbFileName)" }
private static var databasePathShm: String { "\(GRDBStorage.sharedDatabaseDirectoryPath)/\(GRDBStorage.dbFileName)-shm" }
private static var databasePathWal: String { "\(GRDBStorage.sharedDatabaseDirectoryPath)/\(GRDBStorage.dbFileName)-wal" }
private static var databasePath: String { "\(Storage.sharedDatabaseDirectoryPath)/\(Storage.dbFileName)" }
private static var databasePathShm: String { "\(Storage.sharedDatabaseDirectoryPath)/\(Storage.dbFileName)-shm" }
private static var databasePathWal: String { "\(Storage.sharedDatabaseDirectoryPath)/\(Storage.dbFileName)-wal" }
public static var isDatabasePasswordAccessible: Bool {
guard (try? getDatabaseCipherKeySpec()) != nil else { return false }
@ -22,7 +22,7 @@ public final class GRDBStorage {
return true
}
public static let shared: GRDBStorage = GRDBStorage()
public static let shared: Storage = Storage()
public private(set) var isValid: Bool = false
public private(set) var hasCompletedMigrations: Bool = false
@ -36,11 +36,10 @@ public final class GRDBStorage {
customWriter: DatabaseWriter? = nil,
customMigrations: [TargetMigrations]? = nil
) {
// Create the database directory if needed and ensure it's protection level is set before attempting to
// create the database KeySpec or the database itself
OWSFileSystem.ensureDirectoryExists(GRDBStorage.sharedDatabaseDirectoryPath)
OWSFileSystem.protectFileOrFolder(atPath: GRDBStorage.sharedDatabaseDirectoryPath)
OWSFileSystem.ensureDirectoryExists(Storage.sharedDatabaseDirectoryPath)
OWSFileSystem.protectFileOrFolder(atPath: Storage.sharedDatabaseDirectoryPath)
// If a custom writer was provided then use that (for unit testing)
guard customWriter == nil else {
@ -55,15 +54,16 @@ public final class GRDBStorage {
//
// Note: We reset the bytes immediately after generation to ensure the database key doesn't hang
// around in memory unintentionally
var tmpKeySpec: Data = GRDBStorage.getOrGenerateDatabaseKeySpec()
var tmpKeySpec: Data = Storage.getOrGenerateDatabaseKeySpec()
tmpKeySpec.resetBytes(in: 0..<tmpKeySpec.count)
// Configure the database and create the DatabasePool for interacting with the database
var config = Configuration()
config.maximumReaderCount = 10 // Increase the max read connection limit - Default is 5
config.prepareDatabase { db in
var keySpec: Data = GRDBStorage.getOrGenerateDatabaseKeySpec()
var keySpec: Data = Storage.getOrGenerateDatabaseKeySpec()
defer { keySpec.resetBytes(in: 0..<keySpec.count) } // Reset content immediately after use
// Use a raw key spec, where the 96 hexadecimal digits are provided
// (i.e. 64 hex for the 256 bit key, followed by 32 hex for the 128 bit salt)
// using explicit BLOB syntax, e.g.:
@ -86,7 +86,7 @@ public final class GRDBStorage {
// Create the DatabasePool to allow us to connect to the database and mark the storage as valid
do {
dbWriter = try DatabasePool(
path: "\(GRDBStorage.sharedDatabaseDirectoryPath)/\(GRDBStorage.dbFileName)",
path: "\(Storage.sharedDatabaseDirectoryPath)/\(Storage.dbFileName)",
configuration: config
)
isValid = true
@ -180,7 +180,7 @@ public final class GRDBStorage {
self?.hasCompletedMigrations = true
self?.migrationProgressUpdater = nil
SUKLegacy.clearLegacyDatabaseInstance()
// SUKLegacy.deleteLegacyDatabaseFilesAndKey() // TODO: Delete legacy database after the migration is done
// SUKLegacy.deleteLegacyDatabaseFilesAndKey() // TODO: Add a "Delete legacy database" migration to run after the '003' migrations
if let error = error {
SNLog("[Migration Error] Migration failed with error: \(error)")
@ -212,7 +212,7 @@ public final class GRDBStorage {
// would crash as it gets force-unwrapped - better to just do the check explicitly instead
guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return }
GRDBStorage.shared.migrationProgressUpdater?.wrappedValue(target.key(with: migration), progress)
Storage.shared.migrationProgressUpdater?.wrappedValue(target.key(with: migration), progress)
}
// MARK: - Security
@ -284,14 +284,15 @@ public final class GRDBStorage {
SUKLegacy.clearLegacyDatabaseInstance()
try? SUKLegacy.deleteLegacyDatabaseFilesAndKey()
GRDBStorage.shared.isValid = false
GRDBStorage.shared.hasCompletedMigrations = false
GRDBStorage.shared.dbWriter = nil
Storage.shared.isValid = false
Storage.shared.hasCompletedMigrations = false
Storage.shared.dbWriter = nil
self.deleteDatabaseFiles()
try? self.deleteDbKeys()
}
// TODO: Change these back to private
public/*private*/ static func deleteDatabaseFiles() {
OWSFileSystem.deleteFile(databasePath)
OWSFileSystem.deleteFile(databasePathShm)
@ -373,7 +374,7 @@ public final class GRDBStorage {
// MARK: - Promise Extensions
public extension GRDBStorage {
public extension Storage {
// FIXME: Would be good to replace these with Swift Combine
@discardableResult func read<T>(_ value: (Database) throws -> Promise<T>) -> Promise<T> {
guard isValid, let dbWriter: DatabaseWriter = dbWriter else {

View File

@ -375,7 +375,7 @@ public class PagedDatabaseObserver<ObservedTable, T>: TransactionObserver where
let orderSQL: SQL = self.orderSQL
let dataQuery: ([Int64]) -> AdaptedFetchRequest<SQLRequest<T>> = self.dataQuery
let loadedPage: (data: [T]?, pageInfo: PagedData.PageInfo)? = GRDBStorage.shared.read { [weak self] db in
let loadedPage: (data: [T]?, pageInfo: PagedData.PageInfo)? = Storage.shared.read { [weak self] db in
let totalCount: Int = PagedData.totalCount(
db,
tableName: pagedTableName,

View File

@ -9,9 +9,9 @@ open class Dependencies {
set { _generalCache = newValue }
}
public var _storage: GRDBStorage?
public var storage: GRDBStorage {
get { Dependencies.getValueSettingIfNull(&_storage) { GRDBStorage.shared } }
public var _storage: Storage?
public var storage: Storage {
get { Dependencies.getValueSettingIfNull(&_storage) { Storage.shared } }
set { _storage = newValue }
}
@ -31,7 +31,7 @@ open class Dependencies {
public init(
generalCache: Atomic<GeneralCacheType>? = nil,
storage: GRDBStorage? = nil,
storage: Storage? = nil,
standardUserDefaults: UserDefaultsType? = nil,
date: Date? = nil
) {

View File

@ -175,7 +175,7 @@ public final class JobRunner {
public static func appDidFinishLaunching() {
// Note: 'appDidBecomeActive' will run on first launch anyway so we can
// leave those jobs out and can wait until then to start the JobRunner
let jobsToRun: (blocking: [Job], nonBlocking: [Job]) = GRDBStorage.shared
let jobsToRun: (blocking: [Job], nonBlocking: [Job]) = Storage.shared
.read { db in
let blockingJobs: [Job] = try Job
.filter(
@ -222,7 +222,7 @@ public final class JobRunner {
// long as there are no other jobs already running
let alreadyRunningOtherJobs: Bool = queues.wrappedValue
.contains(where: { _, queue -> Bool in queue.isRunning.wrappedValue })
let jobsToRun: (blocking: [Job], nonBlocking: [Job]) = GRDBStorage.shared
let jobsToRun: (blocking: [Job], nonBlocking: [Job]) = Storage.shared
.read { db in
guard !alreadyRunningOtherJobs else {
let onActiveJobs: [Job] = try Job
@ -548,7 +548,7 @@ private final class JobQueue {
// Get any pending jobs
let jobIdsAlreadyRunning: Set<Int64> = jobsCurrentlyRunning.wrappedValue
let jobsAlreadyInQueue: Set<Int64> = queue.wrappedValue.compactMap { $0.id }.asSet()
let jobsToRun: [Job] = GRDBStorage.shared.read { db in
let jobsToRun: [Job] = Storage.shared.read { db in
try Job.filterPendingJobs(variants: jobVariants)
.filter(!jobIdsAlreadyRunning.contains(Job.Columns.id)) // Exclude jobs already running
.filter(!jobsAlreadyInQueue.contains(Job.Columns.id)) // Exclude jobs already in the queue
@ -623,7 +623,7 @@ private final class JobQueue {
}
// Check if the next job has any dependencies
let dependencyInfo: (expectedCount: Int, jobs: [Job]) = GRDBStorage.shared.read { db in
let dependencyInfo: (expectedCount: Int, jobs: [Job]) = Storage.shared.read { db in
let numExpectedDependencies: Int = try JobDependencies
.filter(JobDependencies.Columns.jobId == nextJob.id)
.fetchCount(db)
@ -714,7 +714,7 @@ private final class JobQueue {
}
private func scheduleNextSoonestJob() {
let nextJobTimestamp: TimeInterval? = GRDBStorage.shared.read { db in
let nextJobTimestamp: TimeInterval? = Storage.shared.read { db in
try Job.filterPendingJobs(variants: jobVariants, excludeFutureJobs: false)
.select(.nextRunTimestamp)
.asRequest(of: TimeInterval.self)
@ -768,7 +768,7 @@ private final class JobQueue {
private func handleJobSucceeded(_ job: Job, shouldStop: Bool) {
switch job.behaviour {
case .runOnce, .runOnceNextLaunch:
GRDBStorage.shared.write { db in
Storage.shared.write { db in
// First remove any JobDependencies requiring this job to be completed (if
// we don't then the dependant jobs will automatically be deleted)
_ = try JobDependencies
@ -779,7 +779,7 @@ private final class JobQueue {
}
case .recurring where shouldStop == true:
GRDBStorage.shared.write { db in
Storage.shared.write { db in
// First remove any JobDependencies requiring this job to be completed (if
// we don't then the dependant jobs will automatically be deleted)
_ = try JobDependencies
@ -793,7 +793,7 @@ private final class JobQueue {
// but we want at least 1 second to pass before doing so - the job itself should
// really update it's own 'nextRunTimestamp' (this is just a safety net)
case .recurring where job.nextRunTimestamp <= Date().timeIntervalSince1970:
GRDBStorage.shared.write { db in
Storage.shared.write { db in
_ = try job
.with(nextRunTimestamp: (Date().timeIntervalSince1970 + 1))
.saved(db)
@ -805,7 +805,7 @@ private final class JobQueue {
// For concurrent queues retrieve any 'dependant' jobs and re-add them here (if they have other
// dependencies they will be removed again when they try to execute)
if executionType == .concurrent {
let dependantJobs: [Job] = GRDBStorage.shared
let dependantJobs: [Job] = Storage.shared
.read { db in try job.dependantJobs.fetchAll(db) }
.defaulting(to: [])
let dependantJobIds: [Int64] = dependantJobs
@ -837,7 +837,7 @@ private final class JobQueue {
/// This function is called when a job fails, if it's wasn't a permanent failure then the 'failureCount' for the job will be incremented and it'll
/// be re-run after a retry interval has passed
private func handleJobFailed(_ job: Job, error: Error?, permanentFailure: Bool) {
guard GRDBStorage.shared.read({ db in try Job.exists(db, id: job.id ?? -1) }) == true else {
guard Storage.shared.read({ db in try Job.exists(db, id: job.id ?? -1) }) == true else {
SNLog("[JobRunner] \(queueContext) \(job.variant) job canceled")
jobsCurrentlyRunning.mutate { $0 = $0.removing(job.id) }
detailsForCurrentlyRunningJobs.mutate { $0 = $0.removingValue(forKey: job.id) }
@ -865,7 +865,7 @@ private final class JobQueue {
let maxFailureCount: Int = (JobRunner.executorMap.wrappedValue[job.variant]?.maxFailureCount ?? 0)
let nextRunTimestamp: TimeInterval = (Date().timeIntervalSince1970 + JobRunner.getRetryInterval(for: job))
GRDBStorage.shared.write { db in
Storage.shared.write { db in
guard
!permanentFailure && (
maxFailureCount < 0 ||

View File

@ -32,7 +32,7 @@ import SessionMessagingKit
accessibilityIdentifier: "\(type(of: self).self).block",
style: .destructive,
handler: { _ in
GRDBStorage.shared.writeAsync(
Storage.shared.writeAsync(
updates: { db in
try Contact
.fetchOrCreate(db, id: threadId)
@ -83,7 +83,7 @@ import SessionMessagingKit
accessibilityIdentifier: "\(type(of: self).self).unblock",
style: .destructive,
handler: { _ in
GRDBStorage.shared.writeAsync(
Storage.shared.writeAsync(
updates: { db in
try Contact
.fetchOrCreate(db, id: threadId)

View File

@ -59,7 +59,7 @@ public final class ProfilePictureView: UIView {
public func update(forThreadId threadId: String?) {
guard
let threadId: String = threadId,
let viewModel: SessionThreadViewModel = GRDBStorage.shared.read({ db -> SessionThreadViewModel? in
let viewModel: SessionThreadViewModel = Storage.shared.read({ db -> SessionThreadViewModel? in
let userPublicKey: String = getUserHexEncodedPublicKey(db)
return try SessionThreadViewModel

View File

@ -41,12 +41,12 @@ import SessionMessagingKit
// MARK: - Properties
@objc public func isScreenLockEnabled() -> Bool {
return GRDBStorage.shared[.isScreenLockEnabled]
return Storage.shared[.isScreenLockEnabled]
}
@objc
public func setIsScreenLockEnabled(_ value: Bool) {
GRDBStorage.shared.writeAsync(
Storage.shared.writeAsync(
updates: { db in db[.isScreenLockEnabled] = value },
completion: { _, _ in
NotificationCenter.default.postNotificationNameAsync(OWSScreenLock.ScreenLockDidChange, object: nil)
@ -55,12 +55,12 @@ import SessionMessagingKit
}
@objc public func screenLockTimeout() -> TimeInterval {
return GRDBStorage.shared[.screenLockTimeoutSeconds]
return Storage.shared[.screenLockTimeoutSeconds]
.defaulting(to: screenLockTimeoutDefault)
}
@objc public func setScreenLockTimeout(_ value: TimeInterval) {
GRDBStorage.shared.writeAsync(
Storage.shared.writeAsync(
updates: { db in db[.screenLockTimeoutSeconds] = value },
completion: { _, _ in
NotificationCenter.default.postNotificationNameAsync(OWSScreenLock.ScreenLockDidChange, object: nil)

Some files were not shown because too many files have changed in this diff Show More