NCContentPresenter.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. @objc static let shared: NCContentPresenter = {
  29. let instance = NCContentPresenter()
  30. return instance
  31. }()
  32. typealias MainFont = Font.HelveticaNeue
  33. enum Font {
  34. enum HelveticaNeue: String {
  35. case ultraLightItalic = "UltraLightItalic"
  36. case medium = "Medium"
  37. case mediumItalic = "MediumItalic"
  38. case ultraLight = "UltraLight"
  39. case italic = "Italic"
  40. case light = "Light"
  41. case thinItalic = "ThinItalic"
  42. case lightItalic = "LightItalic"
  43. case bold = "Bold"
  44. case thin = "Thin"
  45. case condensedBlack = "CondensedBlack"
  46. case condensedBold = "CondensedBold"
  47. case boldItalic = "BoldItalic"
  48. func with(size: CGFloat) -> UIFont {
  49. return UIFont(name: "HelveticaNeue-\(rawValue)", size: size)!
  50. }
  51. }
  52. }
  53. @objc enum messageType: Int {
  54. case error
  55. case success
  56. case info
  57. }
  58. // MARK: - Message
  59. func showError(error: NKError, priority: EKAttributes.Precedence.Priority = .normal) {
  60. messageNotification(
  61. "_error_",
  62. error: error,
  63. delay: NCGlobal.shared.dismissAfterSecond,
  64. type: .error,
  65. priority: priority)
  66. }
  67. func showInfo(error: NKError, priority: EKAttributes.Precedence.Priority = .normal) {
  68. messageNotification(
  69. "_info_",
  70. error: error,
  71. delay: NCGlobal.shared.dismissAfterSecond,
  72. type: .info,
  73. priority: priority)
  74. }
  75. func showInfo(title: String = "", description: String = "") {
  76. self.flatTop(title: NSLocalizedString(title, comment: ""), description: NSLocalizedString(description, comment: ""), delay: NCGlobal.shared.dismissAfterSecond, imageName: nil, type: .info, priority: .normal)
  77. }
  78. func showWarning(error: NKError, priority: EKAttributes.Precedence.Priority = .normal) {
  79. messageNotification(
  80. "_warning_",
  81. error: error,
  82. delay: NCGlobal.shared.dismissAfterSecond,
  83. type: .info,
  84. priority: priority)
  85. }
  86. @objc func messageNotification(_ title: String, error: NKError, delay: TimeInterval, type: messageType) {
  87. messageNotification(title, error: error, delay: delay, type: type, priority: .normal, dropEnqueuedEntries: false)
  88. }
  89. func messageNotification(_ title: String, error: NKError, delay: TimeInterval, type: messageType, priority: EKAttributes.Precedence.Priority = .normal, dropEnqueuedEntries: Bool = false) {
  90. // No notification message for:
  91. if error.errorCode == NSURLErrorCancelled || error.errorCode == NCGlobal.shared.errorRequestExplicityCancelled { return } else if error == .success && type == messageType.error { return }
  92. // Hardcode change type
  93. var type = type
  94. if error.errorCode == NCGlobal.shared.errorE2EEUploadInProgress {
  95. type = .info
  96. }
  97. DispatchQueue.main.async {
  98. switch error.errorCode {
  99. case Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue):
  100. let image = UIImage(named: "networkInProgress")!.image(color: .white, size: 20)
  101. self.noteTop(text: NSLocalizedString(title, comment: ""), image: image, color: .lightGray, delay: delay, priority: .max)
  102. default:
  103. var responseMessage = ""
  104. if let data = error.responseData {
  105. do {
  106. if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any],
  107. let message = json["message"] as? String {
  108. responseMessage = "\n\n" + message
  109. }
  110. } catch {
  111. print("Something went wrong")
  112. }
  113. }
  114. if error.errorDescription.trimmingCharacters(in: .whitespacesAndNewlines) == "" { return }
  115. let description = NSLocalizedString(error.errorDescription, comment: "")
  116. self.flatTop(title: NSLocalizedString(title, comment: ""), description: description + responseMessage + " \(error.errorCode)", delay: delay, imageName: nil, type: type, priority: priority, dropEnqueuedEntries: dropEnqueuedEntries)
  117. }
  118. }
  119. }
  120. // MARK: - Flat message
  121. private func flatTop(title: String, description: String, delay: TimeInterval, imageName: String?, type: messageType, priority: EKAttributes.Precedence.Priority = .normal, dropEnqueuedEntries: Bool = false) {
  122. if SwiftEntryKit.isCurrentlyDisplaying(entryNamed: title + description) { return }
  123. var attributes = EKAttributes.topFloat
  124. var image: UIImage?
  125. attributes.windowLevel = .normal
  126. attributes.displayDuration = delay
  127. attributes.name = title + description
  128. attributes.entryBackground = .color(color: EKColor(getBackgroundColorFromType(type)))
  129. attributes.popBehavior = .animated(animation: .init(translate: .init(duration: 0.3), scale: .init(from: 1, to: 0.7, duration: 0.7)))
  130. attributes.shadow = .active(with: .init(color: .black, opacity: 0.5, radius: 10, offset: .zero))
  131. attributes.scroll = .enabled(swipeable: true, pullbackAnimation: .jolt)
  132. attributes.precedence = .override(priority: priority, dropEnqueuedEntries: dropEnqueuedEntries)
  133. let title = EKProperty.LabelContent(text: title, style: .init(font: MainFont.bold.with(size: 16), color: .white))
  134. let description = EKProperty.LabelContent(text: description, style: .init(font: MainFont.medium.with(size: 13), color: .white))
  135. if imageName == nil {
  136. image = getImageFromType(type)
  137. } else {
  138. image = UIImage(named: imageName!)
  139. }
  140. let imageMessage = EKProperty.ImageContent(image: image!, size: CGSize(width: 35, height: 35))
  141. let simpleMessage = EKSimpleMessage(image: imageMessage, title: title, description: description)
  142. let notificationMessage = EKNotificationMessage(simpleMessage: simpleMessage)
  143. let contentView = EKNotificationMessageView(with: notificationMessage)
  144. DispatchQueue.main.async { SwiftEntryKit.display(entry: contentView, using: attributes) }
  145. }
  146. // MARK: -
  147. 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) {
  148. var buttonAttributes: EKAttributes {
  149. var attributes = attributes
  150. attributes.hapticFeedbackType = .success
  151. attributes.displayDuration = .infinity
  152. attributes.entryBackground = .color(color: EKColor(backgroundColor))
  153. attributes.shadow = .active(with: .init(color: .black, opacity: 0.3, radius: 8))
  154. attributes.screenInteraction = .dismiss
  155. attributes.entryInteraction = .absorbTouches
  156. attributes.scroll = .enabled(swipeable: true, pullbackAnimation: .jolt)
  157. attributes.roundCorners = .all(radius: 25)
  158. 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)))
  159. attributes.exitAnimation = .init(translate: .init(duration: 0.2))
  160. attributes.popBehavior = .animated(animation: .init(translate: .init(duration: 0.2)))
  161. attributes.positionConstraints.verticalOffset = 20
  162. attributes.positionConstraints.size = .init(width: .offset(value: 20), height: .intrinsic)
  163. attributes.positionConstraints.maxSize = .init(width: .constant(value: min(UIScreen.main.bounds.width, UIScreen.main.bounds.height)), height: .intrinsic)
  164. attributes.statusBar = .dark
  165. return attributes
  166. }
  167. let simpleMessage = EKSimpleMessage(image: EKProperty.ImageContent(image: image, size: sizeImage, contentMode: contentModeImage),
  168. title: EKProperty.LabelContent(text: NSLocalizedString(title, comment: ""), style: .init(font: MainFont.medium.with(size: 15), color: EKColor(textColor)), accessibilityIdentifier: "title"),
  169. description: EKProperty.LabelContent(text: NSLocalizedString(description, comment: ""), style: .init( font: MainFont.light.with(size: 13), color: EKColor(textColor)), accessibilityIdentifier: "description"))
  170. let cancelButton = EKProperty.ButtonContent(
  171. label: EKProperty.LabelContent(text: NSLocalizedString(textCancelButton, comment: ""), style: EKProperty.LabelStyle(font: MainFont.medium.with(size: 16), color: EKColor(textColor))),
  172. backgroundColor: .clear,
  173. highlightedBackgroundColor: EKColor(UIColor.lightGray),
  174. accessibilityIdentifier: "close") {
  175. SwiftEntryKit.dismiss()
  176. completion("close")
  177. }
  178. let okButton = EKProperty.ButtonContent(
  179. label: EKProperty.LabelContent(text: NSLocalizedString(textOkButton, comment: ""), style: EKProperty.LabelStyle(font: MainFont.medium.with(size: 16), color: EKColor(textColor))),
  180. backgroundColor: .clear,
  181. highlightedBackgroundColor: EKColor(UIColor.lightGray),
  182. displayMode: EKAttributes.DisplayMode.inferred,
  183. accessibilityIdentifier: "ok") {
  184. SwiftEntryKit.dismiss()
  185. completion("ok")
  186. }
  187. let buttonsBarContent = EKProperty.ButtonBarContent(with: cancelButton, okButton, separatorColor: EKColor(textColor), buttonHeight: 60, expandAnimatedly: true)
  188. let alertMessage = EKAlertMessage(simpleMessage: simpleMessage, imagePosition: .left, buttonBarContent: buttonsBarContent)
  189. let contentView = EKAlertMessageView(with: alertMessage)
  190. SwiftEntryKit.display(entry: contentView, using: buttonAttributes)
  191. }
  192. // MARK: - Note Message
  193. func noteTop(text: String, image: UIImage?, color: UIColor? = nil, type: messageType? = nil, delay: TimeInterval, priority: EKAttributes.Precedence.Priority = .normal, dropEnqueuedEntries: Bool = false) {
  194. if SwiftEntryKit.isCurrentlyDisplaying(entryNamed: text) { return }
  195. DispatchQueue.main.async {
  196. var attributes = EKAttributes.topNote
  197. attributes.windowLevel = .normal
  198. attributes.displayDuration = delay
  199. attributes.name = text
  200. if let color = color {
  201. attributes.entryBackground = .color(color: EKColor(color))
  202. }
  203. if let type = type {
  204. attributes.entryBackground = .color(color: EKColor(self.getBackgroundColorFromType(type)))
  205. }
  206. attributes.precedence = .override(priority: priority, dropEnqueuedEntries: dropEnqueuedEntries)
  207. let style = EKProperty.LabelStyle(font: MainFont.light.with(size: 14), color: .white, alignment: .center)
  208. let labelContent = EKProperty.LabelContent(text: text, style: style)
  209. if let image = image {
  210. let imageContent = EKProperty.ImageContent(image: image, size: CGSize(width: 17, height: 17))
  211. let contentView = EKImageNoteMessageView(with: labelContent, imageContent: imageContent)
  212. SwiftEntryKit.display(entry: contentView, using: attributes)
  213. } else {
  214. let contentView = EKNoteMessageView(with: labelContent)
  215. SwiftEntryKit.display(entry: contentView, using: attributes)
  216. }
  217. }
  218. }
  219. func dismiss(after: TimeInterval = 0) {
  220. DispatchQueue.main.asyncAfter(deadline: .now() + after) {
  221. SwiftEntryKit.dismiss()
  222. }
  223. }
  224. // MARK: - Private
  225. private func getBackgroundColorFromType(_ type: messageType) -> UIColor {
  226. switch type {
  227. case .info:
  228. return NCBrandColor.shared.brandElement
  229. case .error:
  230. return UIColor(red: 1, green: 0, blue: 0, alpha: 0.9)
  231. case .success:
  232. return UIColor(red: 0.588, green: 0.797, blue: 0, alpha: 0.9)
  233. default:
  234. return .white
  235. }
  236. }
  237. private func getImageFromType(_ type: messageType) -> UIImage? {
  238. switch type {
  239. case .info:
  240. return UIImage(named: "iconInfo")
  241. case .error:
  242. return UIImage(named: "iconError")
  243. case .success:
  244. return UIImage(named: "iconSuccess")
  245. default:
  246. return nil
  247. }
  248. }
  249. }