From e2814fb884da4088a36dbe18c9b92fc2b1c97d05 Mon Sep 17 00:00:00 2001 From: Niels Andriesse Date: Thu, 25 Mar 2021 16:16:08 +1100 Subject: [PATCH] Implement open group suggestion grid --- Session.xcodeproj/project.pbxproj | 4 + Session/Open Groups/JoinOpenGroupVC.swift | 121 +++++++----------- .../Open Groups/OpenGroupSuggestionGrid.swift | 117 +++++++++++++++++ .../Open Groups/V2/OpenGroupAPIV2.swift | 34 ++++- .../Open Groups/V2/OpenGroupV2.swift | 8 +- 5 files changed, 200 insertions(+), 84 deletions(-) create mode 100644 Session/Open Groups/OpenGroupSuggestionGrid.swift diff --git a/Session.xcodeproj/project.pbxproj b/Session.xcodeproj/project.pbxproj index fd0f37594..6829f69ab 100644 --- a/Session.xcodeproj/project.pbxproj +++ b/Session.xcodeproj/project.pbxproj @@ -252,6 +252,7 @@ B886B4A92398BA1500211ABE /* QRCode.swift in Sources */ = {isa = PBXBuildFile; fileRef = B886B4A82398BA1500211ABE /* QRCode.swift */; }; B88A1AC725C90A4700E6D421 /* TypingIndicatorInteraction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34B6A904218B4C90007C4606 /* TypingIndicatorInteraction.swift */; }; B88FA7B826045D100049422F /* OpenGroupAPIV2.swift in Sources */ = {isa = PBXBuildFile; fileRef = B88FA7B726045D100049422F /* OpenGroupAPIV2.swift */; }; + B88FA7F2260C3EB10049422F /* OpenGroupSuggestionGrid.swift in Sources */ = {isa = PBXBuildFile; fileRef = B88FA7F1260C3EB10049422F /* OpenGroupSuggestionGrid.swift */; }; B893063F2383961A005EAA8E /* ScanQRCodeWrapperVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = B893063E2383961A005EAA8E /* ScanQRCodeWrapperVC.swift */; }; B894D0752339EDCF00B4D94D /* NukeDataModal.swift in Sources */ = {isa = PBXBuildFile; fileRef = B894D0742339EDCF00B4D94D /* NukeDataModal.swift */; }; B897621C25D201F7004F83B2 /* ScrollToBottomButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = B897621B25D201F7004F83B2 /* ScrollToBottomButton.swift */; }; @@ -1241,6 +1242,7 @@ B886B4A62398B23E00211ABE /* QRCodeVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QRCodeVC.swift; sourceTree = ""; }; B886B4A82398BA1500211ABE /* QRCode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QRCode.swift; sourceTree = ""; }; B88FA7B726045D100049422F /* OpenGroupAPIV2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenGroupAPIV2.swift; sourceTree = ""; }; + B88FA7F1260C3EB10049422F /* OpenGroupSuggestionGrid.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenGroupSuggestionGrid.swift; sourceTree = ""; }; B893063E2383961A005EAA8E /* ScanQRCodeWrapperVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScanQRCodeWrapperVC.swift; sourceTree = ""; }; B894D0742339EDCF00B4D94D /* NukeDataModal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NukeDataModal.swift; sourceTree = ""; }; B897621B25D201F7004F83B2 /* ScrollToBottomButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScrollToBottomButton.swift; sourceTree = ""; }; @@ -2888,6 +2890,7 @@ isa = PBXGroup; children = ( B8CCF63E23975CFB0091D419 /* JoinOpenGroupVC.swift */, + B88FA7F1260C3EB10049422F /* OpenGroupSuggestionGrid.swift */, ); path = "Open Groups"; sourceTree = ""; @@ -4967,6 +4970,7 @@ B835246E25C38ABF0089A44F /* ConversationVC.swift in Sources */, B821494625D4D6FF009C0F2A /* URLModal.swift in Sources */, C374EEEB25DA3CA70073A857 /* ConversationTitleView.swift in Sources */, + B88FA7F2260C3EB10049422F /* OpenGroupSuggestionGrid.swift in Sources */, 4CA485BB2232339F004B9E7D /* PhotoCaptureViewController.swift in Sources */, 34330AA31E79686200DF2FB9 /* OWSProgressView.m in Sources */, 344825C6211390C800DB4BD8 /* OWSOrphanDataCleaner.m in Sources */, diff --git a/Session/Open Groups/JoinOpenGroupVC.swift b/Session/Open Groups/JoinOpenGroupVC.swift index a812efaf2..f469c76ca 100644 --- a/Session/Open Groups/JoinOpenGroupVC.swift +++ b/Session/Open Groups/JoinOpenGroupVC.swift @@ -20,15 +20,15 @@ final class JoinOpenGroupVC : BaseVC, UIPageViewControllerDataSource, UIPageView return TabBar(tabs: tabs) }() - private lazy var enterChatURLVC: EnterChatURLVC = { - let result = EnterChatURLVC() - result.joinPublicChatVC = self + private lazy var enterURLVC: EnterURLVC = { + let result = EnterURLVC() + result.joinOpenGroupVC = self return result }() private lazy var scanQRCodePlaceholderVC: ScanQRCodePlaceholderVC = { let result = ScanQRCodePlaceholderVC() - result.joinPublicChatVC = self + result.joinOpenGroupVC = self return result }() @@ -46,17 +46,17 @@ final class JoinOpenGroupVC : BaseVC, UIPageViewControllerDataSource, UIPageView setUpNavBarStyle() setNavBarTitle(NSLocalizedString("vc_join_public_chat_title", comment: "")) let navigationBar = navigationController!.navigationBar - // Set up navigation bar buttons + // Navigation bar buttons let closeButton = UIBarButtonItem(image: #imageLiteral(resourceName: "X"), style: .plain, target: self, action: #selector(close)) closeButton.tintColor = Colors.text navigationItem.leftBarButtonItem = closeButton - // Set up page VC + // Page VC let hasCameraAccess = (AVCaptureDevice.authorizationStatus(for: .video) == .authorized) - pages = [ enterChatURLVC, (hasCameraAccess ? scanQRCodeWrapperVC : scanQRCodePlaceholderVC) ] + pages = [ enterURLVC, (hasCameraAccess ? scanQRCodeWrapperVC : scanQRCodePlaceholderVC) ] pageVC.dataSource = self pageVC.delegate = self - pageVC.setViewControllers([ enterChatURLVC ], direction: .forward, animated: false, completion: nil) - // Set up tab bar + pageVC.setViewControllers([ enterURLVC ], direction: .forward, animated: false, completion: nil) + // Tab bar view.addSubview(tabBar) tabBar.pin(.leading, to: .leading, of: view) let tabBarInset: CGFloat @@ -67,7 +67,7 @@ final class JoinOpenGroupVC : BaseVC, UIPageViewControllerDataSource, UIPageView } tabBar.pin(.top, to: .top, of: view, withInset: tabBarInset) view.pin(.trailing, to: .trailing, of: tabBar) - // Set up page VC constraints + // Page VC constraints let pageVCView = pageVC.view! view.addSubview(pageVCView) pageVCView.pin(.leading, to: .leading, of: view) @@ -84,7 +84,7 @@ final class JoinOpenGroupVC : BaseVC, UIPageViewControllerDataSource, UIPageView height = navigationController!.view.bounds.height - navigationBar.height() - TabBar.snHeight - statusBarHeight } pageVCView.set(.height, to: height) - enterChatURLVC.constrainHeight(to: height) + enterURLVC.constrainHeight(to: height) scanQRCodePlaceholderVC.constrainHeight(to: height) } @@ -121,19 +121,18 @@ final class JoinOpenGroupVC : BaseVC, UIPageViewControllerDataSource, UIPageView } func controller(_ controller: OWSQRCodeScanningViewController, didDetectQRCodeWith string: String) { - let chatURL = string - joinPublicChatIfPossible(with: chatURL) + joinOpenGroupIfPossible(with: string) } - fileprivate func joinPublicChatIfPossible(with urlAsString: String) { + fileprivate func joinOpenGroupIfPossible(with urlAsString: String) { + + // TODO: V1 open groups + guard !isJoining else { return } - guard let url = URL(string: urlAsString), let scheme = url.scheme, scheme == "https", url.host != nil else { - return showError(title: NSLocalizedString("invalid_url", comment: ""), message: "Please check the URL you entered and try again") - } isJoining = true ModalActivityIndicatorViewController.present(fromViewController: navigationController!, canCancel: false) { [weak self] _ in Storage.shared.write { transaction in - OpenGroupManager.shared.add(with: urlAsString, using: transaction) + OpenGroupManagerV2.shared.add(room: "main", server: "https://sessionopengroup.com", publicKey: "658d29b91892a2389505596b135e76a53db6e11d613a51dbd3d0816adffb231b", using: transaction) .done(on: DispatchQueue.main) { [weak self] _ in self?.presentingViewController!.dismiss(animated: true, completion: nil) let appDelegate = UIApplication.shared.delegate as! AppDelegate @@ -141,12 +140,8 @@ final class JoinOpenGroupVC : BaseVC, UIPageViewControllerDataSource, UIPageView } .catch(on: DispatchQueue.main) { [weak self] error in self?.dismiss(animated: true, completion: nil) // Dismiss the loader - var title = "Couldn't Join" - var message = "" - if case OnionRequestAPI.Error.httpRequestFailedAtDestination(let statusCode, _) = error, statusCode == 401 || statusCode == 403 { - title = "Unauthorized" - message = "Please ask the open group operator to add you to the group." - } + let title = "Couldn't Join" + let message = error.localizedDescription self?.isJoining = false self?.showError(title: title, message: message) } @@ -162,18 +157,22 @@ final class JoinOpenGroupVC : BaseVC, UIPageViewControllerDataSource, UIPageView } } -private final class EnterChatURLVC : UIViewController { - weak var joinPublicChatVC: JoinOpenGroupVC! - private var bottomConstraint: NSLayoutConstraint! +private final class EnterURLVC : UIViewController { + weak var joinOpenGroupVC: JoinOpenGroupVC! // MARK: Components - private lazy var chatURLTextField: TextField = { + private lazy var urlTextField: TextField = { let result = TextField(placeholder: NSLocalizedString("vc_enter_chat_url_text_field_hint", comment: "")) result.keyboardType = .URL result.autocapitalizationType = .none return result }() + private lazy var suggestionGrid: OpenGroupSuggestionGrid = { + let maxWidth = UIScreen.main.bounds.width - Values.largeSpacing * 2 + return OpenGroupSuggestionGrid(maxWidth: maxWidth) + }() + // MARK: Lifecycle override func viewDidLoad() { // Remove background color @@ -181,37 +180,30 @@ private final class EnterChatURLVC : UIViewController { // Next button let nextButton = Button(style: .prominentOutline, size: .large) nextButton.setTitle(NSLocalizedString("next", comment: ""), for: UIControl.State.normal) - nextButton.addTarget(self, action: #selector(joinPublicChatIfPossible), for: UIControl.Event.touchUpInside) + nextButton.addTarget(self, action: #selector(joinOpenGroupIfPossible), for: UIControl.Event.touchUpInside) let nextButtonContainer = UIView() nextButtonContainer.addSubview(nextButton) nextButton.pin(.leading, to: .leading, of: nextButtonContainer, withInset: 80) nextButton.pin(.top, to: .top, of: nextButtonContainer) nextButtonContainer.pin(.trailing, to: .trailing, of: nextButton, withInset: 80) nextButtonContainer.pin(.bottom, to: .bottom, of: nextButton) - // Set up stack view - let stackView = UIStackView(arrangedSubviews: [ chatURLTextField, UIView.vStretchingSpacer(), nextButtonContainer ]) + // Spacers + let spacer1 = UIView.vStretchingSpacer() + let spacer2 = UIView.vStretchingSpacer() + // Stack view + let stackView = UIStackView(arrangedSubviews: [ urlTextField, spacer1, suggestionGrid, spacer2, nextButtonContainer ]) stackView.axis = .vertical stackView.alignment = .fill - stackView.layoutMargins = UIEdgeInsets(top: Values.largeSpacing, left: Values.largeSpacing, bottom: Values.largeSpacing, right: Values.largeSpacing) + stackView.layoutMargins = UIEdgeInsets(uniform: Values.largeSpacing) stackView.isLayoutMarginsRelativeArrangement = true view.addSubview(stackView) - stackView.pin(.leading, to: .leading, of: view) - stackView.pin(.top, to: .top, of: view) - view.pin(.trailing, to: .trailing, of: stackView) - bottomConstraint = view.pin(.bottom, to: .bottom, of: stackView) - // Set up width constraint + stackView.pin(to: view) + // Constraints view.set(.width, to: UIScreen.main.bounds.width) + spacer1.heightAnchor.constraint(equalTo: spacer2.heightAnchor).isActive = true // Dismiss keyboard on tap let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) view.addGestureRecognizer(tapGestureRecognizer) - // Listen to keyboard notifications - let notificationCenter = NotificationCenter.default - notificationCenter.addObserver(self, selector: #selector(handleKeyboardWillChangeFrameNotification(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) - notificationCenter.addObserver(self, selector: #selector(handleKeyboardWillHideNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) - } - - deinit { - NotificationCenter.default.removeObserver(self) } // MARK: General @@ -220,42 +212,23 @@ private final class EnterChatURLVC : UIViewController { } @objc private func dismissKeyboard() { - chatURLTextField.resignFirstResponder() - } - - // MARK: Updating - @objc private func handleKeyboardWillChangeFrameNotification(_ notification: Notification) { - guard let newHeight = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size.height else { return } - bottomConstraint.constant = newHeight - UIView.animate(withDuration: 0.25) { - self.view.layoutIfNeeded() - } - } - - @objc private func handleKeyboardWillHideNotification(_ notification: Notification) { - bottomConstraint.constant = 0 - UIView.animate(withDuration: 0.25) { - self.view.layoutIfNeeded() - } + urlTextField.resignFirstResponder() } // MARK: Interaction - @objc private func joinPublicChatIfPossible() { - var chatURL = chatURLTextField.text?.trimmingCharacters(in: .whitespaces) ?? "" - if !chatURL.lowercased().starts(with: "http") { - chatURL = "https://" + chatURL - } - joinPublicChatVC.joinPublicChatIfPossible(with: chatURL) + @objc private func joinOpenGroupIfPossible() { + let url = urlTextField.text?.trimmingCharacters(in: .whitespaces) ?? "" + joinOpenGroupVC.joinOpenGroupIfPossible(with: url) } } private final class ScanQRCodePlaceholderVC : UIViewController { - weak var joinPublicChatVC: JoinOpenGroupVC! + weak var joinOpenGroupVC: JoinOpenGroupVC! override func viewDidLoad() { // Remove background color view.backgroundColor = .clear - // Set up explanation label + // Explanation label let explanationLabel = UILabel() explanationLabel.textColor = Colors.text explanationLabel.font = .systemFont(ofSize: Values.smallFontSize) @@ -263,18 +236,18 @@ private final class ScanQRCodePlaceholderVC : UIViewController { explanationLabel.numberOfLines = 0 explanationLabel.textAlignment = .center explanationLabel.lineBreakMode = .byWordWrapping - // Set up call to action button + // Call to action button let callToActionButton = UIButton() callToActionButton.titleLabel!.font = .boldSystemFont(ofSize: Values.mediumFontSize) callToActionButton.setTitleColor(Colors.accent, for: UIControl.State.normal) callToActionButton.setTitle(NSLocalizedString("vc_scan_qr_code_grant_camera_access_button_title", comment: ""), for: UIControl.State.normal) callToActionButton.addTarget(self, action: #selector(requestCameraAccess), for: UIControl.Event.touchUpInside) - // Set up stack view + // Stack view let stackView = UIStackView(arrangedSubviews: [ explanationLabel, callToActionButton ]) stackView.axis = .vertical stackView.spacing = Values.mediumSpacing stackView.alignment = .center - // Set up constraints + // Constraints view.set(.width, to: UIScreen.main.bounds.width) view.addSubview(stackView) stackView.pin(.leading, to: .leading, of: view, withInset: Values.massiveSpacing) @@ -290,7 +263,7 @@ private final class ScanQRCodePlaceholderVC : UIViewController { @objc private func requestCameraAccess() { ows_ask(forCameraPermissions: { [weak self] hasCameraAccess in if hasCameraAccess { - self?.joinPublicChatVC.handleCameraAccessGranted() + self?.joinOpenGroupVC.handleCameraAccessGranted() } else { // Do nothing } diff --git a/Session/Open Groups/OpenGroupSuggestionGrid.swift b/Session/Open Groups/OpenGroupSuggestionGrid.swift new file mode 100644 index 000000000..c4377cb1d --- /dev/null +++ b/Session/Open Groups/OpenGroupSuggestionGrid.swift @@ -0,0 +1,117 @@ + +final class OpenGroupSuggestionGrid : UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { + private let maxWidth: CGFloat + private var rooms: [OpenGroupAPIV2.Info] = [] { didSet { reload() } } + private var heightConstraint: NSLayoutConstraint! + + // MARK: UI Components + private lazy var layout: UICollectionViewFlowLayout = { + let result = UICollectionViewFlowLayout() + result.minimumLineSpacing = OpenGroupSuggestionGrid.separatorWidth + result.minimumInteritemSpacing = OpenGroupSuggestionGrid.separatorWidth + return result + }() + + private lazy var collectionView: UICollectionView = { + let result = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) + result.register(Cell.self, forCellWithReuseIdentifier: Cell.identifier) + result.backgroundColor = Colors.unimportant + result.isScrollEnabled = false + result.dataSource = self + result.delegate = self + return result + }() + + // MARK: Settings + private static let cellHeight: CGFloat = 40 + private static let separatorWidth = 1 / UIScreen.main.scale + + // MARK: Initialization + init(maxWidth: CGFloat) { + self.maxWidth = maxWidth + super.init(frame: CGRect.zero) + initialize() + } + + override init(frame: CGRect) { + preconditionFailure("Use init(maxWidth:) instead.") + } + + required init?(coder: NSCoder) { + preconditionFailure("Use init(maxWidth:) instead.") + } + + private func initialize() { + addSubview(collectionView) + collectionView.pin(to: self) + heightConstraint = set(.height, to: 0) + attempt(maxRetryCount: 8, recoveringOn: DispatchQueue.main) { + return OpenGroupAPIV2.getAllRooms(from: "https://sessionopengroup.com").done { [weak self] rooms in + self?.rooms = rooms + } + }.retainUntilComplete() + } + + // MARK: Updating + private func reload() { + let height = OpenGroupSuggestionGrid.cellHeight * ceil(CGFloat(rooms.count) / 3) + heightConstraint.constant = height + collectionView.reloadData() + } + + // MARK: Layout + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + return CGSize(width: (maxWidth - (2 * OpenGroupSuggestionGrid.separatorWidth)) / 3, height: OpenGroupSuggestionGrid.cellHeight) + } + + // MARK: Data Source + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return min(rooms.count, 12) // Cap to a maximum of 12 (4 rows of 3) + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.identifier, for: indexPath) as! Cell + cell.room = rooms[indexPath.item] + return cell + } +} + +// MARK: Cell +extension OpenGroupSuggestionGrid { + + fileprivate final class Cell : UICollectionViewCell { + var room: OpenGroupAPIV2.Info? { didSet { update() } } + + static let identifier = "OpenGroupSuggestionGridCell" + + private lazy var label: UILabel = { + let result = UILabel() + result.textColor = Colors.text + result.font = .systemFont(ofSize: Values.smallFontSize) + return result + }() + + override init(frame: CGRect) { + super.init(frame: frame) + setUpViewHierarchy() + } + + required init?(coder: NSCoder) { + super.init(coder: coder) + setUpViewHierarchy() + } + + private func setUpViewHierarchy() { + backgroundColor = .white + addSubview(label) + label.center(in: self) + label.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor, constant: Values.smallSpacing).isActive = true + trailingAnchor.constraint(greaterThanOrEqualTo: label.trailingAnchor, constant: Values.smallSpacing).isActive = true + } + + private func update() { + guard let room = room else { return } + label.text = room.name + } + } +} diff --git a/SessionMessagingKit/Open Groups/V2/OpenGroupAPIV2.swift b/SessionMessagingKit/Open Groups/V2/OpenGroupAPIV2.swift index 45fa48ae9..8533a2dec 100644 --- a/SessionMessagingKit/Open Groups/V2/OpenGroupAPIV2.swift +++ b/SessionMessagingKit/Open Groups/V2/OpenGroupAPIV2.swift @@ -33,7 +33,7 @@ public final class OpenGroupAPIV2 : NSObject { // MARK: Request private struct Request { let verb: HTTP.Verb - let room: String + let room: String? let server: String let endpoint: String let queryParameters: [String:String] @@ -44,7 +44,7 @@ public final class OpenGroupAPIV2 : NSObject { /// this when running over Lokinet. let useOnionRouting: Bool - init(verb: HTTP.Verb, room: String, server: String, endpoint: String, queryParameters: [String:String] = [:], + init(verb: HTTP.Verb, room: String?, server: String, endpoint: String, queryParameters: [String:String] = [:], parameters: JSON = [:], headers: [String:String] = [:], isAuthRequired: Bool = true, useOnionRouting: Bool = true) { self.verb = verb self.room = room @@ -61,7 +61,12 @@ public final class OpenGroupAPIV2 : NSObject { // MARK: Info public struct Info { public let name: String - public let imageID: String + public let imageID: String? + + public init(name: String, imageID: String?) { + self.name = name + self.imageID = imageID + } } // MARK: Convenience @@ -85,8 +90,8 @@ public final class OpenGroupAPIV2 : NSObject { tsRequest.setValue(request.room, forHTTPHeaderField: "Room") if request.useOnionRouting { guard let publicKey = SNMessagingKitConfiguration.shared.storage.getOpenGroupPublicKey(for: request.server) else { return Promise(error: Error.noPublicKey) } - if request.isAuthRequired { - return getAuthToken(for: request.room, on: request.server).then(on: DispatchQueue.global(qos: .default)) { authToken -> Promise in + if request.isAuthRequired, let room = request.room { // Because auth happens on a per-room basis, we need both to make an authenticated request + return getAuthToken(for: room, on: request.server).then(on: DispatchQueue.global(qos: .default)) { authToken -> Promise in tsRequest.setValue(authToken, forHTTPHeaderField: "Authorization") return OnionRequestAPI.sendOnionRequest(tsRequest, to: request.server, using: publicKey) } @@ -276,11 +281,28 @@ public final class OpenGroupAPIV2 : NSObject { public static func getInfo(for room: String, on server: String) -> Promise { let request = Request(verb: .get, room: room, server: server, endpoint: "rooms/\(room)") return send(request).map(on: DispatchQueue.global(qos: .userInitiated)) { json in - guard let name = json["name"] as? String, let imageID = json["image_id"] as? String else { throw Error.parsingFailed } + guard let name = json["name"] as? String else { throw Error.parsingFailed } + let imageID = json["image_id"] as? String return Info(name: name, imageID: imageID) } } + public static func getAllRooms(from server: String) -> Promise<[Info]> { + let request = Request(verb: .get, room: nil, server: server, endpoint: "rooms") + return send(request).map(on: DispatchQueue.global(qos: .userInitiated)) { json in + guard let rawRooms = json["rooms"] as? [JSON] else { throw Error.parsingFailed } + let rooms: [Info] = rawRooms.compactMap { json in + guard let name = json["name"] as? String else { + SNLog("Couldn't parse room from JSON: \(json).") + return nil + } + let imageID = json["image_id"] as? String + return Info(name: name, imageID: imageID) + } + return rooms + } + } + public static func getMemberCount(for room: String, on server: String) -> Promise { let request = Request(verb: .get, room: room, server: server, endpoint: "member_count") return send(request).map(on: DispatchQueue.global(qos: .userInitiated)) { json in diff --git a/SessionMessagingKit/Open Groups/V2/OpenGroupV2.swift b/SessionMessagingKit/Open Groups/V2/OpenGroupV2.swift index d5d3390d9..2d1baa3fe 100644 --- a/SessionMessagingKit/Open Groups/V2/OpenGroupV2.swift +++ b/SessionMessagingKit/Open Groups/V2/OpenGroupV2.swift @@ -5,9 +5,9 @@ public final class OpenGroupV2 : NSObject, NSCoding { // NSObject/NSCoding confo @objc public let room: String public let id: String public let name: String - public let imageID: String + public let imageID: String? - public init(server: String, room: String, name: String, imageID: String) { + public init(server: String, room: String, name: String, imageID: String?) { self.server = server.lowercased() self.room = room self.id = "\(server).\(room)" @@ -21,7 +21,7 @@ public final class OpenGroupV2 : NSObject, NSCoding { // NSObject/NSCoding confo room = coder.decodeObject(forKey: "room") as! String self.id = "\(server).\(room)" name = coder.decodeObject(forKey: "name") as! String - imageID = coder.decodeObject(forKey: "imageID") as! String + imageID = coder.decodeObject(forKey: "imageID") as! String? super.init() } @@ -29,7 +29,7 @@ public final class OpenGroupV2 : NSObject, NSCoding { // NSObject/NSCoding confo coder.encode(server, forKey: "server") coder.encode(room, forKey: "room") coder.encode(name, forKey: "name") - coder.encode(imageID, forKey: "imageID") + if let imageID = imageID { coder.encode(imageID, forKey: "imageID") } } override public var description: String { "\(name) (Server: \(server), Room: \(room)" }