Implement open group suggestion grid

This commit is contained in:
Niels Andriesse 2021-03-25 16:16:08 +11:00
parent 6a8c717d7b
commit e2814fb884
5 changed files with 200 additions and 84 deletions

View file

@ -252,6 +252,7 @@
B886B4A92398BA1500211ABE /* QRCode.swift in Sources */ = {isa = PBXBuildFile; fileRef = B886B4A82398BA1500211ABE /* QRCode.swift */; }; B886B4A92398BA1500211ABE /* QRCode.swift in Sources */ = {isa = PBXBuildFile; fileRef = B886B4A82398BA1500211ABE /* QRCode.swift */; };
B88A1AC725C90A4700E6D421 /* TypingIndicatorInteraction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34B6A904218B4C90007C4606 /* TypingIndicatorInteraction.swift */; }; B88A1AC725C90A4700E6D421 /* TypingIndicatorInteraction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34B6A904218B4C90007C4606 /* TypingIndicatorInteraction.swift */; };
B88FA7B826045D100049422F /* OpenGroupAPIV2.swift in Sources */ = {isa = PBXBuildFile; fileRef = B88FA7B726045D100049422F /* OpenGroupAPIV2.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 */; }; B893063F2383961A005EAA8E /* ScanQRCodeWrapperVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = B893063E2383961A005EAA8E /* ScanQRCodeWrapperVC.swift */; };
B894D0752339EDCF00B4D94D /* NukeDataModal.swift in Sources */ = {isa = PBXBuildFile; fileRef = B894D0742339EDCF00B4D94D /* NukeDataModal.swift */; }; B894D0752339EDCF00B4D94D /* NukeDataModal.swift in Sources */ = {isa = PBXBuildFile; fileRef = B894D0742339EDCF00B4D94D /* NukeDataModal.swift */; };
B897621C25D201F7004F83B2 /* ScrollToBottomButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = B897621B25D201F7004F83B2 /* ScrollToBottomButton.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 = "<group>"; }; B886B4A62398B23E00211ABE /* QRCodeVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QRCodeVC.swift; sourceTree = "<group>"; };
B886B4A82398BA1500211ABE /* QRCode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QRCode.swift; sourceTree = "<group>"; }; B886B4A82398BA1500211ABE /* QRCode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QRCode.swift; sourceTree = "<group>"; };
B88FA7B726045D100049422F /* OpenGroupAPIV2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenGroupAPIV2.swift; sourceTree = "<group>"; }; B88FA7B726045D100049422F /* OpenGroupAPIV2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenGroupAPIV2.swift; sourceTree = "<group>"; };
B88FA7F1260C3EB10049422F /* OpenGroupSuggestionGrid.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenGroupSuggestionGrid.swift; sourceTree = "<group>"; };
B893063E2383961A005EAA8E /* ScanQRCodeWrapperVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScanQRCodeWrapperVC.swift; sourceTree = "<group>"; }; B893063E2383961A005EAA8E /* ScanQRCodeWrapperVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScanQRCodeWrapperVC.swift; sourceTree = "<group>"; };
B894D0742339EDCF00B4D94D /* NukeDataModal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NukeDataModal.swift; sourceTree = "<group>"; }; B894D0742339EDCF00B4D94D /* NukeDataModal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NukeDataModal.swift; sourceTree = "<group>"; };
B897621B25D201F7004F83B2 /* ScrollToBottomButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScrollToBottomButton.swift; sourceTree = "<group>"; }; B897621B25D201F7004F83B2 /* ScrollToBottomButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScrollToBottomButton.swift; sourceTree = "<group>"; };
@ -2888,6 +2890,7 @@
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
B8CCF63E23975CFB0091D419 /* JoinOpenGroupVC.swift */, B8CCF63E23975CFB0091D419 /* JoinOpenGroupVC.swift */,
B88FA7F1260C3EB10049422F /* OpenGroupSuggestionGrid.swift */,
); );
path = "Open Groups"; path = "Open Groups";
sourceTree = "<group>"; sourceTree = "<group>";
@ -4967,6 +4970,7 @@
B835246E25C38ABF0089A44F /* ConversationVC.swift in Sources */, B835246E25C38ABF0089A44F /* ConversationVC.swift in Sources */,
B821494625D4D6FF009C0F2A /* URLModal.swift in Sources */, B821494625D4D6FF009C0F2A /* URLModal.swift in Sources */,
C374EEEB25DA3CA70073A857 /* ConversationTitleView.swift in Sources */, C374EEEB25DA3CA70073A857 /* ConversationTitleView.swift in Sources */,
B88FA7F2260C3EB10049422F /* OpenGroupSuggestionGrid.swift in Sources */,
4CA485BB2232339F004B9E7D /* PhotoCaptureViewController.swift in Sources */, 4CA485BB2232339F004B9E7D /* PhotoCaptureViewController.swift in Sources */,
34330AA31E79686200DF2FB9 /* OWSProgressView.m in Sources */, 34330AA31E79686200DF2FB9 /* OWSProgressView.m in Sources */,
344825C6211390C800DB4BD8 /* OWSOrphanDataCleaner.m in Sources */, 344825C6211390C800DB4BD8 /* OWSOrphanDataCleaner.m in Sources */,

