ThreemaWebViewController.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2018-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. import UIKit
  21. import ThreemaFramework
  22. class ThreemaWebViewController: ThemedTableViewController {
  23. @IBOutlet weak var cameraButton: UIBarButtonItem!
  24. var entityManager: EntityManager = EntityManager()
  25. var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>?
  26. var selectedIndexPath: IndexPath?
  27. override func viewDidLoad() {
  28. super.viewDidLoad()
  29. fetchedResultsController = entityManager.entityFetcher.fetchedResultsControllerForWebClientSessions()
  30. fetchedResultsController!.delegate = self
  31. do {
  32. try fetchedResultsController!.performFetch()
  33. } catch {
  34. ErrorHandler.abortWithError(nil)
  35. }
  36. self.title = NSLocalizedString("webClientSession_title", comment: "")
  37. }
  38. override func viewWillAppear(_ animated: Bool) {
  39. super.viewWillAppear(animated)
  40. let mdmSetup = MDMSetup(setup: false)!
  41. cameraButton.isEnabled = !mdmSetup.disableWeb()
  42. cleanupWebClientSessions()
  43. cameraButton.image = BundleUtil.imageNamed("QRScan").withTint(Colors.main())
  44. cameraButton.accessibilityLabel = BundleUtil.localizedString(forKey: "scan_qr")
  45. tableView.reloadData()
  46. }
  47. // MARK: - Private functions
  48. private func presentActionSheetForSession(_ webClientSession: WebClientSession, indexPath: IndexPath) {
  49. let alert = UIAlertController(title: NSLocalizedString("webClientSession_actionSheetTitle", comment: ""), message: nil, preferredStyle: .actionSheet)
  50. if (webClientSession.active?.boolValue)! {
  51. // Stop action
  52. alert.addAction(UIAlertAction(title: NSLocalizedString("webClientSession_actionSheet_stopSession", comment: ""), style: .default) { stopAction in
  53. ValidationLogger.shared().logString("Threema Web: Disconnect webclient userStoppedSession")
  54. WCSessionManager.shared.stopSession(webClientSession)
  55. })
  56. } else {
  57. // Start action
  58. alert.addAction(UIAlertAction(title: NSLocalizedString("webClientSession_actionSheet_startSession", comment: ""), style: .default) { stopAction in
  59. ValidationLogger.shared().logString("Threema Web: User start connection")
  60. WCSessionManager.shared.connect(authToken: nil, wca: nil, webClientSession: webClientSession)
  61. })
  62. }
  63. // Rename action
  64. alert.addAction(UIAlertAction(title: NSLocalizedString("webClientSession_actionSheet_renameSession", comment: ""), style: .default) { _ in
  65. let renameAlert = UIAlertController(title: NSLocalizedString("webClientSession_sessionName", comment: ""), message: nil, preferredStyle: .alert)
  66. renameAlert.addTextField { textfield in
  67. if let sessionName = webClientSession.name {
  68. textfield.text = sessionName
  69. } else {
  70. textfield.placeholder = NSLocalizedString("webClientSession_unnamed", comment: "")
  71. }
  72. }
  73. let saveAction = UIAlertAction(title: NSLocalizedString("save", comment: ""), style: .default) { alertAction in
  74. let textField = renameAlert.textFields![0]
  75. WebClientSessionStore.shared.updateWebClientSession(session: webClientSession, sessionName: textField.text)
  76. self.tableView.deselectRow(at: indexPath, animated: true)
  77. }
  78. renameAlert.addAction(saveAction)
  79. let cancelAction = UIAlertAction(title: NSLocalizedString("cancel", comment: ""), style: .cancel) { _ in
  80. self.tableView.deselectRow(at: indexPath, animated: true)
  81. }
  82. renameAlert.addAction(cancelAction)
  83. self.present(renameAlert, animated: true)
  84. })
  85. // Delete action
  86. alert.addAction(UIAlertAction(title: NSLocalizedString("webClientSession_actionSheet_deleteSession", comment: ""), style: .destructive) { _ in
  87. self.deleteWebClientSession(webClientSession)
  88. })
  89. // Cancel action
  90. alert.addAction(UIAlertAction(title: NSLocalizedString("cancel", comment: ""), style: .cancel) { _ in
  91. self.tableView.deselectRow(at: indexPath, animated: true)
  92. })
  93. self.present(alert, animated: true)
  94. }
  95. /// Will delete all not persistent sessions where are older then 24 hours and not active
  96. private func cleanupWebClientSessions() {
  97. guard let allSessions = entityManager.entityFetcher.allWebClientSessions() as? [WebClientSession] else {
  98. return
  99. }
  100. for session in allSessions {
  101. if session.permanent?.boolValue == true {
  102. continue
  103. }
  104. if let date = session.lastConnection {
  105. if let diff = Calendar.current.dateComponents([.hour], from: date, to: Date()).hour, diff > 24 {
  106. if session.active?.boolValue == false {
  107. WebClientSessionStore.shared.deleteWebClientSession(session)
  108. }
  109. }
  110. }
  111. }
  112. }
  113. private func deleteWebClientSession(_ session: WebClientSession) {
  114. WCSessionManager.shared.stopAndDeleteSession(session)
  115. if fetchedResultsController!.fetchedObjects!.count == 0 {
  116. UserSettings.shared().threemaWeb = false
  117. }
  118. }
  119. // MARK: - Table view data source
  120. override func numberOfSections(in tableView: UITableView) -> Int {
  121. return fetchedResultsController!.sections!.count + 1
  122. }
  123. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  124. if section == 0 {
  125. return 1
  126. }
  127. return fetchedResultsController!.fetchedObjects!.count
  128. }
  129. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  130. if section == 1 {
  131. return NSLocalizedString("webClientSession_sessions_header", comment: "")
  132. }
  133. return nil
  134. }
  135. override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
  136. if section == 0 {
  137. let mdmSetup = MDMSetup(setup: false)!
  138. if mdmSetup.existsMdmKey(MDM_KEY_DISABLE_WEB) {
  139. return NSLocalizedString("disabled_by_device_policy", comment: "")
  140. } else {
  141. return NSLocalizedString("webClientSession_add_footer", comment: "")
  142. }
  143. }
  144. return nil
  145. }
  146. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  147. if indexPath.section == 0 {
  148. let cell = tableView.dequeueReusableCell(withIdentifier: "ThreemaWebSettingCell", for: indexPath) as! ThreemaWebSettingCell
  149. cell.setupCell()
  150. return cell
  151. } else {
  152. let cell = tableView.dequeueReusableCell(withIdentifier: "WebClientSessionCell", for: indexPath) as! WebClientSessionCell
  153. cell.webClientSession = fetchedResultsController!.fetchedObjects![indexPath.row] as? WebClientSession
  154. cell.viewController = self
  155. cell.setupCell()
  156. return cell
  157. }
  158. }
  159. override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
  160. if indexPath.section == 0 && indexPath.row == 0 {
  161. return nil
  162. }
  163. return indexPath
  164. }
  165. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  166. if indexPath.section == 1 {
  167. let webClientSession = fetchedResultsController!.fetchedObjects![indexPath.row] as! WebClientSession
  168. presentActionSheetForSession(webClientSession, indexPath: indexPath)
  169. }
  170. }
  171. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
  172. return indexPath.section == 1
  173. }
  174. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
  175. if editingStyle == .delete {
  176. let webClientSession = fetchedResultsController!.fetchedObjects![indexPath.row] as! WebClientSession
  177. deleteWebClientSession(webClientSession)
  178. }
  179. }
  180. }
  181. extension ThreemaWebViewController {
  182. @IBAction func scanNewSession(_ sender: Any?) {
  183. let qrController = QRScannerViewController()
  184. qrController.delegate = self
  185. qrController.title = NSLocalizedString("scan_qr", comment: "")
  186. let nav = PortraitNavigationController(rootViewController: qrController)
  187. nav.navigationBar.barStyle = .blackTranslucent
  188. nav.navigationBar.tintColor = Colors.main()
  189. nav.modalTransitionStyle = .crossDissolve
  190. self.present(nav, animated: true)
  191. }
  192. @IBAction func threemaWebSwitchChanged(_ sender: Any) {
  193. let threemaWebSwitch = sender as! UISwitch
  194. UserSettings.shared().threemaWeb = threemaWebSwitch.isOn
  195. if !threemaWebSwitch.isOn {
  196. // disconnect if there is a active session
  197. ValidationLogger.shared()?.logString("Threema Web: Disconnect webclient threemaWebOff")
  198. WCSessionManager.shared.stopAllSessions()
  199. // delete all not saved sessions if it's off
  200. WCSessionManager.shared.removeAllNotPermanentSessions()
  201. } else {
  202. if fetchedResultsController!.fetchedObjects!.count == 0 {
  203. scanNewSession(nil)
  204. }
  205. }
  206. }
  207. }
  208. extension ThreemaWebViewController: QRScannerViewControllerDelegate {
  209. func qrScannerViewController(_ controller: QRScannerViewController!, didScanResult result: String!) {
  210. let data = Data(base64Encoded: result)
  211. if UserSettings.shared().inAppVibrate {
  212. AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
  213. }
  214. if UserSettings.shared().threemaWeb == false {
  215. UserSettings.shared().threemaWeb = true
  216. }
  217. guard let qrCodeData = data else {
  218. ValidationLogger.shared().logString("Threema Web: Can't read qr code")
  219. let alert = UIAlertController(title: NSLocalizedString("webClientSession_add_wrong_qr_title", comment: ""), message: NSLocalizedString("webClientSession_add_wrong_qr_message", comment: ""), preferredStyle: .alert)
  220. alert.addAction(UIAlertAction(title: NSLocalizedString("ok", comment: ""), style: .default))
  221. self.dismiss(animated: true) {
  222. self.present(alert, animated: true)
  223. }
  224. return
  225. }
  226. func scannedCodeHandler() {
  227. handleScannedCode(data: qrCodeData) { error in
  228. if error == false {
  229. self.dismiss(animated: true, completion: nil)
  230. } else {
  231. controller.stopRunning()
  232. }
  233. }
  234. }
  235. // Don't enable Threema Web until all contacts have a non-nil feature mask
  236. let contacts = ContactStore.shared().contactsWithFeatureMaskNil()
  237. if let nilContacts = contacts, nilContacts.count > 0 {
  238. ContactStore.shared().updateFeatureMasks(forContacts: nilContacts, onCompletion: {
  239. scannedCodeHandler()
  240. }) { error in
  241. scannedCodeHandler()
  242. }
  243. } else {
  244. scannedCodeHandler()
  245. }
  246. }
  247. func qrScannerViewControllerDidCancel(_ controller: QRScannerViewController!) {
  248. self.dismiss(animated: true)
  249. }
  250. private func handleScannedCode(data: Data, completion: @escaping (_ error: Bool?) -> Void) {
  251. do {
  252. let format = String(format: ">HB32B32B32BH%is", (data.count) - 101)
  253. let a = try unpack(format, data)
  254. let allOptions = Bitfield(rawValue: a[1] as! Int)
  255. var initiatorPermanentPublicKeyArray = [UInt8]()
  256. for index in 2...33 {
  257. initiatorPermanentPublicKeyArray.append(UInt8(a[index] as! Int))
  258. }
  259. var authTokenArray = [UInt8]()
  260. for index in 34...65 {
  261. authTokenArray.append(UInt8(a[index] as! Int))
  262. }
  263. var serverPermanentPublicKeyArray = [UInt8]()
  264. for index in 66...97 {
  265. serverPermanentPublicKeyArray.append(UInt8(a[index] as! Int))
  266. }
  267. let scanController = ScanIdentityController()
  268. scanController.playSuccessSound()
  269. var session = [String: Any]()
  270. session.updateValue(a[0] as! Int, forKey: "webClientVersion")
  271. session.updateValue(allOptions.contains(.permanent) ? true : false, forKey: "permanent")
  272. session.updateValue(allOptions.contains(.selfHosted) ? true : false, forKey: "selfHosted")
  273. session.updateValue(Data(initiatorPermanentPublicKeyArray), forKey: "initiatorPermanentPublicKey")
  274. session.updateValue(Data(serverPermanentPublicKeyArray), forKey: "serverPermanentPublicKey")
  275. session.updateValue((a[98] as! Int), forKey: "saltyRTCPort")
  276. session.updateValue(a[99] as! NSString, forKey: "saltyRTCHost")
  277. if LicenseStore.requiresLicenseKey() == true {
  278. let mdmSetup = MDMSetup(setup: false)!
  279. if let webHosts = mdmSetup.webHosts() {
  280. if WCSessionManager.isWebHostAllowed(scannedHostName: session["saltyRTCHost"] as! String, whiteList: webHosts) == false {
  281. ValidationLogger.shared().logString("Threema Web: Scanned qr code host is not white listed")
  282. let topViewController = AppDelegate.shared()?.currentTopViewController()
  283. UIAlertTemplate.showAlert(owner: topViewController!, title: BundleUtil.localizedString(forKey: "webClient_scan_error_mdm_host_title"), message: BundleUtil.localizedString(forKey: "webClient_scan_error_mdm_host_message")) { (action) in
  284. self.dismiss(animated: true, completion: nil)
  285. }
  286. completion(true)
  287. return
  288. }
  289. }
  290. }
  291. ValidationLogger.shared().logString("Threema Web: Scanned qr code")
  292. let webClientSession = WebClientSessionStore.shared.addWebClientSession(dictionary: session)
  293. WCSessionManager.shared.connect(authToken: Data(authTokenArray), wca: nil, webClientSession: webClientSession)
  294. completion(false)
  295. } catch {
  296. ValidationLogger.shared().logString("Threema Web: Can't read qr code")
  297. completion(false)
  298. }
  299. }
  300. }
  301. struct Bitfield: OptionSet {
  302. let rawValue: Int
  303. static let selfHosted = Bitfield(rawValue: 1 << 0)
  304. static let permanent = Bitfield(rawValue: 1 << 1)
  305. }
  306. extension ThreemaWebViewController: NSFetchedResultsControllerDelegate {
  307. public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
  308. tableView.reloadData()
  309. }
  310. @nonobjc public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
  311. tableView.reloadData()
  312. }
  313. public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
  314. tableView.reloadData()
  315. }
  316. }