QrViewController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import Foundation
  2. import UIKit
  3. class QrViewController: UITableViewController, QrCodeReaderDelegate {
  4. private let rowContact = 0
  5. private let rowQRCode = 1
  6. private let rowScanQR = 2
  7. weak var coordinator: QrViewCoordinator?
  8. let qrCodeReaderController = QrCodeReaderController()
  9. var secureJoinObserver: Any?
  10. var dcContext: DcContext
  11. var contact: DcContact? {
  12. // This is nil if we do not have an account setup yet
  13. if !DcConfig.configured {
  14. return nil
  15. }
  16. return DcContact(id: Int(DC_CONTACT_ID_SELF))
  17. }
  18. init(dcContext: DcContext) {
  19. self.dcContext = dcContext
  20. super.init(nibName: nil, bundle: nil)
  21. }
  22. required init?(coder _: NSCoder) {
  23. fatalError("init(coder:) has not been implemented")
  24. }
  25. override func viewDidLoad() {
  26. super.viewDidLoad()
  27. title = String.localized("qr_code_title")
  28. qrCodeReaderController.delegate = self
  29. tableView.separatorStyle = .none
  30. }
  31. override func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  32. let row = indexPath.row
  33. switch row {
  34. case rowContact:
  35. return createContactCell()
  36. case rowQRCode:
  37. return createQRCodeCell()
  38. case rowScanQR:
  39. return createQRCodeScanCell()
  40. default:
  41. return UITableViewCell(style: .default, reuseIdentifier: nil)
  42. }
  43. }
  44. override func numberOfSections(in _: UITableView) -> Int {
  45. return 1
  46. }
  47. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  48. return 3
  49. }
  50. override func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  51. switch indexPath.row {
  52. case rowContact:
  53. return 72
  54. case rowQRCode:
  55. return 225
  56. case rowScanQR:
  57. return 40
  58. default:
  59. return 10
  60. }
  61. }
  62. private lazy var progressAlert: UIAlertController = {
  63. let alert = UIAlertController(title: String.localized("one_moment"), message: "TESTMESSAGE", preferredStyle: .alert)
  64. let rect = CGRect(x: 0, y: 0, width: 25, height: 25)
  65. let activityIndicator = UIActivityIndicatorView(frame: rect)
  66. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  67. activityIndicator.style = .gray
  68. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .default, handler: { _ in
  69. self.dcContext.stopOngoingProcess()
  70. self.dismiss(animated: true, completion: nil)
  71. }))
  72. return alert
  73. }()
  74. private func showProgressAlert() {
  75. self.present(self.progressAlert, animated: true, completion: {
  76. let rect = CGRect(x: 10, y: 10, width: 20, height: 20)
  77. let progressView = UIActivityIndicatorView(frame: rect)
  78. progressView.tintColor = .blue
  79. progressView.startAnimating()
  80. self.progressAlert.view.addSubview(progressView)
  81. })
  82. }
  83. private func showErrorAlert(error: String) {
  84. let alert = UIAlertController(title: String.localized("error"), message: error, preferredStyle: .alert)
  85. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  86. alert.dismiss(animated: true, completion: nil)
  87. }))
  88. }
  89. private func addSecureJoinProgressListener() {
  90. let nc = NotificationCenter.default
  91. secureJoinObserver = nc.addObserver(
  92. forName: dcNotificationSecureJoinerProgress,
  93. object: nil,
  94. queue: nil
  95. ) { notification in
  96. print("secure join: ", notification)
  97. if let ui = notification.userInfo {
  98. if ui["progress"] as? Int == 400 {
  99. if let contactId = ui["contact_id"] as? Int {
  100. self.progressAlert.message = String.localizedStringWithFormat(
  101. String.localized("qrscan_x_verified_introduce_myself"),
  102. DcContact(id: contactId).nameNAddr)
  103. }
  104. }
  105. }
  106. }
  107. }
  108. private func removeSecureJoinProgressListener() {
  109. let nc = NotificationCenter.default
  110. if let secureJoinObserver = self.secureJoinObserver {
  111. nc.removeObserver(secureJoinObserver)
  112. }
  113. }
  114. //QRCodeDelegate
  115. func handleQrCode(_ code: String) {
  116. //remove qr code scanner view
  117. if let ctrl = navigationController {
  118. ctrl.viewControllers.removeLast()
  119. }
  120. let qrParsed: DcLot = self.dcContext.checkQR(qrCode: code)
  121. let state = Int32(qrParsed.state)
  122. switch state {
  123. case DC_QR_ASK_VERIFYCONTACT:
  124. let nameAndAddress = DcContact(id: qrParsed.id).nameNAddr
  125. joinSecureJoin(alertMessage: String.localizedStringWithFormat(String.localized("qrscan_ask_fingerprint_ask_oob"), nameAndAddress), code: code)
  126. case DC_QR_ASK_VERIFYGROUP:
  127. if let group = qrParsed.text1?.replacingOccurrences(of: "+", with: " ") {
  128. joinSecureJoin(alertMessage: String.localizedStringWithFormat(String.localized("qrscan_ask_join_group"), group), code: code)
  129. }
  130. default:
  131. let alertMessage = "QR code scanning for type " + String(state) + " is not yet implemented."
  132. let alert = UIAlertController(title: alertMessage,
  133. message: nil,
  134. preferredStyle: .alert)
  135. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  136. }
  137. }
  138. private func joinSecureJoin(alertMessage: String, code: String) {
  139. let alert = UIAlertController(title: alertMessage,
  140. message: nil,
  141. preferredStyle: .alert)
  142. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .default, handler: nil))
  143. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  144. alert.dismiss(animated: true, completion: nil)
  145. self.showProgressAlert()
  146. // execute blocking secure join in background
  147. DispatchQueue.global(qos: .background).async {
  148. self.addSecureJoinProgressListener()
  149. AppDelegate.lastErrorString = nil
  150. let chatId = self.dcContext.joinSecurejoin(qrCode: code)
  151. let errorString = AppDelegate.lastErrorString
  152. self.removeSecureJoinProgressListener()
  153. DispatchQueue.main.async {
  154. self.progressAlert.dismiss(animated: true, completion: nil)
  155. if chatId != 0 {
  156. self.coordinator?.showChat(chatId: chatId)
  157. } else if errorString != nil {
  158. self.showErrorAlert(error: errorString!)
  159. }
  160. }
  161. }
  162. }))
  163. present(alert, animated: true, completion: nil)
  164. }
  165. private func createContactCell() -> UITableViewCell {
  166. let cell = ContactCell(style: .default, reuseIdentifier: "contactCell")
  167. let bg = UIColor(red: 248 / 255, green: 248 / 255, blue: 255 / 255, alpha: 1.0)
  168. if let contact = self.contact {
  169. let name = DcConfig.displayname ?? contact.displayName
  170. cell.backgroundColor = bg
  171. cell.nameLabel.text = name
  172. cell.emailLabel.text = contact.email
  173. cell.darkMode = false
  174. if let img = contact.profileImage {
  175. cell.setImage(img)
  176. } else {
  177. cell.setBackupImage(name: name, color: contact.color)
  178. }
  179. } else {
  180. cell.nameLabel.text = String.localized("no_account_setup")
  181. }
  182. return cell
  183. }
  184. private func createQRCodeCell() -> UITableViewCell {
  185. let cell = UITableViewCell(style: .default, reuseIdentifier: "qrCodeCell")
  186. let qrCode = createQRCodeView()
  187. let infolabel = createInfoLabel()
  188. cell.contentView.addSubview(qrCode)
  189. cell.contentView.addSubview(infolabel)
  190. cell.selectionStyle = .none
  191. let qrCodeConstraints = [qrCode.constraintAlignTopTo(cell.contentView, paddingTop: 25),
  192. qrCode.constraintCenterXTo(cell.contentView)]
  193. let infoLabelConstraints = [infolabel.constraintToBottomOf(qrCode, paddingTop: 25),
  194. infolabel.constraintAlignLeadingTo(cell.contentView, paddingLeading: 8),
  195. infolabel.constraintAlignTrailingTo(cell.contentView, paddingTrailing: 8)]
  196. cell.contentView.addConstraints(qrCodeConstraints)
  197. cell.contentView.addConstraints(infoLabelConstraints)
  198. return cell
  199. }
  200. private func createQRCodeScanCell() -> UITableViewCell {
  201. let cell = UITableViewCell(style: .default, reuseIdentifier: "scanQR")
  202. let scanButton = createQRCodeScannerButton()
  203. cell.contentView.addSubview(scanButton)
  204. cell.selectionStyle = .none
  205. let scanButtonConstraints = [scanButton.constraintCenterXTo(cell.contentView),
  206. scanButton.constraintCenterYTo(cell.contentView)]
  207. cell.contentView.addConstraints(scanButtonConstraints)
  208. return cell
  209. }
  210. private func createInfoLabel() -> UIView {
  211. let label = UILabel.init()
  212. label.translatesAutoresizingMaskIntoConstraints = false
  213. if let contact = contact {
  214. label.text = String.localizedStringWithFormat(String.localized("qrshow_join_contact_hint"), contact.email)
  215. }
  216. label.lineBreakMode = .byWordWrapping
  217. label.numberOfLines = 0
  218. label.textAlignment = .center
  219. label.font = UIFont.systemFont(ofSize: 14)
  220. return label
  221. }
  222. private func createQRCodeScannerButton() -> UIView {
  223. let btn = UIButton.init(type: UIButton.ButtonType.system)
  224. btn.translatesAutoresizingMaskIntoConstraints = false
  225. btn.setTitle(String.localized("qrscan_title"), for: .normal)
  226. btn.addTarget(self, action: #selector(self.openQRCodeScanner), for: .touchUpInside)
  227. return btn
  228. }
  229. @objc func openQRCodeScanner() {
  230. if let ctrl = navigationController {
  231. ctrl.pushViewController(qrCodeReaderController, animated: true)
  232. }
  233. }
  234. private func createQRCodeView() -> UIView {
  235. let width: CGFloat = 130
  236. let frame = CGRect(origin: .zero, size: .init(width: width, height: width))
  237. let imageView = QRCodeView(frame: frame)
  238. if let qrCode = dcContext.getSecurejoinQr(chatId: 0) {
  239. imageView.generateCode(
  240. qrCode,
  241. foregroundColor: .darkText,
  242. backgroundColor: .white
  243. )
  244. }
  245. imageView.translatesAutoresizingMaskIntoConstraints = false
  246. imageView.widthAnchor.constraint(equalToConstant: width).isActive = true
  247. imageView.heightAnchor.constraint(equalToConstant: width).isActive = true
  248. return imageView
  249. }
  250. func displayNewChat(contactId: Int) {
  251. let chatId = dc_create_chat_by_contact_id(mailboxPointer, UInt32(contactId))
  252. let chatVC = ChatViewController(dcContext: dcContext, chatId: Int(chatId))
  253. chatVC.hidesBottomBarWhenPushed = true
  254. navigationController?.pushViewController(chatVC, animated: true)
  255. }
  256. }