View file

@ -20,15 +20,15 @@ final class JoinOpenGroupVC : BaseVC, UIPageViewControllerDataSource, UIPageView
return TabBar(tabs: tabs) return TabBar(tabs: tabs)
}() }()
private lazy var enterChatURLVC: EnterChatURLVC = { private lazy var enterURLVC: EnterURLVC = {
let result = EnterChatURLVC() let result = EnterURLVC()
result.joinPublicChatVC = self result.joinOpenGroupVC = self
return result return result
}() }()
private lazy var scanQRCodePlaceholderVC: ScanQRCodePlaceholderVC = { private lazy var scanQRCodePlaceholderVC: ScanQRCodePlaceholderVC = {
let result = ScanQRCodePlaceholderVC() let result = ScanQRCodePlaceholderVC()
result.joinPublicChatVC = self result.joinOpenGroupVC = self
return result return result
}() }()
@ -46,17 +46,17 @@ final class JoinOpenGroupVC : BaseVC, UIPageViewControllerDataSource, UIPageView
setUpNavBarStyle() setUpNavBarStyle()
setNavBarTitle(NSLocalizedString("vc_join_public_chat_title", comment: "")) setNavBarTitle(NSLocalizedString("vc_join_public_chat_title", comment: ""))
let navigationBar = navigationController!.navigationBar 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)) let closeButton = UIBarButtonItem(image: #imageLiteral(resourceName: "X"), style: .plain, target: self, action: #selector(close))
closeButton.tintColor = Colors.text closeButton.tintColor = Colors.text
navigationItem.leftBarButtonItem = closeButton navigationItem.leftBarButtonItem = closeButton
// Set up page VC // Page VC
let hasCameraAccess = (AVCaptureDevice.authorizationStatus(for: .video) == .authorized) let hasCameraAccess = (AVCaptureDevice.authorizationStatus(for: .video) == .authorized)
pages = [ enterChatURLVC, (hasCameraAccess ? scanQRCodeWrapperVC : scanQRCodePlaceholderVC) ] pages = [ enterURLVC, (hasCameraAccess ? scanQRCodeWrapperVC : scanQRCodePlaceholderVC) ]
pageVC.dataSource = self pageVC.dataSource = self
pageVC.delegate = self pageVC.delegate = self
pageVC.setViewControllers([ enterChatURLVC ], direction: .forward, animated: false, completion: nil) pageVC.setViewControllers([ enterURLVC ], direction: .forward, animated: false, completion: nil)
// Set up tab bar // Tab bar
view.addSubview(tabBar) view.addSubview(tabBar)
tabBar.pin(.leading, to: .leading, of: view) tabBar.pin(.leading, to: .leading, of: view)
let tabBarInset: CGFloat let tabBarInset: CGFloat
@ -67,7 +67,7 @@ final class JoinOpenGroupVC : BaseVC, UIPageViewControllerDataSource, UIPageView
} }
tabBar.pin(.top, to: .top, of: view, withInset: tabBarInset) tabBar.pin(.top, to: .top, of: view, withInset: tabBarInset)
view.pin(.trailing, to: .trailing, of: tabBar) view.pin(.trailing, to: .trailing, of: tabBar)
// Set up page VC constraints // Page VC constraints
let pageVCView = pageVC.view! let pageVCView = pageVC.view!
view.addSubview(pageVCView) view.addSubview(pageVCView)
pageVCView.pin(.leading, to: .leading, of: view) 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 height = navigationController!.view.bounds.height - navigationBar.height() - TabBar.snHeight - statusBarHeight
} }
pageVCView.set(.height, to: height) pageVCView.set(.height, to: height)
enterChatURLVC.constrainHeight(to: height) enterURLVC.constrainHeight(to: height)
scanQRCodePlaceholderVC.constrainHeight(to: height) scanQRCodePlaceholderVC.constrainHeight(to: height)
} }
@ -121,19 +121,18 @@ final class JoinOpenGroupVC : BaseVC, UIPageViewControllerDataSource, UIPageView
} }
func controller(_ controller: OWSQRCodeScanningViewController, didDetectQRCodeWith string: String) { func controller(_ controller: OWSQRCodeScanningViewController, didDetectQRCodeWith string: String) {
let chatURL = string joinOpenGroupIfPossible(with: string)
joinPublicChatIfPossible(with: chatURL)
} }
fileprivate func joinPublicChatIfPossible(with urlAsString: String) { fileprivate func joinOpenGroupIfPossible(with urlAsString: String) {
// TODO: V1 open groups
guard !isJoining else { return } 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 isJoining = true
ModalActivityIndicatorViewController.present(fromViewController: navigationController!, canCancel: false) { [weak self] _ in ModalActivityIndicatorViewController.present(fromViewController: navigationController!, canCancel: false) { [weak self] _ in
Storage.shared.write { transaction 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 .done(on: DispatchQueue.main) { [weak self] _ in
self?.presentingViewController!.dismiss(animated: true, completion: nil) self?.presentingViewController!.dismiss(animated: true, completion: nil)
let appDelegate = UIApplication.shared.delegate as! AppDelegate 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 .catch(on: DispatchQueue.main) { [weak self] error in
self?.dismiss(animated: true, completion: nil) // Dismiss the loader self?.dismiss(animated: true, completion: nil) // Dismiss the loader
var title = "Couldn't Join" let title = "Couldn't Join"
var message = "" let message = error.localizedDescription
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."
}
self?.isJoining = false self?.isJoining = false
self?.showError(title: title, message: message) self?.showError(title: title, message: message)
} }
@ -162,18 +157,22 @@ final class JoinOpenGroupVC : BaseVC, UIPageViewControllerDataSource, UIPageView
} }
} }
private final class EnterChatURLVC : UIViewController { private final class EnterURLVC : UIViewController {
weak var joinPublicChatVC: JoinOpenGroupVC! weak var joinOpenGroupVC: JoinOpenGroupVC!
private var bottomConstraint: NSLayoutConstraint!
// MARK: Components // 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: "")) let result = TextField(placeholder: NSLocalizedString("vc_enter_chat_url_text_field_hint", comment: ""))
result.keyboardType = .URL result.keyboardType = .URL
result.autocapitalizationType = .none result.autocapitalizationType = .none
return result return result
}() }()
private lazy var suggestionGrid: OpenGroupSuggestionGrid = {
let maxWidth = UIScreen.main.bounds.width - Values.largeSpacing * 2
return OpenGroupSuggestionGrid(maxWidth: maxWidth)
}()
// MARK: Lifecycle // MARK: Lifecycle
override func viewDidLoad() { override func viewDidLoad() {
// Remove background color // Remove background color
@ -181,37 +180,30 @@ private final class EnterChatURLVC : UIViewController {
// Next button // Next button
let nextButton = Button(style: .prominentOutline, size: .large) let nextButton = Button(style: .prominentOutline, size: .large)
nextButton.setTitle(NSLocalizedString("next", comment: ""), for: UIControl.State.normal) 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() let nextButtonContainer = UIView()
nextButtonContainer.addSubview(nextButton) nextButtonContainer.addSubview(nextButton)
nextButton.pin(.leading, to: .leading, of: nextButtonContainer, withInset: 80) nextButton.pin(.leading, to: .leading, of: nextButtonContainer, withInset: 80)
nextButton.pin(.top, to: .top, of: nextButtonContainer) nextButton.pin(.top, to: .top, of: nextButtonContainer)
nextButtonContainer.pin(.trailing, to: .trailing, of: nextButton, withInset: 80) nextButtonContainer.pin(.trailing, to: .trailing, of: nextButton, withInset: 80)
nextButtonContainer.pin(.bottom, to: .bottom, of: nextButton) nextButtonContainer.pin(.bottom, to: .bottom, of: nextButton)
// Set up stack view // Spacers
let stackView = UIStackView(arrangedSubviews: [ chatURLTextField, UIView.vStretchingSpacer(), nextButtonContainer ]) let spacer1 = UIView.vStretchingSpacer()
let spacer2 = UIView.vStretchingSpacer()
// Stack view
let stackView = UIStackView(arrangedSubviews: [ urlTextField, spacer1, suggestionGrid, spacer2, nextButtonContainer ])
stackView.axis = .vertical stackView.axis = .vertical
stackView.alignment = .fill 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 stackView.isLayoutMarginsRelativeArrangement = true
view.addSubview(stackView) view.addSubview(stackView)
stackView.pin(.leading, to: .leading, of: view) stackView.pin(to: view)
stackView.pin(.top, to: .top, of: view) // Constraints
view.pin(.trailing, to: .trailing, of: stackView)
bottomConstraint = view.pin(.bottom, to: .bottom, of: stackView)
// Set up width constraint
view.set(.width, to: UIScreen.main.bounds.width) view.set(.width, to: UIScreen.main.bounds.width)
spacer1.heightAnchor.constraint(equalTo: spacer2.heightAnchor).isActive = true
// Dismiss keyboard on tap // Dismiss keyboard on tap
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tapGestureRecognizer) 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 // MARK: General
@ -220,42 +212,23 @@ private final class EnterChatURLVC : UIViewController {
} }
@objc private func dismissKeyboard() { @objc private func dismissKeyboard() {
chatURLTextField.resignFirstResponder() urlTextField.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()
}
} }
// MARK: Interaction // MARK: Interaction
@objc private func joinPublicChatIfPossible() { @objc private func joinOpenGroupIfPossible() {
var chatURL = chatURLTextField.text?.trimmingCharacters(in: .whitespaces) ?? "" let url = urlTextField.text?.trimmingCharacters(in: .whitespaces) ?? ""
if !chatURL.lowercased().starts(with: "http") { joinOpenGroupVC.joinOpenGroupIfPossible(with: url)
chatURL = "https://" + chatURL
}
joinPublicChatVC.joinPublicChatIfPossible(with: chatURL)
} }
} }
private final class ScanQRCodePlaceholderVC : UIViewController { private final class ScanQRCodePlaceholderVC : UIViewController {
weak var joinPublicChatVC: JoinOpenGroupVC! weak var joinOpenGroupVC: JoinOpenGroupVC!
override func viewDidLoad() { override func viewDidLoad() {
// Remove background color // Remove background color
view.backgroundColor = .clear view.backgroundColor = .clear
// Set up explanation label // Explanation label
let explanationLabel = UILabel() let explanationLabel = UILabel()
explanationLabel.textColor = Colors.text explanationLabel.textColor = Colors.text
explanationLabel.font = .systemFont(ofSize: Values.smallFontSize) explanationLabel.font = .systemFont(ofSize: Values.smallFontSize)
@ -263,18 +236,18 @@ private final class ScanQRCodePlaceholderVC : UIViewController {
explanationLabel.numberOfLines = 0 explanationLabel.numberOfLines = 0
explanationLabel.textAlignment = .center explanationLabel.textAlignment = .center
explanationLabel.lineBreakMode = .byWordWrapping explanationLabel.lineBreakMode = .byWordWrapping
// Set up call to action button // Call to action button
let callToActionButton = UIButton() let callToActionButton = UIButton()
callToActionButton.titleLabel!.font = .boldSystemFont(ofSize: Values.mediumFontSize) callToActionButton.titleLabel!.font = .boldSystemFont(ofSize: Values.mediumFontSize)
callToActionButton.setTitleColor(Colors.accent, for: UIControl.State.normal) 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.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) callToActionButton.addTarget(self, action: #selector(requestCameraAccess), for: UIControl.Event.touchUpInside)
// Set up stack view // Stack view
let stackView = UIStackView(arrangedSubviews: [ explanationLabel, callToActionButton ]) let stackView = UIStackView(arrangedSubviews: [ explanationLabel, callToActionButton ])
stackView.axis = .vertical stackView.axis = .vertical
stackView.spacing = Values.mediumSpacing stackView.spacing = Values.mediumSpacing
stackView.alignment = .center stackView.alignment = .center
// Set up constraints // Constraints
view.set(.width, to: UIScreen.main.bounds.width) view.set(.width, to: UIScreen.main.bounds.width)
view.addSubview(stackView) view.addSubview(stackView)
stackView.pin(.leading, to: .leading, of: view, withInset: Values.massiveSpacing) stackView.pin(.leading, to: .leading, of: view, withInset: Values.massiveSpacing)
@ -290,7 +263,7 @@ private final class ScanQRCodePlaceholderVC : UIViewController {
@objc private func requestCameraAccess() { @objc private func requestCameraAccess() {
ows_ask(forCameraPermissions: { [weak self] hasCameraAccess in ows_ask(forCameraPermissions: { [weak self] hasCameraAccess in
if hasCameraAccess { if hasCameraAccess {
self?.joinPublicChatVC.handleCameraAccessGranted() self?.joinOpenGroupVC.handleCameraAccessGranted()
} else { } else {
// Do nothing // Do nothing
} }

View file

@ -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
}
}
}

View file

@ -33,7 +33,7 @@ public final class OpenGroupAPIV2 : NSObject {
// MARK: Request // MARK: Request
private struct Request { private struct Request {
let verb: HTTP.Verb let verb: HTTP.Verb
let room: String let room: String?
let server: String let server: String
let endpoint: String let endpoint: String
let queryParameters: [String:String] let queryParameters: [String:String]
@ -44,7 +44,7 @@ public final class OpenGroupAPIV2 : NSObject {
/// this when running over Lokinet. /// this when running over Lokinet.
let useOnionRouting: Bool 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) { parameters: JSON = [:], headers: [String:String] = [:], isAuthRequired: Bool = true, useOnionRouting: Bool = true) {
self.verb = verb self.verb = verb
self.room = room self.room = room
@ -61,7 +61,12 @@ public final class OpenGroupAPIV2 : NSObject {
// MARK: Info // MARK: Info
public struct Info { public struct Info {
public let name: String 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 // MARK: Convenience
@ -85,8 +90,8 @@ public final class OpenGroupAPIV2 : NSObject {
tsRequest.setValue(request.room, forHTTPHeaderField: "Room") tsRequest.setValue(request.room, forHTTPHeaderField: "Room")
if request.useOnionRouting { if request.useOnionRouting {
guard let publicKey = SNMessagingKitConfiguration.shared.storage.getOpenGroupPublicKey(for: request.server) else { return Promise(error: Error.noPublicKey) } guard let publicKey = SNMessagingKitConfiguration.shared.storage.getOpenGroupPublicKey(for: request.server) else { return Promise(error: Error.noPublicKey) }
if request.isAuthRequired { 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: request.room, on: request.server).then(on: DispatchQueue.global(qos: .default)) { authToken -> Promise<JSON> in return getAuthToken(for: room, on: request.server).then(on: DispatchQueue.global(qos: .default)) { authToken -> Promise<JSON> in
tsRequest.setValue(authToken, forHTTPHeaderField: "Authorization") tsRequest.setValue(authToken, forHTTPHeaderField: "Authorization")
return OnionRequestAPI.sendOnionRequest(tsRequest, to: request.server, using: publicKey) 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<Info> { public static func getInfo(for room: String, on server: String) -> Promise<Info> {
let request = Request(verb: .get, room: room, server: server, endpoint: "rooms/\(room)") let request = Request(verb: .get, room: room, server: server, endpoint: "rooms/\(room)")
return send(request).map(on: DispatchQueue.global(qos: .userInitiated)) { json in 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) 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<UInt> { public static func getMemberCount(for room: String, on server: String) -> Promise<UInt> {
let request = Request(verb: .get, room: room, server: server, endpoint: "member_count") let request = Request(verb: .get, room: room, server: server, endpoint: "member_count")
return send(request).map(on: DispatchQueue.global(qos: .userInitiated)) { json in return send(request).map(on: DispatchQueue.global(qos: .userInitiated)) { json in

View file

@ -5,9 +5,9 @@ public final class OpenGroupV2 : NSObject, NSCoding { // NSObject/NSCoding confo
@objc public let room: String @objc public let room: String
public let id: String public let id: String
public let name: 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.server = server.lowercased()
self.room = room self.room = room
self.id = "\(server).\(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 room = coder.decodeObject(forKey: "room") as! String
self.id = "\(server).\(room)" self.id = "\(server).\(room)"
name = coder.decodeObject(forKey: "name") as! String name = coder.decodeObject(forKey: "name") as! String
imageID = coder.decodeObject(forKey: "imageID") as! String imageID = coder.decodeObject(forKey: "imageID") as! String?
super.init() super.init()
} }
@ -29,7 +29,7 @@ public final class OpenGroupV2 : NSObject, NSCoding { // NSObject/NSCoding confo
coder.encode(server, forKey: "server") coder.encode(server, forKey: "server")
coder.encode(room, forKey: "room") coder.encode(room, forKey: "room")
coder.encode(name, forKey: "name") 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)" } override public var description: String { "\(name) (Server: \(server), Room: \(room)" }