KMAdsWebView.swift 11 KB

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