mirror of
https://github.com/oxen-io/session-ios.git
synced 2023-12-13 21:30:14 +01:00
Merge pull request #242 from loki-project/multi-device
Disable Multi Device
This commit is contained in:
commit
a67bf946c5
1
Podfile
1
Podfile
|
@ -77,6 +77,7 @@ target 'Signal' do
|
|||
pod 'FeedKit', '~> 8.1', :inhibit_warnings => true
|
||||
pod 'CryptoSwift', '~> 1.3', :inhibit_warnings => true
|
||||
pod 'NVActivityIndicatorView', '~> 4.7', :inhibit_warnings => true
|
||||
pod 'UITextView+Placeholder', '~> 1.4', :inhibit_warnings => true
|
||||
|
||||
target 'SignalTests' do
|
||||
inherit! :search_paths
|
||||
|
|
|
@ -130,6 +130,7 @@ PODS:
|
|||
- SSZipArchive (2.2.3)
|
||||
- Starscream (3.0.6)
|
||||
- SwiftProtobuf (1.5.0)
|
||||
- "UITextView+Placeholder (1.4.0)"
|
||||
- YapDatabase/SQLCipher (3.1.1):
|
||||
- YapDatabase/SQLCipher/Core (= 3.1.1)
|
||||
- YapDatabase/SQLCipher/Extensions (= 3.1.1)
|
||||
|
@ -222,6 +223,7 @@ DEPENDENCIES:
|
|||
- SQLCipher (>= 4.0.1)
|
||||
- SSZipArchive
|
||||
- Starscream (from `https://github.com/signalapp/Starscream.git`, branch `signal-release`)
|
||||
- "UITextView+Placeholder (~> 1.4)"
|
||||
- YapDatabase/SQLCipher (from `https://github.com/signalapp/YapDatabase.git`, branch `signal-release`)
|
||||
- YYImage
|
||||
|
||||
|
@ -241,6 +243,7 @@ SPEC REPOS:
|
|||
- SQLCipher
|
||||
- SSZipArchive
|
||||
- SwiftProtobuf
|
||||
- "UITextView+Placeholder"
|
||||
- YYImage
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
|
@ -322,9 +325,10 @@ SPEC CHECKSUMS:
|
|||
SSZipArchive: 62d4947b08730e4cda640473b0066d209ff033c9
|
||||
Starscream: 8aaf1a7feb805c816d0e7d3190ef23856f6665b9
|
||||
SwiftProtobuf: 241400280f912735c1e1b9fe675fdd2c6c4d42e2
|
||||
"UITextView+Placeholder": d7b0c400921f66523f3a85d74f774512e14f6502
|
||||
YapDatabase: b418a4baa6906e8028748938f9159807fd039af4
|
||||
YYImage: 1e1b62a9997399593e4b9c4ecfbbabbf1d3f3b54
|
||||
|
||||
PODFILE CHECKSUM: b4f88816a817cc27f499940c644c0449ef5d7cc7
|
||||
PODFILE CHECKSUM: 0d59a208ed95a7e5640a3e89cff48cd0a5b51e0b
|
||||
|
||||
COCOAPODS: 1.9.3
|
||||
|
|
2
Pods
2
Pods
|
@ -1 +1 @@
|
|||
Subproject commit d1322a0a5e38a04b7c9fb57c847ea0f2eb7c13c3
|
||||
Subproject commit 5d61962cd5848660e72017012f20caab92289f48
|
|
@ -585,6 +585,7 @@
|
|||
C3638C0524C7F0B500AF29BC /* LK002RemoveFriendRequests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3638C0424C7F0B500AF29BC /* LK002RemoveFriendRequests.swift */; };
|
||||
C369549D24D27A3500CEB4E3 /* MultiDeviceRemovalSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = C369549C24D27A3500CEB4E3 /* MultiDeviceRemovalSheet.swift */; };
|
||||
C36B8707243C50C60049991D /* SignalMessaging.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 453518921FC63DBF00210559 /* SignalMessaging.framework */; };
|
||||
C3C3CF8924D8EED300E1CCE7 /* TextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C3CF8824D8EED300E1CCE7 /* TextView.swift */; };
|
||||
C3DAB3242480CB2B00725F25 /* SRCopyableLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3DAB3232480CB2A00725F25 /* SRCopyableLabel.swift */; };
|
||||
C3DFFAC623E96F0D0058DAF8 /* Sheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3DFFAC523E96F0D0058DAF8 /* Sheet.swift */; };
|
||||
C3DFFAC823E970080058DAF8 /* OpenGroupSuggestionSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3DFFAC723E970080058DAF8 /* OpenGroupSuggestionSheet.swift */; };
|
||||
|
@ -1373,6 +1374,7 @@
|
|||
C3638C0424C7F0B500AF29BC /* LK002RemoveFriendRequests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LK002RemoveFriendRequests.swift; sourceTree = "<group>"; };
|
||||
C369549C24D27A3500CEB4E3 /* MultiDeviceRemovalSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MultiDeviceRemovalSheet.swift; sourceTree = "<group>"; };
|
||||
C3AA6BB824CE8F1B002358B6 /* Migrating Translations from Android.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = "Migrating Translations from Android.md"; sourceTree = "<group>"; };
|
||||
C3C3CF8824D8EED300E1CCE7 /* TextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextView.swift; sourceTree = "<group>"; };
|
||||
C3DAB3232480CB2A00725F25 /* SRCopyableLabel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SRCopyableLabel.swift; sourceTree = "<group>"; };
|
||||
C3DFFAC523E96F0D0058DAF8 /* Sheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sheet.swift; sourceTree = "<group>"; };
|
||||
C3DFFAC723E970080058DAF8 /* OpenGroupSuggestionSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenGroupSuggestionSheet.swift; sourceTree = "<group>"; };
|
||||
|
@ -2673,6 +2675,7 @@
|
|||
2400888D239F30A600305217 /* SessionRestorationView.swift */,
|
||||
B8CCF638239721E20091D419 /* TabBar.swift */,
|
||||
B8BB82B423947F2D00BA5194 /* TextField.swift */,
|
||||
C3C3CF8824D8EED300E1CCE7 /* TextView.swift */,
|
||||
);
|
||||
path = Components;
|
||||
sourceTree = "<group>";
|
||||
|
@ -3414,6 +3417,7 @@
|
|||
"${BUILT_PRODUCTS_DIR}/SessionServiceKit/SessionServiceKit.framework",
|
||||
"${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework",
|
||||
"${BUILT_PRODUCTS_DIR}/SwiftProtobuf/SwiftProtobuf.framework",
|
||||
"${BUILT_PRODUCTS_DIR}/UITextView+Placeholder/UITextView_Placeholder.framework",
|
||||
"${BUILT_PRODUCTS_DIR}/YYImage/YYImage.framework",
|
||||
"${BUILT_PRODUCTS_DIR}/YapDatabase/YapDatabase.framework",
|
||||
"${BUILT_PRODUCTS_DIR}/libPhoneNumber-iOS/libPhoneNumber_iOS.framework",
|
||||
|
@ -3442,6 +3446,7 @@
|
|||
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SessionServiceKit.framework",
|
||||
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework",
|
||||
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftProtobuf.framework",
|
||||
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/UITextView_Placeholder.framework",
|
||||
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/YYImage.framework",
|
||||
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/YapDatabase.framework",
|
||||
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/libPhoneNumber_iOS.framework",
|
||||
|
@ -3767,6 +3772,7 @@
|
|||
EF764C351DB67CC5000D9A87 /* UIViewController+Permissions.m in Sources */,
|
||||
45CD81EF1DC030E7004C9430 /* SyncPushTokensJob.swift in Sources */,
|
||||
34D2CCE0206939B400CB1A14 /* DebugUIMessagesAssetLoader.m in Sources */,
|
||||
C3C3CF8924D8EED300E1CCE7 /* TextView.swift in Sources */,
|
||||
4CEB78C92178EBAB00F315D2 /* OWSSessionResetJobRecord.m in Sources */,
|
||||
45794E861E00620000066731 /* CallUIAdapter.swift in Sources */,
|
||||
340FC8BA204DAC8D007AEB0F /* FingerprintViewScanController.m in Sources */,
|
||||
|
|
57
Signal/src/Loki/Components/TextView.swift
Normal file
57
Signal/src/Loki/Components/TextView.swift
Normal file
|
@ -0,0 +1,57 @@
|
|||
import UITextView_Placeholder
|
||||
|
||||
final class TextView : UITextView {
|
||||
private let usesDefaultHeight: Bool
|
||||
private let height: CGFloat
|
||||
private let horizontalInset: CGFloat
|
||||
private let verticalInset: CGFloat
|
||||
|
||||
override var contentSize: CGSize { didSet { centerTextVertically() } }
|
||||
|
||||
init(placeholder: String, usesDefaultHeight: Bool = true, customHeight: CGFloat? = nil, customHorizontalInset: CGFloat? = nil, customVerticalInset: CGFloat? = nil) {
|
||||
self.usesDefaultHeight = usesDefaultHeight
|
||||
self.height = customHeight ?? Values.textFieldHeight
|
||||
self.horizontalInset = customHorizontalInset ?? (isIPhone5OrSmaller ? Values.mediumSpacing : Values.largeSpacing)
|
||||
self.verticalInset = customVerticalInset ?? (isIPhone5OrSmaller ? Values.smallSpacing : Values.largeSpacing)
|
||||
super.init(frame: CGRect.zero, textContainer: nil)
|
||||
self.placeholder = placeholder
|
||||
setUpStyle()
|
||||
}
|
||||
|
||||
override init(frame: CGRect, textContainer: NSTextContainer?) {
|
||||
preconditionFailure("Use init(placeholder:) instead.")
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
preconditionFailure("Use init(placeholder:) instead.")
|
||||
}
|
||||
|
||||
private func setUpStyle() {
|
||||
showsHorizontalScrollIndicator = false
|
||||
showsVerticalScrollIndicator = false
|
||||
let placeholder = NSMutableAttributedString(string: self.placeholder!)
|
||||
self.placeholder = nil
|
||||
let placeholderColor = Colors.text.withAlphaComponent(Values.unimportantElementOpacity)
|
||||
placeholder.addAttribute(.foregroundColor, value: placeholderColor, range: NSRange(location: 0, length: placeholder.length))
|
||||
placeholder.addAttribute(.font, value: UIFont.systemFont(ofSize: Values.smallFontSize), range: NSRange(location: 0, length: placeholder.length))
|
||||
attributedPlaceholder = placeholder
|
||||
backgroundColor = .clear
|
||||
textColor = Colors.text
|
||||
font = .systemFont(ofSize: Values.smallFontSize)
|
||||
tintColor = Colors.accent
|
||||
keyboardAppearance = isLightMode ? .light : .dark
|
||||
if usesDefaultHeight {
|
||||
set(.height, to: height)
|
||||
}
|
||||
layer.borderColor = isLightMode ? Colors.text.cgColor : Colors.border.withAlphaComponent(Values.textFieldBorderOpacity).cgColor
|
||||
layer.borderWidth = Values.borderThickness
|
||||
layer.cornerRadius = Values.textFieldCornerRadius
|
||||
let horizontalInset = usesDefaultHeight ? self.horizontalInset : Values.mediumSpacing
|
||||
textContainerInset = UIEdgeInsets(top: 0, leading: horizontalInset, bottom: 0, trailing: horizontalInset)
|
||||
}
|
||||
|
||||
private func centerTextVertically() {
|
||||
let topInset = max(0, (bounds.size.height - contentSize.height * zoomScale) / 2)
|
||||
contentInset = UIEdgeInsets(top: topInset, left: 0, bottom: 0, right: 0)
|
||||
}
|
||||
}
|
|
@ -5,14 +5,16 @@ extension UIView {
|
|||
let size: CGFloat
|
||||
let color: UIColor
|
||||
let isAnimated: Bool
|
||||
let animationDuration: TimeInterval
|
||||
let offset: CGSize
|
||||
let opacity: Float
|
||||
let radius: CGFloat
|
||||
|
||||
init(size: CGFloat, color: UIColor, isAnimated: Bool, offset: CGSize = CGSize(width: 0, height: 0.8), opacity: Float = isLightMode ? 0.4 : 1, radius: CGFloat) {
|
||||
init(size: CGFloat, color: UIColor, isAnimated: Bool, animationDuration: TimeInterval = 0.25, offset: CGSize = CGSize(width: 0, height: 0.8), opacity: Float = isLightMode ? 0.4 : 1, radius: CGFloat) {
|
||||
self.size = size
|
||||
self.color = color
|
||||
self.isAnimated = isAnimated
|
||||
self.animationDuration = animationDuration
|
||||
self.offset = offset
|
||||
self.opacity = opacity
|
||||
self.radius = radius
|
||||
|
@ -26,7 +28,7 @@ extension UIView {
|
|||
let pathAnimation = CABasicAnimation(keyPath: "shadowPath")
|
||||
pathAnimation.fromValue = layer.shadowPath
|
||||
pathAnimation.toValue = newPath
|
||||
pathAnimation.duration = 0.25
|
||||
pathAnimation.duration = configuration.animationDuration
|
||||
layer.add(pathAnimation, forKey: pathAnimation.keyPath)
|
||||
}
|
||||
layer.shadowPath = newPath
|
||||
|
@ -35,7 +37,7 @@ extension UIView {
|
|||
let colorAnimation = CABasicAnimation(keyPath: "shadowColor")
|
||||
colorAnimation.fromValue = layer.shadowColor
|
||||
colorAnimation.toValue = newColor
|
||||
colorAnimation.duration = 0.25
|
||||
colorAnimation.duration = configuration.animationDuration
|
||||
layer.add(colorAnimation, forKey: colorAnimation.keyPath)
|
||||
}
|
||||
layer.shadowColor = newColor
|
||||
|
|
|
@ -135,7 +135,7 @@ final class HomeVC : BaseVC, UITableViewDataSource, UITableViewDelegate, UIScrol
|
|||
newConversationButtonSet.center(.horizontal, in: view)
|
||||
newConversationButtonSet.pin(.bottom, to: .bottom, of: view, withInset: -Values.newConversationButtonBottomOffset) // Negative due to how the constraint is set up
|
||||
// Set up previewing
|
||||
if (traitCollection.forceTouchCapability == .available) {
|
||||
if traitCollection.forceTouchCapability == .available {
|
||||
registerForPreviewing(with: self, sourceView: tableView)
|
||||
}
|
||||
// Listen for notifications
|
||||
|
@ -173,6 +173,10 @@ final class HomeVC : BaseVC, UITableViewDataSource, UITableViewDelegate, UIScrol
|
|||
let _ = FileServerAPI.getDeviceLinks(associatedWith: publicKeys)
|
||||
// Do initial update
|
||||
reload()
|
||||
// Clear all data if this is a secondary device
|
||||
if UserDefaults.standard[.masterHexEncodedPublicKey] != nil {
|
||||
NotificationCenter.default.post(name: .dataNukeRequested, object: nil, userInfo: nil)
|
||||
}
|
||||
}
|
||||
|
||||
override func viewDidAppear(_ animated: Bool) {
|
||||
|
|
|
@ -149,7 +149,7 @@ private final class EnterPublicKeyVC : UIViewController {
|
|||
}()
|
||||
|
||||
// MARK: Components
|
||||
private lazy var publicKeyTextField = TextField(placeholder: NSLocalizedString("vc_enter_public_key_text_field_hint", comment: ""))
|
||||
private let publicKeyTextView = TextView(placeholder: NSLocalizedString("vc_enter_public_key_text_field_hint", comment: ""))
|
||||
|
||||
private lazy var copyButton: Button = {
|
||||
let result = Button(style: .unimportant, size: .medium)
|
||||
|
@ -200,7 +200,7 @@ private final class EnterPublicKeyVC : UIViewController {
|
|||
nextButtonContainer.pin(.trailing, to: .trailing, of: nextButton, withInset: 80)
|
||||
nextButtonContainer.pin(.bottom, to: .bottom, of: nextButton)
|
||||
// Set up stack view
|
||||
let stackView = UIStackView(arrangedSubviews: [ publicKeyTextField, UIView.spacer(withHeight: Values.smallSpacing), explanationLabel, UIView.spacer(withHeight: Values.largeSpacing), separator, UIView.spacer(withHeight: Values.largeSpacing), userPublicKeyLabel, UIView.spacer(withHeight: Values.largeSpacing), buttonContainer, UIView.vStretchingSpacer(), nextButtonContainer ])
|
||||
let stackView = UIStackView(arrangedSubviews: [ publicKeyTextView, UIView.spacer(withHeight: Values.smallSpacing), explanationLabel, UIView.spacer(withHeight: Values.largeSpacing), separator, UIView.spacer(withHeight: Values.largeSpacing), userPublicKeyLabel, UIView.spacer(withHeight: Values.largeSpacing), buttonContainer, UIView.vStretchingSpacer(), nextButtonContainer ])
|
||||
stackView.axis = .vertical
|
||||
stackView.alignment = .fill
|
||||
stackView.layoutMargins = UIEdgeInsets(top: Values.largeSpacing, left: Values.largeSpacing, bottom: Values.largeSpacing, right: Values.largeSpacing)
|
||||
|
@ -220,7 +220,7 @@ private final class EnterPublicKeyVC : UIViewController {
|
|||
}
|
||||
|
||||
@objc private func dismissKeyboard() {
|
||||
publicKeyTextField.resignFirstResponder()
|
||||
publicKeyTextView.resignFirstResponder()
|
||||
}
|
||||
|
||||
@objc private func enableCopyButton() {
|
||||
|
@ -246,7 +246,7 @@ private final class EnterPublicKeyVC : UIViewController {
|
|||
}
|
||||
|
||||
@objc private func startNewPrivateChatIfPossible() {
|
||||
let hexEncodedPublicKey = publicKeyTextField.text?.trimmingCharacters(in: .whitespaces) ?? ""
|
||||
let hexEncodedPublicKey = publicKeyTextView.text?.trimmingCharacters(in: .whitespaces) ?? ""
|
||||
newPrivateChatVC.startNewPrivateChatIfPossible(with: hexEncodedPublicKey)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -132,7 +132,7 @@ final class PathVC : BaseVC {
|
|||
// MARK: General
|
||||
private func getPathRow(title: String, subtitle: String?, location: LineView.Location, dotAnimationStartDelay: Double, dotAnimationRepeatInterval: Double) -> UIStackView {
|
||||
let lineView = LineView(location: location, dotAnimationStartDelay: dotAnimationStartDelay, dotAnimationRepeatInterval: dotAnimationRepeatInterval)
|
||||
lineView.set(.width, to: Values.pathRowDotSize)
|
||||
lineView.set(.width, to: Values.pathRowExpandedDotSize)
|
||||
lineView.set(.height, to: Values.pathRowHeight)
|
||||
let titleLabel = UILabel()
|
||||
titleLabel.textColor = Colors.text
|
||||
|
@ -190,7 +190,9 @@ private final class LineView : UIView {
|
|||
private lazy var dotView: UIView = {
|
||||
let result = UIView()
|
||||
result.layer.cornerRadius = Values.pathRowDotSize / 2
|
||||
let glowConfiguration = UIView.CircularGlowConfiguration(size: Values.pathRowDotSize, color: Colors.accent, isAnimated: true, radius: isLightMode ? 2 : 4)
|
||||
let glowRadius: CGFloat = isLightMode ? 1 : 2
|
||||
let glowColor = isLightMode ? UIColor.black.withAlphaComponent(0.4) : UIColor.black
|
||||
let glowConfiguration = UIView.CircularGlowConfiguration(size: Values.pathRowDotSize, color: glowColor, isAnimated: true, animationDuration: 0.5, radius: glowRadius)
|
||||
result.setCircularGlow(with: glowConfiguration)
|
||||
result.backgroundColor = Colors.accent
|
||||
return result
|
||||
|
@ -254,17 +256,19 @@ private final class LineView : UIView {
|
|||
|
||||
private func expandDot() {
|
||||
let newSize = Values.pathRowExpandedDotSize
|
||||
let newGlowRadius: CGFloat = isLightMode ? 6 : 8
|
||||
updateDotView(size: newSize, glowRadius: newGlowRadius)
|
||||
let newGlowRadius: CGFloat = isLightMode ? 4 : 6
|
||||
let newGlowColor = Colors.accent.withAlphaComponent(0.6)
|
||||
updateDotView(size: newSize, glowRadius: newGlowRadius, glowColor: newGlowColor)
|
||||
}
|
||||
|
||||
private func collapseDot() {
|
||||
let newSize = Values.pathRowDotSize
|
||||
let newGlowRadius: CGFloat = isLightMode ? 2 : 4
|
||||
updateDotView(size: newSize, glowRadius: newGlowRadius)
|
||||
let newGlowRadius: CGFloat = isLightMode ? 1 : 2
|
||||
let newGlowColor = isLightMode ? UIColor.black.withAlphaComponent(0.4) : UIColor.black
|
||||
updateDotView(size: newSize, glowRadius: newGlowRadius, glowColor: newGlowColor)
|
||||
}
|
||||
|
||||
private func updateDotView(size: CGFloat, glowRadius: CGFloat) {
|
||||
private func updateDotView(size: CGFloat, glowRadius: CGFloat, glowColor: UIColor) {
|
||||
let frame = CGRect(center: dotView.center, size: CGSize(width: size, height: size))
|
||||
dotViewWidthConstraint.constant = size
|
||||
dotViewHeightConstraint.constant = size
|
||||
|
@ -272,8 +276,7 @@ private final class LineView : UIView {
|
|||
self.layoutIfNeeded()
|
||||
self.dotView.frame = frame
|
||||
self.dotView.layer.cornerRadius = size / 2
|
||||
let glowColor = Colors.accent
|
||||
let glowConfiguration = UIView.CircularGlowConfiguration(size: size, color: glowColor, isAnimated: true, radius: glowRadius)
|
||||
let glowConfiguration = UIView.CircularGlowConfiguration(size: size, color: glowColor, isAnimated: true, animationDuration: 0.5, radius: glowRadius)
|
||||
self.dotView.setCircularGlow(with: glowConfiguration)
|
||||
self.dotView.backgroundColor = Colors.accent
|
||||
}
|
||||
|
|
|
@ -0,0 +1,148 @@
|
|||
import PromiseKit
|
||||
|
||||
public extension FileServerAPI {
|
||||
|
||||
/// Gets the device links associated with the given hex encoded public key from the
|
||||
/// server and stores and returns the valid ones.
|
||||
///
|
||||
/// - Note: Deprecated.
|
||||
public static func getDeviceLinks(associatedWith hexEncodedPublicKey: String) -> Promise<Set<DeviceLink>> {
|
||||
return getDeviceLinks(associatedWith: [ hexEncodedPublicKey ])
|
||||
}
|
||||
|
||||
/// Gets the device links associated with the given hex encoded public keys from the
|
||||
/// server and stores and returns the valid ones.
|
||||
///
|
||||
/// - Note: Deprecated.
|
||||
public static func getDeviceLinks(associatedWith hexEncodedPublicKeys: Set<String>) -> Promise<Set<DeviceLink>> {
|
||||
return Promise.value([])
|
||||
/*
|
||||
let hexEncodedPublicKeysDescription = "[ \(hexEncodedPublicKeys.joined(separator: ", ")) ]"
|
||||
print("[Loki] Getting device links for: \(hexEncodedPublicKeysDescription).")
|
||||
return getAuthToken(for: server).then2 { token -> Promise<Set<DeviceLink>> in
|
||||
let queryParameters = "ids=\(hexEncodedPublicKeys.map { "@\($0)" }.joined(separator: ","))&include_user_annotations=1"
|
||||
let url = URL(string: "\(server)/users?\(queryParameters)")!
|
||||
let request = TSRequest(url: url)
|
||||
return OnionRequestAPI.sendOnionRequest(request, to: server, using: fileServerPublicKey).map2 { rawResponse -> Set<DeviceLink> in
|
||||
guard let data = rawResponse["data"] as? [JSON] else {
|
||||
print("[Loki] Couldn't parse device links for users: \(hexEncodedPublicKeys) from: \(rawResponse).")
|
||||
throw DotNetAPIError.parsingFailed
|
||||
}
|
||||
return Set(data.flatMap { data -> [DeviceLink] in
|
||||
guard let annotations = data["annotations"] as? [JSON], !annotations.isEmpty else { return [] }
|
||||
guard let annotation = annotations.first(where: { $0["type"] as? String == deviceLinkType }),
|
||||
let value = annotation["value"] as? JSON, let rawDeviceLinks = value["authorisations"] as? [JSON],
|
||||
let hexEncodedPublicKey = data["username"] as? String else {
|
||||
print("[Loki] Couldn't parse device links from: \(rawResponse).")
|
||||
return []
|
||||
}
|
||||
return rawDeviceLinks.compactMap { rawDeviceLink in
|
||||
guard let masterPublicKey = rawDeviceLink["primaryDevicePubKey"] as? String, let slavePublicKey = rawDeviceLink["secondaryDevicePubKey"] as? String,
|
||||
let base64EncodedSlaveSignature = rawDeviceLink["requestSignature"] as? String else {
|
||||
print("[Loki] Couldn't parse device link for user: \(hexEncodedPublicKey) from: \(rawResponse).")
|
||||
return nil
|
||||
}
|
||||
let masterSignature: Data?
|
||||
if let base64EncodedMasterSignature = rawDeviceLink["grantSignature"] as? String {
|
||||
masterSignature = Data(base64Encoded: base64EncodedMasterSignature)
|
||||
} else {
|
||||
masterSignature = nil
|
||||
}
|
||||
let slaveSignature = Data(base64Encoded: base64EncodedSlaveSignature)
|
||||
let master = DeviceLink.Device(publicKey: masterPublicKey, signature: masterSignature)
|
||||
let slave = DeviceLink.Device(publicKey: slavePublicKey, signature: slaveSignature)
|
||||
let deviceLink = DeviceLink(between: master, and: slave)
|
||||
if let masterSignature = masterSignature {
|
||||
guard DeviceLinkingUtilities.hasValidMasterSignature(deviceLink) else {
|
||||
print("[Loki] Received a device link with an invalid master signature.")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
guard DeviceLinkingUtilities.hasValidSlaveSignature(deviceLink) else {
|
||||
print("[Loki] Received a device link with an invalid slave signature.")
|
||||
return nil
|
||||
}
|
||||
return deviceLink
|
||||
}
|
||||
})
|
||||
}.map2 { deviceLinks in
|
||||
storage.setDeviceLinks(deviceLinks)
|
||||
return deviceLinks
|
||||
}
|
||||
}.handlingInvalidAuthTokenIfNeeded(for: server)
|
||||
*/
|
||||
}
|
||||
|
||||
/// - Note: Deprecated.
|
||||
public static func setDeviceLinks(_ deviceLinks: Set<DeviceLink>) -> Promise<Void> {
|
||||
return Promise.value(())
|
||||
/*
|
||||
print("[Loki] Updating device links.")
|
||||
return getAuthToken(for: server).then2 { token -> Promise<Void> in
|
||||
let isMaster = deviceLinks.contains { $0.master.publicKey == getUserHexEncodedPublicKey() }
|
||||
let deviceLinksAsJSON = deviceLinks.map { $0.toJSON() }
|
||||
let value = !deviceLinksAsJSON.isEmpty ? [ "isPrimary" : isMaster ? 1 : 0, "authorisations" : deviceLinksAsJSON ] : nil
|
||||
let annotation: JSON = [ "type" : deviceLinkType, "value" : value ]
|
||||
let parameters: JSON = [ "annotations" : [ annotation ] ]
|
||||
let url = URL(string: "\(server)/users/me")!
|
||||
let request = TSRequest(url: url, method: "PATCH", parameters: parameters)
|
||||
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
|
||||
return attempt(maxRetryCount: 8, recoveringOn: SnodeAPI.workQueue) {
|
||||
OnionRequestAPI.sendOnionRequest(request, to: server, using: fileServerPublicKey).map2 { _ in }
|
||||
}.handlingInvalidAuthTokenIfNeeded(for: server).recover2 { error in
|
||||
print("[Loki] Couldn't update device links due to error: \(error).")
|
||||
throw error
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
/// Adds the given device link to the user's device mapping on the server.
|
||||
///
|
||||
/// - Note: Deprecated.
|
||||
public static func addDeviceLink(_ deviceLink: DeviceLink) -> Promise<Void> {
|
||||
return Promise.value(())
|
||||
/*
|
||||
var deviceLinks: Set<DeviceLink> = []
|
||||
storage.dbReadConnection.read { transaction in
|
||||
deviceLinks = storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction)
|
||||
}
|
||||
deviceLinks.insert(deviceLink)
|
||||
return setDeviceLinks(deviceLinks).map2 { _ in
|
||||
storage.addDeviceLink(deviceLink)
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
/// Removes the given device link from the user's device mapping on the server.
|
||||
///
|
||||
/// - Note: Deprecated.
|
||||
public static func removeDeviceLink(_ deviceLink: DeviceLink) -> Promise<Void> {
|
||||
return Promise.value(())
|
||||
/*
|
||||
var deviceLinks: Set<DeviceLink> = []
|
||||
storage.dbReadConnection.read { transaction in
|
||||
deviceLinks = storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction)
|
||||
}
|
||||
deviceLinks.remove(deviceLink)
|
||||
return setDeviceLinks(deviceLinks).map2 { _ in
|
||||
storage.removeDeviceLink(deviceLink)
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
@objc public extension FileServerAPI {
|
||||
|
||||
/// - Note: Deprecated.
|
||||
@objc(getDeviceLinksAssociatedWithHexEncodedPublicKey:)
|
||||
public static func objc_getDeviceLinks(associatedWith hexEncodedPublicKey: String) -> AnyPromise {
|
||||
return AnyPromise.from(getDeviceLinks(associatedWith: hexEncodedPublicKey))
|
||||
}
|
||||
|
||||
/// - Note: Deprecated.
|
||||
@objc(getDeviceLinksAssociatedWithHexEncodedPublicKeys:)
|
||||
public static func objc_getDeviceLinks(associatedWith hexEncodedPublicKeys: Set<String>) -> AnyPromise {
|
||||
return AnyPromise.from(getDeviceLinks(associatedWith: hexEncodedPublicKeys))
|
||||
}
|
||||
}
|
|
@ -4,7 +4,6 @@ import SessionMetadataKit
|
|||
/// Base class for `FileServerAPI` and `PublicChatAPI`.
|
||||
public class DotNetAPI : NSObject {
|
||||
|
||||
internal static var storage: OWSPrimaryStorage { OWSPrimaryStorage.shared() }
|
||||
internal static var userKeyPair: ECKeyPair { OWSIdentityManager.shared().identityKeyPair()! }
|
||||
|
||||
// MARK: Settings
|
||||
|
@ -41,10 +40,8 @@ public class DotNetAPI : NSObject {
|
|||
|
||||
private static func getAuthTokenFromDatabase(for server: String) -> String? {
|
||||
var result: String? = nil
|
||||
storage.dbReadConnection.read { transaction in
|
||||
if transaction.hasObject(forKey: server, inCollection: authTokenCollection) {
|
||||
result = transaction.object(forKey: server, inCollection: authTokenCollection) as? String
|
||||
}
|
||||
Storage.read { transaction in
|
||||
result = transaction.object(forKey: server, inCollection: authTokenCollection) as? String
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
@ -53,7 +50,7 @@ public class DotNetAPI : NSObject {
|
|||
transaction.setObject(newValue, forKey: server, inCollection: authTokenCollection)
|
||||
}
|
||||
|
||||
public static func clearAuthToken(for server: String) {
|
||||
public static func removeAuthToken(for server: String) {
|
||||
try! Storage.writeSync { transaction in
|
||||
transaction.removeObject(forKey: server, inCollection: authTokenCollection)
|
||||
}
|
||||
|
@ -68,12 +65,12 @@ public class DotNetAPI : NSObject {
|
|||
let queryParameters = "pubKey=\(getUserHexEncodedPublicKey())"
|
||||
let url = URL(string: "\(server)/loki/v1/get_challenge?\(queryParameters)")!
|
||||
let request = TSRequest(url: url)
|
||||
let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise { $0.fulfill(FileServerAPI.fileServerPublicKey) }
|
||||
let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise.value(FileServerAPI.fileServerPublicKey)
|
||||
: PublicChatAPI.getOpenGroupServerPublicKey(for: server)
|
||||
return serverPublicKeyPromise.then2 { serverPublicKey in
|
||||
OnionRequestAPI.sendOnionRequest(request, to: server, using: serverPublicKey)
|
||||
}.map2 { rawResponse in
|
||||
guard let json = rawResponse as? JSON, let base64EncodedChallenge = json["cipherText64"] as? String, let base64EncodedServerPublicKey = json["serverPubKey64"] as? String,
|
||||
}.map2 { json in
|
||||
guard let base64EncodedChallenge = json["cipherText64"] as? String, let base64EncodedServerPublicKey = json["serverPubKey64"] as? String,
|
||||
let challenge = Data(base64Encoded: base64EncodedChallenge), var serverPublicKey = Data(base64Encoded: base64EncodedServerPublicKey) else {
|
||||
throw DotNetAPIError.parsingFailed
|
||||
}
|
||||
|
@ -96,7 +93,7 @@ public class DotNetAPI : NSObject {
|
|||
let url = URL(string: "\(server)/loki/v1/submit_challenge")!
|
||||
let parameters = [ "pubKey" : getUserHexEncodedPublicKey(), "token" : token ]
|
||||
let request = TSRequest(url: url, method: "POST", parameters: parameters)
|
||||
let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise { $0.fulfill(FileServerAPI.fileServerPublicKey) }
|
||||
let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise.value(FileServerAPI.fileServerPublicKey)
|
||||
: PublicChatAPI.getOpenGroupServerPublicKey(for: server)
|
||||
return serverPublicKeyPromise.then2 { serverPublicKey in
|
||||
OnionRequestAPI.sendOnionRequest(request, to: server, using: serverPublicKey)
|
||||
|
@ -134,7 +131,7 @@ public class DotNetAPI : NSObject {
|
|||
data = unencryptedAttachmentData
|
||||
}
|
||||
// Check the file size if needed
|
||||
print("[Loki] File size: \(data.count)")
|
||||
print("[Loki] File size: \(data.count) bytes.")
|
||||
if Double(data.count) > Double(FileServerAPI.maxFileSize) / FileServerAPI.fileSizeORMultiplier {
|
||||
return seal.reject(DotNetAPIError.maxFileSizeExceeded)
|
||||
}
|
||||
|
@ -144,7 +141,7 @@ public class DotNetAPI : NSObject {
|
|||
var error: NSError?
|
||||
var request = AFHTTPRequestSerializer().multipartFormRequest(withMethod: "POST", urlString: url, parameters: parameters, constructingBodyWith: { formData in
|
||||
let uuid = UUID().uuidString
|
||||
print("[Loki] File UUID: \(uuid)")
|
||||
print("[Loki] File UUID: \(uuid).")
|
||||
formData.appendPart(withFileData: data, name: "content", fileName: uuid, mimeType: "application/binary")
|
||||
}, error: &error)
|
||||
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
||||
|
@ -153,7 +150,7 @@ public class DotNetAPI : NSObject {
|
|||
return seal.reject(error)
|
||||
}
|
||||
// Send the request
|
||||
let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise { $0.fulfill(FileServerAPI.fileServerPublicKey) }
|
||||
let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise.value(FileServerAPI.fileServerPublicKey)
|
||||
: PublicChatAPI.getOpenGroupServerPublicKey(for: server)
|
||||
attachment.isUploaded = false
|
||||
attachment.save()
|
||||
|
@ -198,7 +195,7 @@ internal extension Promise {
|
|||
return recover2 { error -> Promise<T> in
|
||||
if case HTTP.Error.httpRequestFailed(let statusCode, _) = error, statusCode == 401 || statusCode == 403 {
|
||||
print("[Loki] Auth token for: \(server) expired; dropping it.")
|
||||
DotNetAPI.clearAuthToken(for: server)
|
||||
DotNetAPI.removeAuthToken(for: server)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
|
|
@ -22,136 +22,6 @@ public final class FileServerAPI : DotNetAPI {
|
|||
// MARK: Storage
|
||||
override internal class var authTokenCollection: String { return "LokiStorageAuthTokenCollection" }
|
||||
|
||||
// MARK: Device Links
|
||||
/// - Note: Deprecated.
|
||||
@objc(getDeviceLinksAssociatedWithHexEncodedPublicKey:)
|
||||
public static func objc_getDeviceLinks(associatedWith hexEncodedPublicKey: String) -> AnyPromise {
|
||||
return AnyPromise.from(getDeviceLinks(associatedWith: hexEncodedPublicKey))
|
||||
}
|
||||
|
||||
/// Gets the device links associated with the given hex encoded public key from the
|
||||
/// server and stores and returns the valid ones.
|
||||
///
|
||||
/// - Note: Deprecated.
|
||||
public static func getDeviceLinks(associatedWith hexEncodedPublicKey: String) -> Promise<Set<DeviceLink>> {
|
||||
return getDeviceLinks(associatedWith: [ hexEncodedPublicKey ])
|
||||
}
|
||||
|
||||
/// - Note: Deprecated.
|
||||
@objc(getDeviceLinksAssociatedWithHexEncodedPublicKeys:)
|
||||
public static func objc_getDeviceLinks(associatedWith hexEncodedPublicKeys: Set<String>) -> AnyPromise {
|
||||
return AnyPromise.from(getDeviceLinks(associatedWith: hexEncodedPublicKeys))
|
||||
}
|
||||
|
||||
/// Gets the device links associated with the given hex encoded public keys from the
|
||||
/// server and stores and returns the valid ones.
|
||||
///
|
||||
/// - Note: Deprecated.
|
||||
public static func getDeviceLinks(associatedWith hexEncodedPublicKeys: Set<String>) -> Promise<Set<DeviceLink>> {
|
||||
let hexEncodedPublicKeysDescription = "[ \(hexEncodedPublicKeys.joined(separator: ", ")) ]"
|
||||
print("[Loki] Getting device links for: \(hexEncodedPublicKeysDescription).")
|
||||
return getAuthToken(for: server).then2 { token -> Promise<Set<DeviceLink>> in
|
||||
let queryParameters = "ids=\(hexEncodedPublicKeys.map { "@\($0)" }.joined(separator: ","))&include_user_annotations=1"
|
||||
let url = URL(string: "\(server)/users?\(queryParameters)")!
|
||||
let request = TSRequest(url: url)
|
||||
return OnionRequestAPI.sendOnionRequest(request, to: server, using: fileServerPublicKey).map2 { rawResponse -> Set<DeviceLink> in
|
||||
guard let data = rawResponse["data"] as? [JSON] else {
|
||||
print("[Loki] Couldn't parse device links for users: \(hexEncodedPublicKeys) from: \(rawResponse).")
|
||||
throw DotNetAPIError.parsingFailed
|
||||
}
|
||||
return Set(data.flatMap { data -> [DeviceLink] in
|
||||
guard let annotations = data["annotations"] as? [JSON], !annotations.isEmpty else { return [] }
|
||||
guard let annotation = annotations.first(where: { $0["type"] as? String == deviceLinkType }),
|
||||
let value = annotation["value"] as? JSON, let rawDeviceLinks = value["authorisations"] as? [JSON],
|
||||
let hexEncodedPublicKey = data["username"] as? String else {
|
||||
print("[Loki] Couldn't parse device links from: \(rawResponse).")
|
||||
return []
|
||||
}
|
||||
return rawDeviceLinks.compactMap { rawDeviceLink in
|
||||
guard let masterPublicKey = rawDeviceLink["primaryDevicePubKey"] as? String, let slavePublicKey = rawDeviceLink["secondaryDevicePubKey"] as? String,
|
||||
let base64EncodedSlaveSignature = rawDeviceLink["requestSignature"] as? String else {
|
||||
print("[Loki] Couldn't parse device link for user: \(hexEncodedPublicKey) from: \(rawResponse).")
|
||||
return nil
|
||||
}
|
||||
let masterSignature: Data?
|
||||
if let base64EncodedMasterSignature = rawDeviceLink["grantSignature"] as? String {
|
||||
masterSignature = Data(base64Encoded: base64EncodedMasterSignature)
|
||||
} else {
|
||||
masterSignature = nil
|
||||
}
|
||||
let slaveSignature = Data(base64Encoded: base64EncodedSlaveSignature)
|
||||
let master = DeviceLink.Device(publicKey: masterPublicKey, signature: masterSignature)
|
||||
let slave = DeviceLink.Device(publicKey: slavePublicKey, signature: slaveSignature)
|
||||
let deviceLink = DeviceLink(between: master, and: slave)
|
||||
if let masterSignature = masterSignature {
|
||||
guard DeviceLinkingUtilities.hasValidMasterSignature(deviceLink) else {
|
||||
print("[Loki] Received a device link with an invalid master signature.")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
guard DeviceLinkingUtilities.hasValidSlaveSignature(deviceLink) else {
|
||||
print("[Loki] Received a device link with an invalid slave signature.")
|
||||
return nil
|
||||
}
|
||||
return deviceLink
|
||||
}
|
||||
})
|
||||
}.map2 { deviceLinks in
|
||||
storage.setDeviceLinks(deviceLinks)
|
||||
return deviceLinks
|
||||
}
|
||||
}.handlingInvalidAuthTokenIfNeeded(for: server)
|
||||
}
|
||||
|
||||
/// - Note: Deprecated.
|
||||
public static func setDeviceLinks(_ deviceLinks: Set<DeviceLink>) -> Promise<Void> {
|
||||
print("[Loki] Updating device links.")
|
||||
return getAuthToken(for: server).then2 { token -> Promise<Void> in
|
||||
let isMaster = deviceLinks.contains { $0.master.publicKey == getUserHexEncodedPublicKey() }
|
||||
let deviceLinksAsJSON = deviceLinks.map { $0.toJSON() }
|
||||
let value = !deviceLinksAsJSON.isEmpty ? [ "isPrimary" : isMaster ? 1 : 0, "authorisations" : deviceLinksAsJSON ] : nil
|
||||
let annotation: JSON = [ "type" : deviceLinkType, "value" : value ]
|
||||
let parameters: JSON = [ "annotations" : [ annotation ] ]
|
||||
let url = URL(string: "\(server)/users/me")!
|
||||
let request = TSRequest(url: url, method: "PATCH", parameters: parameters)
|
||||
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
|
||||
return attempt(maxRetryCount: 8, recoveringOn: SnodeAPI.workQueue) {
|
||||
OnionRequestAPI.sendOnionRequest(request, to: server, using: fileServerPublicKey).map2 { _ in }
|
||||
}.handlingInvalidAuthTokenIfNeeded(for: server).recover2 { error in
|
||||
print("[Loki] Couldn't update device links due to error: \(error).")
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the given device link to the user's device mapping on the server.
|
||||
///
|
||||
/// - Note: Deprecated.
|
||||
public static func addDeviceLink(_ deviceLink: DeviceLink) -> Promise<Void> {
|
||||
var deviceLinks: Set<DeviceLink> = []
|
||||
storage.dbReadConnection.read { transaction in
|
||||
deviceLinks = storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction)
|
||||
}
|
||||
deviceLinks.insert(deviceLink)
|
||||
return setDeviceLinks(deviceLinks).map2 { _ in
|
||||
storage.addDeviceLink(deviceLink)
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the given device link from the user's device mapping on the server.
|
||||
///
|
||||
/// - Note: Deprecated.
|
||||
public static func removeDeviceLink(_ deviceLink: DeviceLink) -> Promise<Void> {
|
||||
var deviceLinks: Set<DeviceLink> = []
|
||||
storage.dbReadConnection.read { transaction in
|
||||
deviceLinks = storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction)
|
||||
}
|
||||
deviceLinks.remove(deviceLink)
|
||||
return setDeviceLinks(deviceLinks).map2 { _ in
|
||||
storage.removeDeviceLink(deviceLink)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Profile Pictures
|
||||
@objc(uploadProfilePicture:)
|
||||
public static func objc_uploadProfilePicture(_ profilePicture: Data) -> AnyPromise {
|
||||
|
|
|
@ -290,8 +290,8 @@ public enum OnionRequestAPI {
|
|||
let url = "\(guardSnode.address):\(guardSnode.port)/onion_req"
|
||||
let finalEncryptionResult = intermediate.finalEncryptionResult
|
||||
let onion = finalEncryptionResult.ciphertext
|
||||
if case Destination.server = destination {
|
||||
print("[Loki] Onion request size: ~\(onion.count)")
|
||||
if case Destination.server = destination, Double(onion.count) > 0.75 * (Double(FileServerAPI.maxFileSize) / FileServerAPI.fileSizeORMultiplier) {
|
||||
print("[Loki] Approaching request size limit: ~\(onion.count) bytes.")
|
||||
}
|
||||
let parameters: JSON = [
|
||||
"ciphertext" : onion.base64EncodedString(),
|
||||
|
@ -327,7 +327,7 @@ public enum OnionRequestAPI {
|
|||
guard 200...299 ~= statusCode else { return seal.reject(Error.httpRequestFailedAtTargetSnode(statusCode: UInt(statusCode), json: json)) }
|
||||
seal.fulfill(json)
|
||||
}
|
||||
} catch (let error) {
|
||||
} catch {
|
||||
seal.reject(error)
|
||||
}
|
||||
}.catch2 { error in
|
||||
|
|
|
@ -32,7 +32,7 @@ public final class PublicChatAPI : DotNetAPI {
|
|||
|
||||
private static func getLastMessageServerID(for group: UInt64, on server: String) -> UInt? {
|
||||
var result: UInt? = nil
|
||||
storage.dbReadConnection.read { transaction in
|
||||
Storage.read { transaction in
|
||||
result = transaction.object(forKey: "\(server).\(group)", inCollection: lastMessageServerIDCollection) as! UInt?
|
||||
}
|
||||
return result
|
||||
|
@ -52,7 +52,7 @@ public final class PublicChatAPI : DotNetAPI {
|
|||
|
||||
private static func getLastDeletionServerID(for group: UInt64, on server: String) -> UInt? {
|
||||
var result: UInt? = nil
|
||||
storage.dbReadConnection.read { transaction in
|
||||
Storage.read { transaction in
|
||||
result = transaction.object(forKey: "\(server).\(group)", inCollection: lastDeletionServerIDCollection) as! UInt?
|
||||
}
|
||||
return result
|
||||
|
@ -174,8 +174,8 @@ public final class PublicChatAPI : DotNetAPI {
|
|||
return nil
|
||||
}
|
||||
var existingMessageID: String? = nil
|
||||
storage.dbReadConnection.read { transaction in
|
||||
existingMessageID = storage.getIDForMessage(withServerID: UInt(result.serverID!), in: transaction)
|
||||
Storage.read { transaction in
|
||||
existingMessageID = OWSPrimaryStorage.shared().getIDForMessage(withServerID: UInt(result.serverID!), in: transaction)
|
||||
}
|
||||
guard existingMessageID == nil else {
|
||||
print("[Loki] Ignoring duplicate public chat message.")
|
||||
|
|
|
@ -60,6 +60,7 @@ public final class PublicChatPoller : NSObject {
|
|||
let uniquePublicKeys = Set(messages.map { $0.senderPublicKey })
|
||||
func proceed() {
|
||||
let storage = OWSPrimaryStorage.shared()
|
||||
/*
|
||||
var newDisplayNameUpdatees: Set<String> = []
|
||||
storage.dbReadConnection.read { transaction in
|
||||
newDisplayNameUpdatees = Set(uniquePublicKeys.filter { storage.getMasterHexEncodedPublicKey(for: $0, in: transaction) != $0 }.compactMap { storage.getMasterHexEncodedPublicKey(for: $0, in: transaction) })
|
||||
|
@ -68,6 +69,7 @@ public final class PublicChatPoller : NSObject {
|
|||
let displayNameUpdatees = PublicChatAPI.displayNameUpdatees[publicChat.id] ?? []
|
||||
PublicChatAPI.displayNameUpdatees[publicChat.id] = displayNameUpdatees.union(newDisplayNameUpdatees)
|
||||
}
|
||||
*/
|
||||
// Sorting the messages by timestamp before importing them fixes an issue where messages that quote older messages can't find those older messages
|
||||
messages.sorted { $0.timestamp < $1.timestamp }.forEach { message in
|
||||
var wasSentByCurrentUser = false
|
||||
|
@ -183,6 +185,7 @@ public final class PublicChatPoller : NSObject {
|
|||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
let hexEncodedPublicKeysToUpdate = uniquePublicKeys.filter { hexEncodedPublicKey in
|
||||
let timeSinceLastUpdate: TimeInterval
|
||||
if let lastDeviceLinkUpdate = MultiDeviceProtocol.lastDeviceLinkUpdate[hexEncodedPublicKey] {
|
||||
|
@ -208,10 +211,13 @@ public final class PublicChatPoller : NSObject {
|
|||
proceed()
|
||||
}
|
||||
} else {
|
||||
*/
|
||||
DispatchQueue.global(qos: .default).async {
|
||||
proceed()
|
||||
}
|
||||
/*
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -119,7 +119,7 @@ public final class SnodeAPI : NSObject {
|
|||
if let cachedSwarm = swarmCache[publicKey], cachedSwarm.count >= minimumSwarmSnodeCount && !isForcedReload {
|
||||
return Promise<[Snode]> { $0.fulfill(cachedSwarm) }
|
||||
} else {
|
||||
print("[Loki] Getting swarm for: \(publicKey).")
|
||||
print("[Loki] Getting swarm for: \(publicKey == getUserHexEncodedPublicKey() ? "self" : publicKey).")
|
||||
let parameters: [String:Any] = [ "pubKey" : publicKey ]
|
||||
return getRandomSnode().then2 {
|
||||
invoke(.getSwarm, on: $0, associatedWith: publicKey, parameters: parameters)
|
||||
|
|
|
@ -26,6 +26,8 @@ public final class LokiDatabaseUtilities : NSObject {
|
|||
// MARK: - Device Links
|
||||
@objc(getLinkedDeviceHexEncodedPublicKeysFor:in:)
|
||||
public static func getLinkedDeviceHexEncodedPublicKeys(for hexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> Set<String> {
|
||||
return [ hexEncodedPublicKey ]
|
||||
/*
|
||||
let storage = OWSPrimaryStorage.shared()
|
||||
let masterHexEncodedPublicKey = storage.getMasterHexEncodedPublicKey(for: hexEncodedPublicKey, in: transaction) ?? hexEncodedPublicKey
|
||||
var result = Set(storage.getDeviceLinks(for: masterHexEncodedPublicKey, in: transaction).flatMap { deviceLink in
|
||||
|
@ -33,28 +35,35 @@ public final class LokiDatabaseUtilities : NSObject {
|
|||
})
|
||||
result.insert(hexEncodedPublicKey)
|
||||
return result
|
||||
*/
|
||||
}
|
||||
|
||||
@objc(getLinkedDeviceThreadsFor:in:)
|
||||
public static func getLinkedDeviceThreads(for hexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> Set<TSContactThread> {
|
||||
return Set(getLinkedDeviceHexEncodedPublicKeys(for: hexEncodedPublicKey, in: transaction).compactMap { TSContactThread.getWithContactId($0, transaction: transaction) })
|
||||
return Set([ TSContactThread.getWithContactId(hexEncodedPublicKey, transaction: transaction) ].compactMap { $0 })
|
||||
// return Set(getLinkedDeviceHexEncodedPublicKeys(for: hexEncodedPublicKey, in: transaction).compactMap { TSContactThread.getWithContactId($0, transaction: transaction) })
|
||||
}
|
||||
|
||||
@objc(isUserLinkedDevice:in:)
|
||||
public static func isUserLinkedDevice(_ hexEncodedPublicKey: String, transaction: YapDatabaseReadTransaction) -> Bool {
|
||||
return hexEncodedPublicKey == getUserHexEncodedPublicKey()
|
||||
/*
|
||||
let userHexEncodedPublicKey = getUserHexEncodedPublicKey()
|
||||
let userLinkedDeviceHexEncodedPublicKeys = getLinkedDeviceHexEncodedPublicKeys(for: userHexEncodedPublicKey, in: transaction)
|
||||
return userLinkedDeviceHexEncodedPublicKeys.contains(hexEncodedPublicKey)
|
||||
*/
|
||||
}
|
||||
|
||||
@objc(getMasterHexEncodedPublicKeyFor:in:)
|
||||
public static func objc_getMasterHexEncodedPublicKey(for slaveHexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> String? {
|
||||
return OWSPrimaryStorage.shared().getMasterHexEncodedPublicKey(for: slaveHexEncodedPublicKey, in: transaction)
|
||||
return nil
|
||||
// return OWSPrimaryStorage.shared().getMasterHexEncodedPublicKey(for: slaveHexEncodedPublicKey, in: transaction)
|
||||
}
|
||||
|
||||
@objc(getDeviceLinksFor:in:)
|
||||
public static func objc_getDeviceLinks(for masterHexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> Set<DeviceLink> {
|
||||
return OWSPrimaryStorage.shared().getDeviceLinks(for: masterHexEncodedPublicKey, in: transaction)
|
||||
return []
|
||||
// return OWSPrimaryStorage.shared().getDeviceLinks(for: masterHexEncodedPublicKey, in: transaction)
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -30,7 +30,7 @@ public extension OWSPrimaryStorage {
|
|||
|
||||
// MARK: Swarm
|
||||
public func setSwarm(_ swarm: [Snode], for publicKey: String, in transaction: YapDatabaseReadWriteTransaction) {
|
||||
print("[Loki] Caching swarm for: \(publicKey).")
|
||||
print("[Loki] Caching swarm for: \(publicKey == getUserHexEncodedPublicKey() ? "self" : publicKey).")
|
||||
clearSwarm(for: publicKey, in: transaction)
|
||||
let collection = Storage.getSwarmCollection(for: publicKey)
|
||||
swarm.forEach { snode in
|
||||
|
@ -95,31 +95,12 @@ public extension OWSPrimaryStorage {
|
|||
}
|
||||
|
||||
// MARK: Multi Device
|
||||
private static var deviceLinkCache: Set<DeviceLink> = []
|
||||
|
||||
public func setDeviceLinks(_ deviceLinks: Set<DeviceLink>) {
|
||||
deviceLinks.forEach { addDeviceLink($0) }
|
||||
}
|
||||
|
||||
public func addDeviceLink(_ deviceLink: DeviceLink) {
|
||||
OWSPrimaryStorage.deviceLinkCache.insert(deviceLink)
|
||||
}
|
||||
|
||||
public func removeDeviceLink(_ deviceLink: DeviceLink) {
|
||||
OWSPrimaryStorage.deviceLinkCache.remove(deviceLink)
|
||||
}
|
||||
|
||||
public func getDeviceLinks(for masterHexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> Set<DeviceLink> {
|
||||
return OWSPrimaryStorage.deviceLinkCache.filter { $0.master.publicKey == masterHexEncodedPublicKey }
|
||||
}
|
||||
|
||||
public func getDeviceLink(for slaveHexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> DeviceLink? {
|
||||
return OWSPrimaryStorage.deviceLinkCache.filter { $0.slave.publicKey == slaveHexEncodedPublicKey }.first
|
||||
}
|
||||
|
||||
public func getMasterHexEncodedPublicKey(for slaveHexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> String? {
|
||||
return getDeviceLink(for: slaveHexEncodedPublicKey, in: transaction)?.master.publicKey
|
||||
}
|
||||
public func setDeviceLinks(_ deviceLinks: Set<DeviceLink>) { }
|
||||
public func addDeviceLink(_ deviceLink: DeviceLink) { }
|
||||
public func removeDeviceLink(_ deviceLink: DeviceLink) { }
|
||||
public func getDeviceLinks(for masterHexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> Set<DeviceLink> { return [] }
|
||||
public func getDeviceLink(for slaveHexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> DeviceLink? { return nil }
|
||||
public func getMasterHexEncodedPublicKey(for slaveHexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> String? { return nil }
|
||||
|
||||
// MARK: Open Groups
|
||||
public func getUserCount(for publicChat: PublicChat, in transaction: YapDatabaseReadTransaction) -> Int? {
|
||||
|
|
|
@ -19,7 +19,7 @@ public final class SessionMetaProtocol : NSObject {
|
|||
|
||||
// MARK: Message Destination(s)
|
||||
@objc public static func getDestinationsForOutgoingSyncMessage() -> NSMutableSet {
|
||||
return NSMutableSet(set: MultiDeviceProtocol.getUserLinkedDevices())
|
||||
return NSMutableSet(set: [ getUserHexEncodedPublicKey() ]) // return NSMutableSet(set: MultiDeviceProtocol.getUserLinkedDevices())
|
||||
}
|
||||
|
||||
@objc(getDestinationsForOutgoingGroupMessage:inThread:)
|
||||
|
@ -41,7 +41,7 @@ public final class SessionMetaProtocol : NSObject {
|
|||
} else {
|
||||
result = Set(outgoingGroupMessage.sendingRecipientIds())
|
||||
.intersection(thread.groupModel.groupMemberIds)
|
||||
.subtracting(MultiDeviceProtocol.getUserLinkedDevices())
|
||||
.subtracting([ getUserHexEncodedPublicKey() ]) // .subtracting(MultiDeviceProtocol.getUserLinkedDevices())
|
||||
}
|
||||
}
|
||||
return NSMutableSet(set: result)
|
||||
|
@ -51,11 +51,14 @@ public final class SessionMetaProtocol : NSObject {
|
|||
@objc(isThreadNoteToSelf:)
|
||||
public static func isThreadNoteToSelf(_ thread: TSThread) -> Bool {
|
||||
guard let thread = thread as? TSContactThread else { return false }
|
||||
return thread.contactIdentifier() == getUserHexEncodedPublicKey()
|
||||
/*
|
||||
var isNoteToSelf = false
|
||||
storage.dbReadConnection.read { transaction in
|
||||
isNoteToSelf = LokiDatabaseUtilities.isUserLinkedDevice(thread.contactIdentifier(), transaction: transaction)
|
||||
}
|
||||
return isNoteToSelf
|
||||
*/
|
||||
}
|
||||
|
||||
// MARK: Transcripts
|
||||
|
@ -65,12 +68,15 @@ public final class SessionMetaProtocol : NSObject {
|
|||
let isOpenGroupMessage = (thread as? TSGroupThread)?.isPublicChat == true
|
||||
let wouldSignalRequireTranscript = (AreRecipientUpdatesEnabled() || !message.hasSyncedTranscript)
|
||||
guard wouldSignalRequireTranscript && !isOpenGroupMessage else { return false }
|
||||
return false
|
||||
/*
|
||||
var usesMultiDevice = false
|
||||
storage.dbReadConnection.read { transaction in
|
||||
usesMultiDevice = !storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction).isEmpty
|
||||
|| UserDefaults.standard[.masterHexEncodedPublicKey] != nil
|
||||
}
|
||||
return usesMultiDevice
|
||||
*/
|
||||
}
|
||||
|
||||
// MARK: Typing Indicators
|
||||
|
@ -91,21 +97,24 @@ public final class SessionMetaProtocol : NSObject {
|
|||
|
||||
@objc(shouldSkipMessageDecryptResult:wrappedIn:)
|
||||
public static func shouldSkipMessageDecryptResult(_ result: OWSMessageDecryptResult, wrappedIn envelope: SSKProtoEnvelope) -> Bool {
|
||||
return result.source == getUserHexEncodedPublicKey()
|
||||
/*
|
||||
if result.source == getUserHexEncodedPublicKey() { return true }
|
||||
var isLinkedDevice = false
|
||||
Storage.read { transaction in
|
||||
isLinkedDevice = LokiDatabaseUtilities.isUserLinkedDevice(result.source, transaction: transaction)
|
||||
}
|
||||
return isLinkedDevice && envelope.type == .closedGroupCiphertext
|
||||
*/
|
||||
}
|
||||
|
||||
@objc(updateDisplayNameIfNeededForPublicKey:using:transaction:)
|
||||
public static func updateDisplayNameIfNeeded(for publicKey: String, using dataMessage: SSKProtoDataMessage, in transaction: YapDatabaseReadWriteTransaction) {
|
||||
guard let profile = dataMessage.profile, let rawDisplayName = profile.displayName, !rawDisplayName.isEmpty else { return }
|
||||
let displayName: String
|
||||
if UserDefaults.standard[.masterHexEncodedPublicKey] == publicKey {
|
||||
displayName = rawDisplayName
|
||||
} else {
|
||||
// if UserDefaults.standard[.masterHexEncodedPublicKey] == publicKey {
|
||||
// displayName = rawDisplayName
|
||||
// } else {
|
||||
let shortID = publicKey.substring(from: publicKey.index(publicKey.endIndex, offsetBy: -8))
|
||||
let suffix = "(...\(shortID))"
|
||||
if rawDisplayName.hasSuffix(suffix) {
|
||||
|
@ -113,7 +122,7 @@ public final class SessionMetaProtocol : NSObject {
|
|||
} else {
|
||||
displayName = "\(rawDisplayName) \(suffix)"
|
||||
}
|
||||
}
|
||||
// }
|
||||
let profileManager = SSKEnvironment.shared.profileManager
|
||||
profileManager.updateProfileForContact(withID: publicKey, displayName: displayName, with: transaction)
|
||||
}
|
||||
|
@ -122,8 +131,7 @@ public final class SessionMetaProtocol : NSObject {
|
|||
public static func updateProfileKeyIfNeeded(for publicKey: String, using dataMessage: SSKProtoDataMessage) {
|
||||
guard dataMessage.hasProfileKey, let profileKey = dataMessage.profileKey else { return }
|
||||
guard profileKey.count == kAES256_KeyByteLength else {
|
||||
print("[Loki] Unexpected profile key size: \(profileKey.count).")
|
||||
return
|
||||
return print("[Loki] Unexpected profile key size: \(profileKey.count).")
|
||||
}
|
||||
let profilePictureURL = dataMessage.profile?.profilePicture
|
||||
let profileManager = SSKEnvironment.shared.profileManager
|
||||
|
|
|
@ -25,11 +25,7 @@ public final class LokiPushNotificationManager : NSObject {
|
|||
let isUsingFullAPNs = userDefaults[.isUsingFullAPNs]
|
||||
let now = Date().timeIntervalSince1970
|
||||
guard isForcedUpdate || hexEncodedToken != oldToken || now - lastUploadTime > tokenExpirationInterval else {
|
||||
print("[Loki] Device token hasn't changed; no need to re-upload.")
|
||||
return Promise<Void> { $0.fulfill(()) }
|
||||
}
|
||||
guard !isUsingFullAPNs else {
|
||||
print("[Loki] Using full APNs; ignoring call to register(with:).")
|
||||
print("[Loki] Device token hasn't changed or expired; no need to re-upload.")
|
||||
return Promise<Void> { $0.fulfill(()) }
|
||||
}
|
||||
let parameters = [ "token" : hexEncodedToken ]
|
||||
|
@ -70,7 +66,7 @@ public final class LokiPushNotificationManager : NSObject {
|
|||
let lastUploadTime = userDefaults[.lastDeviceTokenUpload]
|
||||
let now = Date().timeIntervalSince1970
|
||||
guard isForcedUpdate || hexEncodedToken != oldToken || now - lastUploadTime > tokenExpirationInterval else {
|
||||
print("[Loki] Device token hasn't changed; no need to re-upload.")
|
||||
print("[Loki] Device token hasn't changed or expired; no need to re-upload.")
|
||||
return Promise<Void> { $0.fulfill(()) }
|
||||
}
|
||||
let parameters = [ "token" : hexEncodedToken, "pubKey" : hexEncodedPublicKey]
|
||||
|
|
|
@ -1240,6 +1240,7 @@ NS_ASSUME_NONNULL_BEGIN
|
|||
return nil;
|
||||
}
|
||||
|
||||
/*
|
||||
// Loki: Update device links in a blocking way
|
||||
// FIXME: This is horrible for performance
|
||||
// FIXME: ========
|
||||
|
@ -1256,6 +1257,7 @@ NS_ASSUME_NONNULL_BEGIN
|
|||
dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC));
|
||||
}
|
||||
// FIXME: ========
|
||||
*/
|
||||
|
||||
if (groupId.length > 0) {
|
||||
NSMutableSet *newMemberIds = [NSMutableSet setWithArray:dataMessage.group.members];
|
||||
|
@ -1509,9 +1511,9 @@ NS_ASSUME_NONNULL_BEGIN
|
|||
serverTimestamp:serverTimestamp
|
||||
wasReceivedByUD:wasReceivedByUD];
|
||||
|
||||
[LKSessionMetaProtocol updateDisplayNameIfNeededForPublicKey:incomingMessage.authorId using:dataMessage transaction:transaction];
|
||||
[LKSessionMetaProtocol updateProfileKeyIfNeededForPublicKey:masterPublicKey using:dataMessage];
|
||||
|
||||
[LKSessionMetaProtocol updateProfileKeyIfNeededForPublicKey:thread.contactIdentifier using:dataMessage];
|
||||
[LKSessionMetaProtocol updateDisplayNameIfNeededForPublicKey:masterPublicKey using:dataMessage transaction:transaction];
|
||||
|
||||
NSArray<TSAttachmentPointer *> *attachmentPointers =
|
||||
[TSAttachmentPointer attachmentPointersFromProtos:dataMessage.attachments albumMessage:incomingMessage];
|
||||
|
|
|
@ -598,14 +598,14 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException";
|
|||
resolve(error);
|
||||
}];
|
||||
|
||||
NSString *publicKey = recipients.firstObject.recipientId;
|
||||
if ([LKMultiDeviceProtocol isMultiDeviceRequiredForMessage:message toPublicKey:publicKey]) { // Avoid the write transaction if possible
|
||||
[self.primaryStorage.dbReadConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
|
||||
[LKMultiDeviceProtocol sendMessageToDestinationAndLinkedDevices:messageSend transaction:transaction];
|
||||
}];
|
||||
} else {
|
||||
// NSString *publicKey = recipients.firstObject.recipientId;
|
||||
// if ([LKMultiDeviceProtocol isMultiDeviceRequiredForMessage:message toPublicKey:publicKey]) { // Avoid the write transaction if possible
|
||||
// [self.primaryStorage.dbReadConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
|
||||
// [LKMultiDeviceProtocol sendMessageToDestinationAndLinkedDevices:messageSend transaction:transaction];
|
||||
// }];
|
||||
// } else {
|
||||
[self sendMessage:messageSend];
|
||||
}
|
||||
// }
|
||||
}];
|
||||
[sendPromises addObject:sendPromise];
|
||||
}
|
||||
|
|
|
@ -397,7 +397,7 @@ public class TypingIndicatorsImpl: NSObject, TypingIndicators {
|
|||
AssertIsOnMainThread()
|
||||
|
||||
displayTypingTimer?.invalidate()
|
||||
displayTypingTimer = Timer.weakScheduledTimer(withTimeInterval: 15,
|
||||
displayTypingTimer = Timer.weakScheduledTimer(withTimeInterval: 5,
|
||||
target: self,
|
||||
selector: #selector(IncomingIndicators.displayTypingTimerDidFire),
|
||||
userInfo: nil,
|
||||
|
|
Loading…
Reference in a new issue