Merge branch 'dev' of https://github.com/loki-project/session-ios into fix-open-group-issues

pull/205/head
ryanzhao 5 years ago
commit edaafd8a42

@ -4439,7 +4439,7 @@
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 80; CURRENT_PROJECT_VERSION = 81;
DEBUG_INFORMATION_FORMAT = dwarf; DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = SUQ8J2PCT7; DEVELOPMENT_TEAM = SUQ8J2PCT7;
FRAMEWORK_SEARCH_PATHS = "$(inherited)"; FRAMEWORK_SEARCH_PATHS = "$(inherited)";
@ -4453,7 +4453,7 @@
INFOPLIST_FILE = SignalShareExtension/Info.plist; INFOPLIST_FILE = SignalShareExtension/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 12.0; IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
MARKETING_VERSION = 1.2.3; MARKETING_VERSION = 1.2.4;
MTL_ENABLE_DEBUG_INFO = YES; MTL_ENABLE_DEBUG_INFO = YES;
PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger.share-extension"; PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger.share-extension";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
@ -4501,7 +4501,7 @@
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 80; CURRENT_PROJECT_VERSION = 81;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = SUQ8J2PCT7; DEVELOPMENT_TEAM = SUQ8J2PCT7;
ENABLE_NS_ASSERTIONS = NO; ENABLE_NS_ASSERTIONS = NO;
@ -4520,7 +4520,7 @@
INFOPLIST_FILE = SignalShareExtension/Info.plist; INFOPLIST_FILE = SignalShareExtension/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 12.0; IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
MARKETING_VERSION = 1.2.3; MARKETING_VERSION = 1.2.4;
MTL_ENABLE_DEBUG_INFO = NO; MTL_ENABLE_DEBUG_INFO = NO;
PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger.share-extension"; PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger.share-extension";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
@ -4555,7 +4555,7 @@
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 80; CURRENT_PROJECT_VERSION = 81;
DEBUG_INFORMATION_FORMAT = dwarf; DEBUG_INFORMATION_FORMAT = dwarf;
DEFINES_MODULE = YES; DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = SUQ8J2PCT7; DEVELOPMENT_TEAM = SUQ8J2PCT7;
@ -4574,7 +4574,7 @@
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 12.0; IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MARKETING_VERSION = 1.2.3; MARKETING_VERSION = 1.2.4;
MTL_ENABLE_DEBUG_INFO = YES; MTL_ENABLE_DEBUG_INFO = YES;
PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger.utilities"; PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger.utilities";
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
@ -4625,7 +4625,7 @@
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 80; CURRENT_PROJECT_VERSION = 81;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEFINES_MODULE = YES; DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = SUQ8J2PCT7; DEVELOPMENT_TEAM = SUQ8J2PCT7;
@ -4649,7 +4649,7 @@
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 12.0; IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
MARKETING_VERSION = 1.2.3; MARKETING_VERSION = 1.2.4;
MTL_ENABLE_DEBUG_INFO = NO; MTL_ENABLE_DEBUG_INFO = NO;
PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger.utilities"; PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger.utilities";
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
@ -4687,7 +4687,7 @@
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 80; CURRENT_PROJECT_VERSION = 81;
DEBUG_INFORMATION_FORMAT = dwarf; DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = SUQ8J2PCT7; DEVELOPMENT_TEAM = SUQ8J2PCT7;
FRAMEWORK_SEARCH_PATHS = "$(inherited)"; FRAMEWORK_SEARCH_PATHS = "$(inherited)";
@ -4699,7 +4699,7 @@
INFOPLIST_FILE = LokiPushNotificationService/Info.plist; INFOPLIST_FILE = LokiPushNotificationService/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 12.0; IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
MARKETING_VERSION = 1.2.3; MARKETING_VERSION = 1.2.4;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES; MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger.push-notification-service"; PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger.push-notification-service";
@ -4750,7 +4750,7 @@
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 80; CURRENT_PROJECT_VERSION = 81;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = SUQ8J2PCT7; DEVELOPMENT_TEAM = SUQ8J2PCT7;
ENABLE_NS_ASSERTIONS = NO; ENABLE_NS_ASSERTIONS = NO;
@ -4767,7 +4767,7 @@
INFOPLIST_FILE = LokiPushNotificationService/Info.plist; INFOPLIST_FILE = LokiPushNotificationService/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 12.0; IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
MARKETING_VERSION = 1.2.3; MARKETING_VERSION = 1.2.4;
MTL_ENABLE_DEBUG_INFO = NO; MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES; MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger.push-notification-service"; PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger.push-notification-service";
@ -4951,7 +4951,7 @@
CODE_SIGN_ENTITLEMENTS = Signal/Signal.entitlements; CODE_SIGN_ENTITLEMENTS = Signal/Signal.entitlements;
CODE_SIGN_IDENTITY = "iPhone Developer"; CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CURRENT_PROJECT_VERSION = 80; CURRENT_PROJECT_VERSION = 81;
DEVELOPMENT_TEAM = SUQ8J2PCT7; DEVELOPMENT_TEAM = SUQ8J2PCT7;
FRAMEWORK_SEARCH_PATHS = ( FRAMEWORK_SEARCH_PATHS = (
"$(inherited)", "$(inherited)",
@ -4986,7 +4986,7 @@
"$(SRCROOT)", "$(SRCROOT)",
); );
LLVM_LTO = NO; LLVM_LTO = NO;
MARKETING_VERSION = 1.2.3; MARKETING_VERSION = 1.2.4;
OTHER_LDFLAGS = "$(inherited)"; OTHER_LDFLAGS = "$(inherited)";
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\""; OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger"; PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger";
@ -5019,7 +5019,7 @@
CODE_SIGN_ENTITLEMENTS = Signal/Signal.entitlements; CODE_SIGN_ENTITLEMENTS = Signal/Signal.entitlements;
CODE_SIGN_IDENTITY = "iPhone Developer"; CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CURRENT_PROJECT_VERSION = 80; CURRENT_PROJECT_VERSION = 81;
DEVELOPMENT_TEAM = SUQ8J2PCT7; DEVELOPMENT_TEAM = SUQ8J2PCT7;
FRAMEWORK_SEARCH_PATHS = ( FRAMEWORK_SEARCH_PATHS = (
"$(inherited)", "$(inherited)",
@ -5054,7 +5054,7 @@
"$(SRCROOT)", "$(SRCROOT)",
); );
LLVM_LTO = NO; LLVM_LTO = NO;
MARKETING_VERSION = 1.2.3; MARKETING_VERSION = 1.2.4;
OTHER_LDFLAGS = "$(inherited)"; OTHER_LDFLAGS = "$(inherited)";
PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger"; PRODUCT_BUNDLE_IDENTIFIER = "com.loki-project.loki-messenger";
PRODUCT_NAME = Session; PRODUCT_NAME = Session;

