NCContentPresenter.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. //
  2. // NCContentPresenter.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 23/12/2019.
  6. // Copyright (c) 2019 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import SwiftEntryKit
  24. import UIKit
  25. import CFNetwork
  26. import NextcloudKit
  27. class NCContentPresenter: NSObject {
  28. typealias MainFont = Font.HelveticaNeue
  29. enum Font {
  30. enum HelveticaNeue: String {
  31. case ultraLightItalic = "UltraLightItalic"
  32. case medium = "Medium"
  33. case mediumItalic = "MediumItalic"
  34. case ultraLight = "UltraLight"
  35. case italic = "Italic"
  36. case light = "Light"
  37. case thinItalic = "ThinItalic"
  38. case lightItalic = "LightItalic"
  39. case bold = "Bold"
  40. case thin = "Thin"
  41. case condensedBlack = "CondensedBlack"
  42. case condensedBold = "CondensedBold"
  43. case boldItalic = "BoldItalic"
  44. func with(size: CGFloat) -> UIFont {
  45. return UIFont(name: "HelveticaNeue-\(rawValue)", size: size)!
  46. }
  47. }
  48. }
  49. @objc enum messageType: Int {
  50. case error
  51. case success
  52. case info
  53. }
  54. // MARK: - Message
  55. func showError(error: NKError, priority: EKAttributes.Precedence.Priority = .normal) {
  56. messageNotification(
  57. "_error_",
  58. error: error,
  59. delay: NCGlobal.shared.dismissAfterSecond,
  60. type: .error,
  61. priority: priority)
  62. }
  63. func showInfo(error: NKError, priority: EKAttributes.Precedence.Priority = .normal) {
  64. messageNotification(
  65. "_info_",
  66. error: error,
  67. delay: NCGlobal.shared.dismissAfterSecond,
  68. type: .info,
  69. priority: priority)
  70. }
  71. func showInfo(title: String = "", description: String = "") {
  72. self.flatTop(title: NSLocalizedString(title, comment: ""), description: NSLocalizedString(description, comment: ""), delay: NCGlobal.shared.dismissAfterSecond, type: .info, priority: .normal)
  73. }
  74. func showWarning(error: NKError, priority: EKAttributes.Precedence.Priority = .normal) {
  75. messageNotification(
  76. "_warning_",
  77. error: error,
  78. delay: NCGlobal.shared.dismissAfterSecond,
  79. type: .info,
  80. priority: priority)
  81. }
  82. @objc func messageNotification(_ title: String, error: NKError, delay: TimeInterval, type: messageType, afterDelay: TimeInterval = 0) {
  83. messageNotification(title, error: error, delay: delay, type: type, priority: .normal, dropEnqueuedEntries: false, afterDelay: afterDelay)
  84. }
  85. func messageNotification(_ title: String, error: NKError, delay: TimeInterval, type: messageType, priority: EKAttributes.Precedence.Priority = .normal, dropEnqueuedEntries: Bool = false, afterDelay: TimeInterval = 0) {
  86. // No notification message for:
  87. if error.errorCode == NSURLErrorCancelled || error.errorCode == NCGlobal.shared.errorRequestExplicityCancelled { return } else if error == .success && type == messageType.error { return }
  88. // Hardcode change type
  89. var type = type
  90. if error.errorCode == NCGlobal.shared.errorE2EEUploadInProgress {
  91. type = .info
  92. }
  93. DispatchQueue.main.asyncAfter(deadline: .now() + afterDelay) {
  94. switch error.errorCode {
  95. case Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue):
  96. let image = UIImage(named: "InfoNetwork")?.image(color: .white, size: 20)
  97. self.noteTop(text: NSLocalizedString("_network_not_available_", comment: ""), image: image, color: .lightGray, delay: delay, priority: .max)
  98. default:
  99. var responseMessage = ""
  100. if let data = error.responseData {
  101. do {
  102. if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any],
  103. let message = json["message"] as? String {
  104. responseMessage = "\n\n" + message
  105. }
  106. } catch {
  107. print("Something went wrong")
  108. }
  109. }
  110. if error.errorDescription.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return }
  111. var description = NSLocalizedString(error.errorDescription, comment: "")
  112. description = description.replacingOccurrences(of: "\t", with: "\n")
  113. self.flatTop(title: NSLocalizedString(title, comment: ""), description: description + responseMessage, delay: delay, type: type, priority: priority, dropEnqueuedEntries: dropEnqueuedEntries)
  114. }
  115. }
  116. }
  117. func showProcessingNote() {
  118. DispatchQueue.main.async {
  119. var attributes = EKAttributes.topFloat
  120. let text = "Waiting for the goodies to arrive!"
  121. let style = EKProperty.LabelStyle(
  122. font: MainFont.light.with(size: 14),
  123. color: .white,
  124. alignment: .center,
  125. displayMode: EKAttributes.DisplayMode.inferred
  126. )
  127. let labelContent = EKProperty.LabelContent(
  128. text: text,
  129. style: style
  130. )
  131. let contentView = EKProcessingNoteMessageView(
  132. with: labelContent,
  133. activityIndicator: .medium
  134. )
  135. attributes.windowLevel = .normal
  136. attributes.entryBackground = .color(color: EKColor(self.getBackgroundColorFromType(.info)))
  137. attributes.displayDuration = .infinity
  138. attributes.positionConstraints.verticalOffset = 20
  139. attributes.positionConstraints.size = .init(width: .offset(value: 20), height: .intrinsic)
  140. attributes.positionConstraints.maxSize = .init(width: .constant(value: min(UIScreen.main.bounds.width, UIScreen.main.bounds.height)), height: .intrinsic)
  141. attributes.shadow = .active(with: .init(color: .black, opacity: 0.5, radius: 10, offset: .zero))
  142. attributes.scroll = .enabled(swipeable: true, pullbackAnimation: .jolt)
  143. attributes.popBehavior = .animated(animation: .init(translate: .init(duration: 0.2)))
  144. SwiftEntryKit.display(entry: contentView, using: attributes)
  145. }
  146. }
  147. // MARK: - Flat message
  148. private func flatTop(title: String, description: String, delay: TimeInterval, type: messageType, priority: EKAttributes.Precedence.Priority = .normal, dropEnqueuedEntries: Bool = false) {
  149. if SwiftEntryKit.isCurrentlyDisplaying(entryNamed: title + description) { return }
  150. var attributes = EKAttributes.topFloat
  151. attributes.windowLevel = .normal
  152. attributes.displayDuration = delay
  153. attributes.name = title + description
  154. attributes.entryBackground = .color(color: EKColor(getBackgroundColorFromType(type)))
  155. attributes.popBehavior = .animated(animation: .init(translate: .init(duration: 0.3), scale: .init(from: 1, to: 0.7, duration: 0.7)))
  156. attributes.shadow = .active(with: .init(color: .black, opacity: 0.5, radius: 10, offset: .zero))
  157. attributes.scroll = .enabled(swipeable: true, pullbackAnimation: .jolt)
  158. attributes.precedence = .override(priority: priority, dropEnqueuedEntries: dropEnqueuedEntries)
  159. let title = EKProperty.LabelContent(text: title, style: .init(font: MainFont.bold.with(size: 16), color: .white))
  160. let description = EKProperty.LabelContent(text: description, style: .init(font: MainFont.medium.with(size: 13), color: .white))
  161. let imageMessage = EKProperty.ImageContent(image: getImageFromType(type), size: CGSize(width: 35, height: 35))
  162. let simpleMessage = EKSimpleMessage(image: imageMessage, title: title, description: description)
  163. let notificationMessage = EKNotificationMessage(simpleMessage: simpleMessage)
  164. let contentView = EKNotificationMessageView(with: notificationMessage)
  165. DispatchQueue.main.async { SwiftEntryKit.display(entry: contentView, using: attributes) }
  166. }
  167. // MARK: -
  168. func alertAction(image: UIImage, contentModeImage: UIView.ContentMode = .scaleToFill, sizeImage: CGSize = CGSize(width: 34, height: 34), backgroundColor: UIColor, textColor: UIColor, title: String, description: String, textCancelButton: String, textOkButton: String, attributes: EKAttributes, completion: @escaping (_ identifier: String) -> Void) {
  169. var buttonAttributes: EKAttributes {
  170. var attributes = attributes
  171. attributes.hapticFeedbackType = .success
  172. attributes.displayDuration = .infinity
  173. attributes.entryBackground = .color(color: EKColor(backgroundColor))
  174. attributes.shadow = .active(with: .init(color: .black, opacity: 0.3, radius: 8))
  175. attributes.screenInteraction = .dismiss
  176. attributes.entryInteraction = .absorbTouches
  177. attributes.scroll = .enabled(swipeable: true, pullbackAnimation: .jolt)
  178. attributes.roundCorners = .all(radius: 25)
  179. attributes.entranceAnimation = .init(translate: .init(duration: 0.7, spring: .init(damping: 1, initialVelocity: 0)), scale: .init(from: 1.05, to: 1, duration: 0.4, spring: .init(damping: 1, initialVelocity: 0)))
  180. attributes.exitAnimation = .init(translate: .init(duration: 0.2))
  181. attributes.popBehavior = .animated(animation: .init(translate: .init(duration: 0.2)))
  182. attributes.positionConstraints.verticalOffset = 20
  183. attributes.positionConstraints.size = .init(width: .offset(value: 20), height: .intrinsic)
  184. attributes.positionConstraints.maxSize = .init(width: .constant(value: min(UIScreen.main.bounds.width, UIScreen.main.bounds.height)), height: .intrinsic)
  185. attributes.statusBar = .dark
  186. return attributes
  187. }
  188. let simpleMessage = EKSimpleMessage(image: EKProperty.ImageContent(image: image, size: sizeImage, contentMode: contentModeImage),
  189. title: EKProperty.LabelContent(text: NSLocalizedString(title, comment: ""), style: .init(font: MainFont.medium.with(size: 15), color: EKColor(textColor)), accessibilityIdentifier: "title"),
  190. description: EKProperty.LabelContent(text: NSLocalizedString(description, comment: ""), style: .init( font: MainFont.light.with(size: 13), color: EKColor(textColor)), accessibilityIdentifier: "description"))
  191. let cancelButton = EKProperty.ButtonContent(
  192. label: EKProperty.LabelContent(text: NSLocalizedString(textCancelButton, comment: ""), style: EKProperty.LabelStyle(font: MainFont.medium.with(size: 16), color: EKColor(textColor))),
  193. backgroundColor: .clear,
  194. highlightedBackgroundColor: EKColor(UIColor.lightGray),
  195. accessibilityIdentifier: "close") {
  196. SwiftEntryKit.dismiss()
  197. completion("close")
  198. }
  199. let okButton = EKProperty.ButtonContent(
  200. label: EKProperty.LabelContent(text: NSLocalizedString(textOkButton, comment: ""), style: EKProperty.LabelStyle(font: MainFont.medium.with(size: 16), color: EKColor(textColor))),
  201. backgroundColor: .clear,
  202. highlightedBackgroundColor: EKColor(UIColor.lightGray),
  203. displayMode: EKAttributes.DisplayMode.inferred,
  204. accessibilityIdentifier: "ok") {
  205. SwiftEntryKit.dismiss()
  206. completion("ok")
  207. }
  208. let buttonsBarContent = EKProperty.ButtonBarContent(with: cancelButton, okButton, separatorColor: EKColor(textColor), buttonHeight: 60, expandAnimatedly: true)
  209. let alertMessage = EKAlertMessage(simpleMessage: simpleMessage, imagePosition: .left, buttonBarContent: buttonsBarContent)
  210. let contentView = EKAlertMessageView(with: alertMessage)
  211. SwiftEntryKit.display(entry: contentView, using: buttonAttributes)
  212. }
  213. // MARK: - Note Message
  214. func noteTop(text: String, image: UIImage?, color: UIColor? = nil, type: messageType? = nil, delay: TimeInterval, priority: EKAttributes.Precedence.Priority = .normal, dropEnqueuedEntries: Bool = false) {
  215. if SwiftEntryKit.isCurrentlyDisplaying(entryNamed: text) { return }
  216. DispatchQueue.main.async {
  217. var attributes = EKAttributes.topNote
  218. attributes.windowLevel = .normal
  219. attributes.displayDuration = delay
  220. attributes.name = text
  221. if let color = color {
  222. attributes.entryBackground = .color(color: EKColor(color))
  223. }
  224. if let type = type {
  225. attributes.entryBackground = .color(color: EKColor(self.getBackgroundColorFromType(type)))
  226. }
  227. attributes.precedence = .override(priority: priority, dropEnqueuedEntries: dropEnqueuedEntries)
  228. let style = EKProperty.LabelStyle(font: MainFont.light.with(size: 14), color: .white, alignment: .center)
  229. let labelContent = EKProperty.LabelContent(text: text, style: style)
  230. if let image = image {
  231. let imageContent = EKProperty.ImageContent(image: image, size: CGSize(width: 17, height: 17))
  232. let contentView = EKImageNoteMessageView(with: labelContent, imageContent: imageContent)
  233. SwiftEntryKit.display(entry: contentView, using: attributes)
  234. } else {
  235. let contentView = EKNoteMessageView(with: labelContent)
  236. SwiftEntryKit.display(entry: contentView, using: attributes)
  237. }
  238. }
  239. }
  240. func dismiss(after: TimeInterval = 0) {
  241. DispatchQueue.main.asyncAfter(deadline: .now() + after) {
  242. SwiftEntryKit.dismiss()
  243. }
  244. }
  245. // MARK: - Private
  246. private func getBackgroundColorFromType(_ type: messageType) -> UIColor {
  247. switch type {
  248. case .info:
  249. return NCBrandColor.shared.customer
  250. case .error:
  251. return UIColor(red: 1, green: 0, blue: 0, alpha: 0.9)
  252. case .success:
  253. return UIColor(red: 0.588, green: 0.797, blue: 0, alpha: 0.9)
  254. default:
  255. return .white
  256. }
  257. }
  258. private func getImageFromType(_ type: messageType) -> UIImage {
  259. switch type {
  260. case .info:
  261. return UIImage(named: "iconInfo")!
  262. case .error:
  263. return UIImage(named: "iconError")!
  264. case .success:
  265. return UIImage(named: "iconSuccess")!
  266. default:
  267. return UIImage(named: "iconInfo")!
  268. }
  269. }
  270. }