KMAdsWebView.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import Cocoa
  2. import WebKit
  3. protocol AdsWebViewDelegate: AnyObject {
  4. func kmAdViewClicked(_ adView: KMAdsWebView)
  5. func kmAdViewClose(_ adView: KMAdsWebView)
  6. }
  7. enum KMADViewDirections: Int {
  8. case up
  9. case down
  10. }
  11. // Banner Ads Width,Height
  12. let kAD_View_Width = 728.0
  13. let kAD_View_Height = 90.0
  14. // Banner Ads refresh rate in second, 新广告会自动刷新,所以时间延长
  15. let kAD_Refresh_Rate = 6000.0
  16. class KMAdsWebView: NSView, WKNavigationDelegate, CAAnimationDelegate {
  17. weak var adDelegate: AdsWebViewDelegate?
  18. private var closeButton: NSButton
  19. private var timer: Timer?
  20. private var currentPage: Int = 0
  21. private var completionHandler: ((Int) -> Void)?
  22. private var adsWebView: WKWebView
  23. var adPosY: CGFloat = 30.0
  24. override init(frame frameRect: NSRect) {
  25. closeButton = NSButton(frame: NSRect(x: frameRect.size.width - 30, y: frameRect.size.height - 30, width: 30, height: 30))
  26. adsWebView = WKWebView(frame: frameRect)
  27. super.init(frame: frameRect)
  28. wantsLayer = true
  29. self.frame = NSRect(x: 0, y: 0, width: kAD_View_Width, height: kAD_View_Height)
  30. autoresizingMask = [.minXMargin, .maxXMargin]
  31. adsWebView.navigationDelegate = self
  32. adsWebView.autoresizingMask = [.width, .height]
  33. addSubview(adsWebView)
  34. adPosY = 30.0
  35. closeButton.isHidden = false
  36. closeButton.imagePosition = .imageOnly
  37. // closeButton.cell?.highlightsBy = .contentsCellMask
  38. closeButton.imageScaling = .scaleProportionallyUpOrDown
  39. closeButton.image = NSImage(named: "ad_cancel_button00")
  40. closeButton.isBordered = false
  41. closeButton.target = self
  42. closeButton.action = #selector(buttonItemClicked_Close(_:))
  43. addSubview(closeButton)
  44. NotificationCenter.default.addObserver(self, selector: #selector(handleUserHaveClickRateUsNotification(_:)), name: NSNotification.Name("kUserHaveClickRateUsNotification"), object: nil)
  45. NotificationCenter.default.addObserver(self, selector: #selector(adsWebView_Switch), name: NSNotification.Name("KMFirebaseRemateConfigRequestIsSuccessful"), object: nil)
  46. }
  47. required init?(coder: NSCoder) {
  48. fatalError("init(coder:) has not been implemented")
  49. }
  50. deinit {
  51. adDelegate = nil
  52. adsWebView.navigationDelegate = nil
  53. adsWebView.stopLoading()
  54. timer?.invalidate()
  55. timer = nil
  56. completionHandler = nil
  57. NotificationCenter.default.removeObserver(self)
  58. }
  59. var adsData: [String] {
  60. get {
  61. #if VERSION_DMG
  62. if !UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey") {
  63. return ["https://test.sitemaji.com/native/pdfreaderpro.html?s=PDFReaderPro_Mac_DMG_HouseAD_728x90"]
  64. } else {
  65. return ["https://test.sitemaji.com/native/pdfreaderpro.html?s=PDFReaderPro_Mac_DMG_728x90"]
  66. }
  67. #else
  68. if !UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey") {
  69. return ["https://test.sitemaji.com/native/pdfreaderpro.html?s=PDFReaderPro_Mac_Store_HouseAD_728x90"]
  70. } else {
  71. return ["https://test.sitemaji.com/native/pdfreaderpro.html?s=PDFReaderPro_Mac_Store_728x90"]
  72. }
  73. #endif
  74. if !UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey") {
  75. return [KMKdanRemoteConfig.remoteConfig().displayHouseAdsUrl()]
  76. } else {
  77. return [KMKdanRemoteConfig.remoteConfig().displayAdsUrl()]
  78. }
  79. #if DEBUG
  80. #if VERSION_DMG
  81. return ["http://test-pdf-pro.kdan.cn:3021/native?s=PDFReaderPro_Mac_DMG_HouseAD_728x90&testflag=on"]
  82. #else
  83. return ["http://test-pdf-pro.kdan.cn:3021/native?s=PDFReaderPro_Mac_Store_HouseAD_728x90&testflag=on"]
  84. #endif
  85. #endif
  86. }
  87. set {
  88. }
  89. }
  90. func restoreDefaultAdPosY() {
  91. adPosY = 30.0
  92. }
  93. func sortAdsData() {
  94. return
  95. let tLength = self.adsData.count
  96. for _ in 0..<24 {
  97. let tIndex0 = Int(arc4random()) % tLength
  98. var tIndex1 = Int(arc4random()) % tLength
  99. if tIndex0 == tIndex1 {
  100. tIndex1 = (tIndex1 + 1) % tLength
  101. }
  102. self.adsData.swapAt(tIndex0, tIndex1)
  103. }
  104. }
  105. func startAdsDataRequest() {
  106. adsWebView.navigationDelegate = self
  107. if adsData.count > 0 {
  108. let url = URL(string: adsData[currentPage])
  109. adsWebView.load(URLRequest(url: url!))
  110. KMAdsManager.defaultManager.refreshLoadingDate()
  111. }
  112. }
  113. func stopLoading() {
  114. adsWebView.navigationDelegate = nil
  115. adsWebView.stopLoading()
  116. }
  117. func resizeWithOldSuperviewSize(oldSize: NSSize) {
  118. var width = kAD_View_Width
  119. var height = kAD_View_Height
  120. if superview?.frame.size.width ?? 0 < width {
  121. let newWidth = (superview?.frame.size.width ?? 0) - 20
  122. height = height / width * newWidth
  123. width = newWidth
  124. }
  125. self.frame = NSRect(x: (superview?.frame.size.width ?? 0 - width) / 2.0, y: frame.origin.y, width: width, height: height)
  126. adsWebView.frame = bounds
  127. }
  128. func beginSheetModalForView(view: NSView, directions: KMADViewDirections, animated: Bool, completionHandler handler: ((Int) -> Void)?) {
  129. self.completionHandler = handler
  130. if adPosY < 0 {
  131. restoreDefaultAdPosY()
  132. }
  133. let tWidth = frame.size.width
  134. let tHeight = frame.size.height
  135. view.addSubview(self)
  136. if animated {
  137. switch directions {
  138. case .up:
  139. frame = NSRect(x: (view.frame.size.width - tWidth) / 2.0, y: view.frame.size.height, width: tWidth, height: tHeight)
  140. animator().frame = NSRect(x: frame.origin.x, y: view.frame.size.height - tHeight - adPosY, width: tWidth, height: tHeight)
  141. case .down:
  142. frame = NSRect(x: (view.frame.size.width - tWidth) / 2.0, y: -tHeight, width: tWidth, height: tHeight)
  143. animator().frame = NSRect(x: frame.origin.x, y: adPosY, width: tWidth, height: tHeight)
  144. default:
  145. frame = NSRect(x: 0, y: 0, width: tWidth, height: tHeight)
  146. }
  147. } else {
  148. switch directions {
  149. case .up:
  150. frame = NSRect(x: (view.frame.size.width - tWidth) / 2.0, y: view.frame.size.height - tHeight - adPosY, width: tWidth, height: tHeight)
  151. case .down:
  152. frame = NSRect(x: (view.frame.size.width - tWidth) / 2.0, y: adPosY, width: tWidth, height: tHeight)
  153. default:
  154. frame = NSRect(x: 0, y: 0, width: tWidth, height: tHeight)
  155. }
  156. }
  157. adsWebView.frame = bounds
  158. currentPage = 0
  159. startAdsDataRequest()
  160. if timer != nil {
  161. timer?.invalidate()
  162. timer = nil
  163. }
  164. var interval = 0
  165. if !UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey") {
  166. interval = KMKdanRemoteConfig.remoteConfig().refreshAdsDate()
  167. } else {
  168. interval = KMKdanRemoteConfig.remoteConfig().refreshAdsDateEvaluateAfter()
  169. }
  170. timer = Timer.scheduledTimer(timeInterval: TimeInterval(interval), target: self, selector: #selector(adsWebView_Switch), userInfo: nil, repeats: true
  171. )
  172. RunLoop.current.add(timer!, forMode: .common)
  173. }
  174. @objc func adsWebView_Switch() {
  175. DispatchQueue.main.async {
  176. if !KMKdanRemoteConfig.remoteConfig().isDisplayAds() || !KMAdsManager.defaultManager.checkTheDate() || !KMAdsManager.defaultManager.isValidLastShowAds() {
  177. self.removeFromSuperview()
  178. return
  179. }
  180. let transition = CATransition()
  181. transition.type = .moveIn
  182. let tRandomData = arc4random() % 100
  183. if tRandomData > 50 {
  184. transition.subtype = .fromBottom
  185. } else {
  186. transition.subtype = .fromTop
  187. }
  188. transition.duration = 0.6
  189. transition.delegate = self
  190. self.layer?.add(transition, forKey: "KMTransitionAnimation")
  191. self.currentPage += 1
  192. if self.currentPage >= self.adsData.count {
  193. self.currentPage = 0
  194. }
  195. let url = URL(string: self.adsData[self.currentPage])
  196. self.adsWebView.load(URLRequest(url: url!))
  197. KMAdsManager.defaultManager.refreshLoadingDate()
  198. }
  199. }
  200. @objc func buttonItemClicked_Open(_ sender: Any) {
  201. guard let newURL = (sender as? NSURL) else {
  202. return
  203. }
  204. NSWorkspace.shared.open(newURL as URL)
  205. adDelegate?.kmAdViewClicked(self)
  206. if let completionHandler = self.completionHandler {
  207. completionHandler(currentPage + 1)
  208. self.completionHandler = nil
  209. }
  210. removeFromSuperview()
  211. }
  212. @objc func buttonItemClicked_Close(_ sender: Any) {
  213. adDelegate?.kmAdViewClose(self)
  214. if let completionHandler = self.completionHandler {
  215. completionHandler(0)
  216. self.completionHandler = nil
  217. }
  218. removeFromSuperview()
  219. }
  220. func animationDidStart(_ anim: CAAnimation) {
  221. if timer != nil {
  222. timer?.invalidate()
  223. }
  224. closeButton.alphaValue = 0
  225. }
  226. func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
  227. if !flag {
  228. return
  229. }
  230. if timer != nil {
  231. timer?.invalidate()
  232. }
  233. var interval = 0
  234. if !UserDefaults.standard.bool(forKey: "kUserHaveClickRateUsKey") {
  235. interval = KMKdanRemoteConfig.remoteConfig().refreshAdsDate()
  236. } else {
  237. interval = KMKdanRemoteConfig.remoteConfig().refreshAdsDateEvaluateAfter()
  238. }
  239. timer = Timer.scheduledTimer(timeInterval: TimeInterval(interval), target: self, selector: #selector(adsWebView_Switch), userInfo: nil, repeats: true)
  240. RunLoop.current.add(timer!, forMode: .common)
  241. closeButton.alphaValue = 1.0
  242. adsWebView.frame = bounds
  243. }
  244. // MARK: - WKNavigationDelegate
  245. func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  246. if navigationAction.navigationType == .linkActivated {
  247. let tURL = navigationAction.request.url
  248. if tURL != nil {
  249. buttonItemClicked_Open(tURL as Any)
  250. decisionHandler(.cancel)
  251. return
  252. }
  253. }
  254. decisionHandler(.allow)
  255. }
  256. func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  257. webView.evaluateJavaScript("document.body.scrollHeight") { [weak self] (result, error) in
  258. if let height = result as? CGFloat, height > 0 {
  259. let newHeight = min(height, kAD_View_Height)
  260. self?.adsWebView.frame = NSRect(x: 0, y: 0, width: (self?.adsWebView.frame.size.width)!, height: newHeight)
  261. self?.frame.size.height = newHeight
  262. self?.closeButton.frame = NSRect(x: (self?.frame.size.width)! - 30, y: (self?.frame.size.height)! - 30, width: 30, height: 30)
  263. }
  264. }
  265. }
  266. func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
  267. print(error)
  268. }
  269. @objc func handleUserHaveClickRateUsNotification(_ notification: Notification) {
  270. adsWebView_Switch()
  271. }
  272. }