@ -137,6 +137,11 @@ final class JoinPublicChatVC : BaseVC, UIPageViewControllerDataSource, UIPageVie
let displayName = OWSProfileManager.shared().profileNameForRecipient(withID: userHexEncodedPublicKey) let displayName = OWSProfileManager.shared().profileNameForRecipient(withID: userHexEncodedPublicKey)
let profilePictureURL = OWSProfileManager.shared().profilePictureURL() let profilePictureURL = OWSProfileManager.shared().profilePictureURL()
let profileKey = OWSProfileManager.shared().localProfileKey().keyData let profileKey = OWSProfileManager.shared().localProfileKey().keyData
// TODO: Profile picture & profile key
OWSPrimaryStorage.shared().dbReadWriteConnection.readWrite { transaction in
transaction.removeObject(forKey: "\(urlAsString).\(channelID)", inCollection: LokiPublicChatAPI.lastMessageServerIDCollection)
transaction.removeObject(forKey: "\(urlAsString).\(channelID)", inCollection: LokiPublicChatAPI.lastDeletionServerIDCollection)
}
LokiPublicChatManager.shared.addChat(server: urlAsString, channel: channelID) LokiPublicChatManager.shared.addChat(server: urlAsString, channel: channelID)
.done(on: .main) { [weak self] _ in .done(on: .main) { [weak self] _ in
let _ = LokiPublicChatAPI.getMessages(for: channelID, on: urlAsString) let _ = LokiPublicChatAPI.getMessages(for: channelID, on: urlAsString)
@ -147,9 +152,15 @@ final class JoinPublicChatVC : BaseVC, UIPageViewControllerDataSource, UIPageVie
let _ = syncManager.syncAllOpenGroups() let _ = syncManager.syncAllOpenGroups()
self?.presentingViewController!.dismiss(animated: true, completion: nil) self?.presentingViewController!.dismiss(animated: true, completion: nil)
} }
.catch(on: .main) { [weak self] _ in .catch(on: .main) { [weak self] error in
var title = NSLocalizedString("Couldn't Join", comment: "")
var message = ""
if case LokiHTTPClient.HTTPError.networkError(let statusCode, _, _) = error, (statusCode == 401 || statusCode == 403) {
title = NSLocalizedString("Unauthorized", comment: "")
message = NSLocalizedString("Please ask the open group operator to add you to the group.", comment: "")
}
self?.isJoining = false self?.isJoining = false
self?.showError(title: NSLocalizedString("Couldn't Join", comment: "")) self?.showError(title: title, message: message)
} }
} }

