QrViewController.swift 12 KB

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