@ -2840,3 +2840,5 @@
"You" = "You"; "You" = "You";
"Destination" = "Destination"; "Destination" = "Destination";
"Learn More" = "Learn More"; "Learn More" = "Learn More";
"Please ask the open group operator to add you to the group." = "Please ask the open group operator to add you to the group.";
"Unauthorized" = "Unauthorized";

@ -132,42 +132,6 @@ public extension LokiAPI {
} }
} }
internal static func getFileServerProxy() -> Promise<LokiAPITarget> {
let (promise, seal) = Promise<LokiAPITarget>.pending()
func getVersion(for snode: LokiAPITarget) -> Promise<String> {
if let version = snodeVersion[snode] {
return Promise { $0.fulfill(version) }
} else {
let url = URL(string: "\(snode.address):\(snode.port)/get_stats/v1")!
let request = TSRequest(url: url)
return TSNetworkManager.shared().perform(request, withCompletionQueue: DispatchQueue.global()).map(on: DispatchQueue.global()) { intermediate in
let rawResponse = intermediate.responseObject
guard let json = rawResponse as? JSON, let version = json["version"] as? String else { throw LokiAPIError.missingSnodeVersion }
snodeVersion[snode] = version
return version
}
}
}
getRandomSnode().then(on: DispatchQueue.global()) { snode -> Promise<LokiAPITarget> in
return getVersion(for: snode).then(on: DispatchQueue.global()) { version -> Promise<LokiAPITarget> in
if version >= "2.0.2" {
print("[Loki] Using file server proxy with version number \(version).")
return Promise { $0.fulfill(snode) }
} else {
print("[Loki] Rejecting file server proxy with version number \(version).")
return getFileServerProxy()
}
}.recover(on: DispatchQueue.global()) { _ in
return getFileServerProxy()
}
}.done(on: DispatchQueue.global()) { snode in
seal.fulfill(snode)
}.catch(on: DispatchQueue.global()) { error in
seal.reject(error)
}
return promise
}
// MARK: Public API // MARK: Public API
@objc public static func clearSnodePool() { @objc public static func clearSnodePool() {
snodePool.removeAll() snodePool.removeAll()

@ -53,6 +53,15 @@ public class LokiDotNetAPI : NSObject {
transaction.setObject(newValue, forKey: server, inCollection: authTokenCollection) transaction.setObject(newValue, forKey: server, inCollection: authTokenCollection)
} }
public static func clearAuthToken(for server: String) {
// Dispatch async on the main queue to avoid nested write transactions
DispatchQueue.main.async {
storage.dbReadWriteConnection.readWrite { transaction in
transaction.removeObject(forKey: server, inCollection: authTokenCollection)
}
}
}
// MARK: Lifecycle // MARK: Lifecycle
override private init() { } override private init() { }
@ -198,3 +207,17 @@ public class LokiDotNetAPI : NSObject {
} }
} }
} }
// MARK: Error Handling
internal extension Promise {
internal func handlingInvalidAuthTokenIfNeeded(for server: String) -> Promise<T> {
return recover(on: DispatchQueue.global()) { error -> Promise<T> in
if let error = error as? NetworkManagerError, (error.statusCode == 401 || error.statusCode == 403) {
print("[Loki] Group chat auth token for: \(server) expired; dropping it.")
LokiDotNetAPI.clearAuthToken(for: server)
}
throw error
}
}
}

@ -92,7 +92,7 @@ public final class LokiFileServerAPI : LokiDotNetAPI {
*/ */
return deviceLinks return deviceLinks
} }
} }.handlingInvalidAuthTokenIfNeeded(for: server)
} }
public static func setDeviceLinks(_ deviceLinks: Set<DeviceLink>) -> Promise<Void> { public static func setDeviceLinks(_ deviceLinks: Set<DeviceLink>) -> Promise<Void> {
@ -108,7 +108,7 @@ public final class LokiFileServerAPI : LokiDotNetAPI {
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ] request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
return attempt(maxRetryCount: 8, recoveringOn: LokiAPI.workQueue) { return attempt(maxRetryCount: 8, recoveringOn: LokiAPI.workQueue) {
LokiFileServerProxy(for: server).perform(request).map { _ in } LokiFileServerProxy(for: server).perform(request).map { _ in }
}.recover { error in }.handlingInvalidAuthTokenIfNeeded(for: server).recover { error in
print("Couldn't update device links due to error: \(error).") print("Couldn't update device links due to error: \(error).")
throw error throw error
} }

@ -49,7 +49,7 @@ internal class LokiFileServerProxy : LokiHTTPClient {
DispatchQueue.global(qos: .userInitiated).async { DispatchQueue.global(qos: .userInitiated).async {
let uncheckedSymmetricKey = try? Curve25519.generateSharedSecret(fromPublicKey: LokiFileServerProxy.fileServerPublicKey, privateKey: keyPair.privateKey) let uncheckedSymmetricKey = try? Curve25519.generateSharedSecret(fromPublicKey: LokiFileServerProxy.fileServerPublicKey, privateKey: keyPair.privateKey)
guard let symmetricKey = uncheckedSymmetricKey else { return seal.reject(Error.symmetricKeyGenerationFailed) } guard let symmetricKey = uncheckedSymmetricKey else { return seal.reject(Error.symmetricKeyGenerationFailed) }
LokiAPI.getFileServerProxy().then(on: DispatchQueue.global()) { proxy -> Promise<Any> in LokiAPI.getRandomSnode().then(on: DispatchQueue.global()) { proxy -> Promise<Any> in
let url = "\(proxy.address):\(proxy.port)/file_proxy" let url = "\(proxy.address):\(proxy.port)/file_proxy"
guard let urlAsString = request.url?.absoluteString, let serverURLEndIndex = urlAsString.range(of: server)?.upperBound, guard let urlAsString = request.url?.absoluteString, let serverURLEndIndex = urlAsString.range(of: server)?.upperBound,
serverURLEndIndex < urlAsString.endIndex else { throw Error.endpointParsingFailed } serverURLEndIndex < urlAsString.endIndex else { throw Error.endpointParsingFailed }

@ -1,7 +1,7 @@
import PromiseKit import PromiseKit
/// Base class for `LokiSnodeProxy` and `LokiFileServerProxy`. /// Base class for `LokiSnodeProxy` and `LokiFileServerProxy`.
internal class LokiHTTPClient { public class LokiHTTPClient {
internal lazy var httpSession: AFHTTPSessionManager = { internal lazy var httpSession: AFHTTPSessionManager = {
let result = AFHTTPSessionManager(sessionConfiguration: .ephemeral) let result = AFHTTPSessionManager(sessionConfiguration: .ephemeral)
@ -34,9 +34,9 @@ internal class LokiHTTPClient {
// MARK: - HTTP Error // MARK: - HTTP Error
internal extension LokiHTTPClient { public extension LokiHTTPClient {
internal enum HTTPError : LocalizedError { public enum HTTPError : LocalizedError {
case networkError(code: Int, response: Any?, underlyingError: Error?) case networkError(code: Int, response: Any?, underlyingError: Error?)
internal static func from(error: Error) -> LokiHTTPClient.HTTPError? { internal static func from(error: Error) -> LokiHTTPClient.HTTPError? {

@ -25,6 +25,7 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
// MARK: Database // MARK: Database
override internal class var authTokenCollection: String { "LokiGroupChatAuthTokenCollection" } override internal class var authTokenCollection: String { "LokiGroupChatAuthTokenCollection" }
@objc public static let lastMessageServerIDCollection = "LokiGroupChatLastMessageServerIDCollection" @objc public static let lastMessageServerIDCollection = "LokiGroupChatLastMessageServerIDCollection"
@objc public static let lastDeletionServerIDCollection = "LokiGroupChatLastDeletionServerIDCollection" @objc public static let lastDeletionServerIDCollection = "LokiGroupChatLastDeletionServerIDCollection"
@ -73,7 +74,7 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
removeLastDeletionServerID(for: channel, on: server) removeLastDeletionServerID(for: channel, on: server)
} }
// MARK: Public API // MARK: Receiving
@objc(getMessagesForGroup:onServer:) @objc(getMessagesForGroup:onServer:)
public static func objc_getMessages(for group: UInt64, on server: String) -> AnyPromise { public static func objc_getMessages(for group: UInt64, on server: String) -> AnyPromise {
return AnyPromise.from(getMessages(for: group, on: server)) return AnyPromise.from(getMessages(for: group, on: server))
@ -86,8 +87,10 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
} else { } else {
queryParameters += "&count=\(fallbackBatchCount)&include_deleted=0" queryParameters += "&count=\(fallbackBatchCount)&include_deleted=0"
} }
return getAuthToken(for: server).then { token -> Promise<[LokiPublicChatMessage]> in
let url = URL(string: "\(server)/channels/\(channel)/messages?\(queryParameters)")! let url = URL(string: "\(server)/channels/\(channel)/messages?\(queryParameters)")!
let request = TSRequest(url: url) let request = TSRequest(url: url)
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
return LokiFileServerProxy(for: server).perform(request).map(on: DispatchQueue.global()) { rawResponse in return LokiFileServerProxy(for: server).perform(request).map(on: DispatchQueue.global()) { rawResponse in
guard let json = rawResponse as? JSON, let rawMessages = json["data"] as? [JSON] else { guard let json = rawResponse as? JSON, let rawMessages = json["data"] as? [JSON] else {
print("[Loki] Couldn't parse messages for public chat channel with ID: \(channel) on server: \(server) from: \(rawResponse).") print("[Loki] Couldn't parse messages for public chat channel with ID: \(channel) on server: \(server) from: \(rawResponse).")
@ -158,8 +161,10 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
return result return result
}.sorted { $0.timestamp < $1.timestamp } }.sorted { $0.timestamp < $1.timestamp }
} }
}.handlingInvalidAuthTokenIfNeeded(for: server)
} }
// MARK: Sending
@objc(sendMessage:toGroup:onServer:) @objc(sendMessage:toGroup:onServer:)
public static func objc_sendMessage(_ message: LokiPublicChatMessage, to group: UInt64, on server: String) -> AnyPromise { public static func objc_sendMessage(_ message: LokiPublicChatMessage, to group: UInt64, on server: String) -> AnyPromise {
return AnyPromise.from(sendMessage(message, to: group, on: server)) return AnyPromise.from(sendMessage(message, to: group, on: server))
@ -190,13 +195,7 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
let timestamp = UInt64(date.timeIntervalSince1970) * 1000 let timestamp = UInt64(date.timeIntervalSince1970) * 1000
return LokiPublicChatMessage(serverID: serverID, hexEncodedPublicKey: getUserHexEncodedPublicKey(), displayName: displayName, profilePicture: signedMessage.profilePicture, body: body, type: publicChatMessageType, timestamp: timestamp, quote: signedMessage.quote, attachments: signedMessage.attachments, signature: signedMessage.signature) return LokiPublicChatMessage(serverID: serverID, hexEncodedPublicKey: getUserHexEncodedPublicKey(), displayName: displayName, profilePicture: signedMessage.profilePicture, body: body, type: publicChatMessageType, timestamp: timestamp, quote: signedMessage.quote, attachments: signedMessage.attachments, signature: signedMessage.signature)
} }
}.recover { error -> Promise<LokiPublicChatMessage> in }.handlingInvalidAuthTokenIfNeeded(for: server)
if let error = error as? NetworkManagerError, error.statusCode == 401 {
print("[Loki] Group chat auth token for: \(server) expired; dropping it.")
storage.dbReadWriteConnection.removeObject(forKey: server, inCollection: authTokenCollection)
}
throw error
}
}.done { message in }.done { message in
seal.fulfill(message) seal.fulfill(message)
}.catch { error in }.catch { error in
@ -206,6 +205,7 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
return promise return promise
} }
// MARK: Deletion
public static func getDeletedMessageServerIDs(for channel: UInt64, on server: String) -> Promise<[UInt64]> { public static func getDeletedMessageServerIDs(for channel: UInt64, on server: String) -> Promise<[UInt64]> {
print("[Loki] Getting deleted messages for public chat channel with ID: \(channel) on server: \(server).") print("[Loki] Getting deleted messages for public chat channel with ID: \(channel) on server: \(server).")
let queryParameters: String let queryParameters: String
@ -214,8 +214,10 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
} else { } else {
queryParameters = "count=\(fallbackBatchCount)" queryParameters = "count=\(fallbackBatchCount)"
} }
return getAuthToken(for: server).then { token -> Promise<[UInt64]> in
let url = URL(string: "\(server)/loki/v1/channel/\(channel)/deletes?\(queryParameters)")! let url = URL(string: "\(server)/loki/v1/channel/\(channel)/deletes?\(queryParameters)")!
let request = TSRequest(url: url) let request = TSRequest(url: url)
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
return LokiFileServerProxy(for: server).perform(request).map { rawResponse in return LokiFileServerProxy(for: server).perform(request).map { rawResponse in
guard let json = rawResponse as? JSON, let deletions = json["data"] as? [JSON] else { guard let json = rawResponse as? JSON, let deletions = json["data"] as? [JSON] else {
print("[Loki] Couldn't parse deleted messages for public chat channel with ID: \(channel) on server: \(server) from: \(rawResponse).") print("[Loki] Couldn't parse deleted messages for public chat channel with ID: \(channel) on server: \(server) from: \(rawResponse).")
@ -231,6 +233,7 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
return messageServerID return messageServerID
} }
} }
}.handlingInvalidAuthTokenIfNeeded(for: server)
} }
@objc(deleteMessageWithID:forGroup:onServer:isSentByUser:) @objc(deleteMessageWithID:forGroup:onServer:isSentByUser:)
@ -239,65 +242,22 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
} }
public static func deleteMessage(with messageID: UInt, for channel: UInt64, on server: String, isSentByUser: Bool) -> Promise<Void> { public static func deleteMessage(with messageID: UInt, for channel: UInt64, on server: String, isSentByUser: Bool) -> Promise<Void> {
return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global()) {
getAuthToken(for: server).then { token -> Promise<Void> in
let isModerationRequest = !isSentByUser let isModerationRequest = !isSentByUser
print("[Loki] Deleting message with ID: \(messageID) for public chat channel with ID: \(channel) on server: \(server) (isModerationRequest = \(isModerationRequest)).") print("[Loki] Deleting message with ID: \(messageID) for public chat channel with ID: \(channel) on server: \(server) (isModerationRequest = \(isModerationRequest)).")
let urlAsString = isSentByUser ? "\(server)/channels/\(channel)/messages/\(messageID)" : "\(server)/loki/v1/moderation/message/\(messageID)" let urlAsString = isSentByUser ? "\(server)/channels/\(channel)/messages/\(messageID)" : "\(server)/loki/v1/moderation/message/\(messageID)"
let url = URL(string: urlAsString)!
let request = TSRequest(url: url, method: "DELETE", parameters: [:])
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
return LokiFileServerProxy(for: server).perform(request).done { result -> Void in
print("[Loki] Deleted message with ID: \(messageID) on server: \(server).")
}
}
}
}
public static func getModerators(for channel: UInt64, on server: String) -> Promise<Set<String>> {
let url = URL(string: "\(server)/loki/v1/channel/\(channel)/get_moderators")!
let request = TSRequest(url: url)
return LokiFileServerProxy(for: server).perform(request).map { rawResponse in
guard let json = rawResponse as? JSON, let moderators = json["moderators"] as? [String] else {
print("[Loki] Couldn't parse moderators for public chat channel with ID: \(channel) on server: \(server) from: \(rawResponse).")
throw LokiDotNetAPIError.parsingFailed
}
let moderatorAsSet = Set(moderators);
if self.moderators.keys.contains(server) {
self.moderators[server]![channel] = moderatorAsSet
} else {
self.moderators[server] = [ channel : moderatorAsSet ]
}
return moderatorAsSet
}
}
public static func join(_ channel: UInt64, on server: String) -> Promise<Void> {
return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global()) { return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global()) {
getAuthToken(for: server).then { token -> Promise<Void> in getAuthToken(for: server).then { token -> Promise<Void> in
let url = URL(string: "\(server)/channels/\(channel)/subscribe")! let url = URL(string: urlAsString)!
let request = TSRequest(url: url, method: "POST", parameters: [:])
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
return LokiFileServerProxy(for: server).perform(request).done { result -> Void in
print("[Loki] Joined channel with ID: \(channel) on server: \(server).")
}
}
}
}
public static func leave(_ channel: UInt64, on server: String) -> Promise<Void> {
return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global()) {
getAuthToken(for: server).then { token -> Promise<Void> in
let url = URL(string: "\(server)/channels/\(channel)/subscribe")!
let request = TSRequest(url: url, method: "DELETE", parameters: [:]) let request = TSRequest(url: url, method: "DELETE", parameters: [:])
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ] request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
return LokiFileServerProxy(for: server).perform(request).done { result -> Void in return LokiFileServerProxy(for: server).perform(request).done { result -> Void in
print("[Loki] Left channel with ID: \(channel) on server: \(server).") print("[Loki] Deleted message with ID: \(messageID) on server: \(server).")
}
} }
}.handlingInvalidAuthTokenIfNeeded(for: server)
} }
} }
// MARK: Display Name & Profile Picture
public static func getDisplayNames(for channel: UInt64, on server: String) -> Promise<Void> { public static func getDisplayNames(for channel: UInt64, on server: String) -> Promise<Void> {
let publicChatID = "\(server).\(channel)" let publicChatID = "\(server).\(channel)"
guard let hexEncodedPublicKeys = displayNameUpdatees[publicChatID] else { return Promise.value(()) } guard let hexEncodedPublicKeys = displayNameUpdatees[publicChatID] else { return Promise.value(()) }
@ -322,12 +282,7 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
} }
} }
} }
} }.handlingInvalidAuthTokenIfNeeded(for: server)
}
@objc(isUserModerator:forChannel:onServer:)
public static func isUserModerator(_ hexEncodedPublicString: String, for channel: UInt64, on server: String) -> Bool {
return moderators[server]?[channel]?.contains(hexEncodedPublicString) ?? false
} }
@objc(setDisplayName:on:) @objc(setDisplayName:on:)
@ -337,9 +292,9 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
public static func setDisplayName(to newDisplayName: String?, on server: String) -> Promise<Void> { public static func setDisplayName(to newDisplayName: String?, on server: String) -> Promise<Void> {
print("[Loki] Updating display name on server: \(server).") print("[Loki] Updating display name on server: \(server).")
let parameters: JSON = [ "name" : (newDisplayName ?? "") ]
return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global()) { return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global()) {
getAuthToken(for: server).then { token -> Promise<Void> in getAuthToken(for: server).then { token -> Promise<Void> in
let parameters: JSON = [ "name" : (newDisplayName ?? "") ]
let url = URL(string: "\(server)/users/me")! let url = URL(string: "\(server)/users/me")!
let request = TSRequest(url: url, method: "PATCH", parameters: parameters) let request = TSRequest(url: url, method: "PATCH", parameters: parameters)
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ] request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
@ -347,7 +302,7 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
print("Couldn't update display name due to error: \(error).") print("Couldn't update display name due to error: \(error).")
throw error throw error
} }
} }.handlingInvalidAuthTokenIfNeeded(for: server)
} }
} }
@ -358,13 +313,13 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
public static func setProfilePictureURL(to url: String?, using profileKey: Data, on server: String) -> Promise<Void> { public static func setProfilePictureURL(to url: String?, using profileKey: Data, on server: String) -> Promise<Void> {
print("[Loki] Updating profile picture on server: \(server).") print("[Loki] Updating profile picture on server: \(server).")
return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global()) {
getAuthToken(for: server).then { token -> Promise<Void> in
var annotation: JSON = [ "type" : profilePictureType ] var annotation: JSON = [ "type" : profilePictureType ]
if let url = url { if let url = url {
annotation["value"] = [ "profileKey" : profileKey.base64EncodedString(), "url" : url ] annotation["value"] = [ "profileKey" : profileKey.base64EncodedString(), "url" : url ]
} }
let parameters: JSON = [ "annotations" : [ annotation ] ] let parameters: JSON = [ "annotations" : [ annotation ] ]
return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global()) {
getAuthToken(for: server).then { token -> Promise<Void> in
let url = URL(string: "\(server)/users/me")! let url = URL(string: "\(server)/users/me")!
let request = TSRequest(url: url, method: "PATCH", parameters: parameters) let request = TSRequest(url: url, method: "PATCH", parameters: parameters)
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ] request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
@ -372,18 +327,22 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
print("[Loki] Couldn't update profile picture due to error: \(error).") print("[Loki] Couldn't update profile picture due to error: \(error).")
throw error throw error
} }
} }.handlingInvalidAuthTokenIfNeeded(for: server)
} }
} }
// MARK: Joining & Leaving
@objc(getInfoForChannelWithID:onServer:) @objc(getInfoForChannelWithID:onServer:)
public static func objc_getInfo(for channel: UInt64, on server: String) -> AnyPromise { public static func objc_getInfo(for channel: UInt64, on server: String) -> AnyPromise {
return AnyPromise.from(getInfo(for: channel, on: server)) return AnyPromise.from(getInfo(for: channel, on: server))
} }
public static func getInfo(for channel: UInt64, on server: String) -> Promise<LokiPublicChatInfo> { public static func getInfo(for channel: UInt64, on server: String) -> Promise<LokiPublicChatInfo> {
return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global()) {
getAuthToken(for: server).then { token -> Promise<LokiPublicChatInfo> in
let url = URL(string: "\(server)/channels/\(channel)?include_annotations=1")! let url = URL(string: "\(server)/channels/\(channel)?include_annotations=1")!
let request = TSRequest(url: url) let request = TSRequest(url: url)
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
return LokiFileServerProxy(for: server).perform(request).map { rawResponse in return LokiFileServerProxy(for: server).perform(request).map { rawResponse in
guard let json = rawResponse as? JSON, guard let json = rawResponse as? JSON,
let data = json["data"] as? JSON, let data = json["data"] as? JSON,
@ -397,10 +356,16 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
print("[Loki] Couldn't parse info for public chat channel with ID: \(channel) on server: \(server) from: \(rawResponse).") print("[Loki] Couldn't parse info for public chat channel with ID: \(channel) on server: \(server) from: \(rawResponse).")
throw LokiDotNetAPIError.parsingFailed throw LokiDotNetAPIError.parsingFailed
} }
let storage = OWSPrimaryStorage.shared()
storage.dbReadWriteConnection.readWrite { transaction in
storage.setUserCount(memberCount, forPublicChatWithID: "\(server).\(channel)", in: transaction)
}
let publicChatInfo = LokiPublicChatInfo(displayName: displayName, profilePictureURL: profilePictureURL, memberCount: memberCount) let publicChatInfo = LokiPublicChatInfo(displayName: displayName, profilePictureURL: profilePictureURL, memberCount: memberCount)
updateOpenGroupProfileIfNeeded(for: channel, on: server, with: publicChatInfo) updateOpenGroupProfileIfNeeded(for: channel, on: server, with: publicChatInfo)
return publicChatInfo return publicChatInfo
} }
}.handlingInvalidAuthTokenIfNeeded(for: server)
}
} }
static func updateOpenGroupProfileIfNeeded(for channel: UInt64, on server: String, with info: LokiPublicChatInfo) { static func updateOpenGroupProfileIfNeeded(for channel: UInt64, on server: String, with info: LokiPublicChatInfo) {
@ -451,6 +416,33 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
} }
} }
public static func join(_ channel: UInt64, on server: String) -> Promise<Void> {
return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global()) {
getAuthToken(for: server).then { token -> Promise<Void> in
let url = URL(string: "\(server)/channels/\(channel)/subscribe")!
let request = TSRequest(url: url, method: "POST", parameters: [:])
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
return LokiFileServerProxy(for: server).perform(request).done { result -> Void in
print("[Loki] Joined channel with ID: \(channel) on server: \(server).")
}
}.handlingInvalidAuthTokenIfNeeded(for: server)
}
}
public static func leave(_ channel: UInt64, on server: String) -> Promise<Void> {
return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global()) {
getAuthToken(for: server).then { token -> Promise<Void> in
let url = URL(string: "\(server)/channels/\(channel)/subscribe")!
let request = TSRequest(url: url, method: "DELETE", parameters: [:])
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
return LokiFileServerProxy(for: server).perform(request).done { result -> Void in
print("[Loki] Left channel with ID: \(channel) on server: \(server).")
}
}.handlingInvalidAuthTokenIfNeeded(for: server)
}
}
// MARK: Reporting
@objc(reportMessageWithID:inChannel:onServer:) @objc(reportMessageWithID:inChannel:onServer:)
public static func objc_reportMessageWithID(_ messageID: UInt64, in channel: UInt64, on server: String) -> AnyPromise { public static func objc_reportMessageWithID(_ messageID: UInt64, in channel: UInt64, on server: String) -> AnyPromise {
return AnyPromise.from(reportMessageWithID(messageID, in: channel, on: server)) return AnyPromise.from(reportMessageWithID(messageID, in: channel, on: server))
@ -459,6 +451,34 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
public static func reportMessageWithID(_ messageID: UInt64, in channel: UInt64, on server: String) -> Promise<Void> { public static func reportMessageWithID(_ messageID: UInt64, in channel: UInt64, on server: String) -> Promise<Void> {
let url = URL(string: "\(server)/loki/v1/channels/\(channel)/messages/\(messageID)/report")! let url = URL(string: "\(server)/loki/v1/channels/\(channel)/messages/\(messageID)/report")!
let request = TSRequest(url: url, method: "POST", parameters: [:]) let request = TSRequest(url: url, method: "POST", parameters: [:])
// Only used for the Loki Public Chat which doesn't require authentication
return LokiFileServerProxy(for: server).perform(request).map { _ in } return LokiFileServerProxy(for: server).perform(request).map { _ in }
} }
// MARK: Moderators
public static func getModerators(for channel: UInt64, on server: String) -> Promise<Set<String>> {
return getAuthToken(for: server).then { token -> Promise<Set<String>> in
let url = URL(string: "\(server)/loki/v1/channel/\(channel)/get_moderators")!
let request = TSRequest(url: url)
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
return LokiFileServerProxy(for: server).perform(request).map { rawResponse in
guard let json = rawResponse as? JSON, let moderators = json["moderators"] as? [String] else {
print("[Loki] Couldn't parse moderators for public chat channel with ID: \(channel) on server: \(server) from: \(rawResponse).")
throw LokiDotNetAPIError.parsingFailed
}
let moderatorsAsSet = Set(moderators);
if self.moderators.keys.contains(server) {
self.moderators[server]![channel] = moderatorsAsSet
} else {
self.moderators[server] = [ channel : moderatorsAsSet ]
}
return moderatorsAsSet
}
}.handlingInvalidAuthTokenIfNeeded(for: server)
}
@objc(isUserModerator:forChannel:onServer:)
public static func isUserModerator(_ hexEncodedPublicString: String, for channel: UInt64, on server: String) -> Bool {
return moderators[server]?[channel]?.contains(hexEncodedPublicString) ?? false
}
} }

Loading…
Cancel
Save