KMUserFeekbackWindowController.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. //
  2. // KMUserFeekbackWindowController.swift
  3. // PDF Reader Pro Edition
  4. //
  5. // Created by tangchao on 2024/7/11.
  6. //
  7. import Cocoa
  8. @objcMembers class KMUserFeekbackWindowController: NSWindowController {
  9. static let shared = KMUserFeekbackWindowController(windowNibName: "KMUserFeekbackWindowController")
  10. @IBOutlet weak var emailBox: NSBox!
  11. @IBOutlet weak var typeBox: NSBox!
  12. @IBOutlet weak var despBox: NSBox!
  13. @IBOutlet weak var listHeaderBox: NSBox!
  14. @IBOutlet weak var listBox: NSBox!
  15. @IBOutlet weak var comfirmButton: NSButton!
  16. @IBOutlet weak var cancelButton: NSButton!
  17. private var emailItemView_: KMUserFbEmailItemView?
  18. private var typeItemView_: KMUserFbTypeItemView?
  19. private var despItemView_: KMUserFbDespItemView?
  20. private var listHeaderItemView_: KMUserFbListHeaderItemView?
  21. private var listItemView_: KMUserListItemView?
  22. typealias KMRequestServerComplete = (_ wrapper: ResultWrapper) -> Void
  23. private var filePaths_: [String] = []
  24. private var logPath_: String?
  25. private var popover_: NSPopover?
  26. var typeString: String = ""
  27. private var fileFormats_: [String] = ["jpg", "jpeg", "png", "gif", "bmp", "tiff", "tif", "psd", "svg", "pdf", "mp4", "mov", "avi", "mkv", "wmv", "flv", "mpg", "3gp", "doc", "docx", "xls" ,"xlsx", "ppt", "pptx", "txt", "rtf", "nfo"]
  28. private var fileFormatsString = "jpg, jpeg, png, gif, bmp, tiff, tif, psd, svg, pdf, mp4, mov, avi, mkv, wmv, flv, mpg, 3gp, doc, docx, xls,xlsx, ppt, pptx, txt, rtf, nfo"
  29. deinit {
  30. Swift.debugPrint("KMUserFeekbackWindowController deinit.")
  31. DistributedNotificationCenter.default().removeObserver(self)
  32. }
  33. override func windowDidLoad() {
  34. super.windowDidLoad()
  35. self._initDefaultValue()
  36. self._initSubViews()
  37. self.typeItemView_?.comBoBox.selectItem(at: 0)
  38. self.updateViewColor()
  39. DistributedNotificationCenter.default().addObserver(self, selector: #selector(themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  40. }
  41. private func _initDefaultValue() {
  42. if let btn = self.window?.standardWindowButton(.miniaturizeButton) {
  43. btn.isHidden = true
  44. }
  45. if let btn = self.window?.standardWindowButton(.zoomButton) {
  46. btn.isHidden = true
  47. }
  48. self.window?.title = NSLocalizedString("Feedback for PDF Reader Pro", comment: "")
  49. self.emailBox.borderWidth = 0
  50. self.typeBox.borderWidth = 0
  51. self.despBox.borderWidth = 0
  52. self.listHeaderBox.borderWidth = 0
  53. self.listBox.borderWidth = 0
  54. let email = VerificationManager.default()?.email ?? ""
  55. self.emailItemView_?.textfiled.stringValue = email
  56. self.emailItemView_?.textfiled.nextResponder = self.despItemView_?.textView
  57. self.cancelButton.title = NSLocalizedString("Cancel", comment: "")
  58. self.comfirmButton.title = NSLocalizedString("Submit", comment: "")
  59. self.cancelButton.target = self
  60. self.cancelButton.action = #selector(_cancelButtonAction)
  61. self.comfirmButton.target = self
  62. self.comfirmButton.action = #selector(_comfirmButtonAction)
  63. }
  64. private func _initSubViews() {
  65. self.emailItemView_ = KMUserFbEmailItemView.createFromNib()
  66. self.emailBox.contentView = self.emailItemView_
  67. self.typeItemView_ = KMUserFbTypeItemView.createFromNib()
  68. self.typeBox.contentView = self.typeItemView_
  69. self.despItemView_ = KMUserFbDespItemView.createFromNib()
  70. self.despBox.contentView = self.despItemView_
  71. self.listHeaderItemView_ = KMUserFbListHeaderItemView.createFromNib()
  72. self.listHeaderBox.contentView = self.listHeaderItemView_
  73. self.listItemView_ = KMUserListItemView.createFromNib()
  74. self.listBox.contentView = self.listItemView_
  75. self.listItemView_?.hiddenTip()
  76. self.listHeaderItemView_?.helpHoverCallback = { [weak self] action in
  77. if action.rawValue == 0 { // enter
  78. self?._showHelpPopover((self?.listHeaderItemView_?.helpButton)!)
  79. } else if action.rawValue == 2 { // exit
  80. self?._hiddenHelpPopover()
  81. }
  82. }
  83. self.listHeaderItemView_?.itemClick = { [weak self] idx in
  84. if idx == 1 { // 获取日志文件
  85. } else if idx == 3 { // 新增文件
  86. let panel = NSOpenPanel()
  87. // panel.message = self?.fileFormatsString
  88. panel.allowedFileTypes = self?.fileFormats_
  89. panel.allowsMultipleSelection = true
  90. panel.beginSheetModal(for: self!.window!) { resp in
  91. if resp == .cancel {
  92. return
  93. }
  94. for url in panel.urls {
  95. self?.filePaths_.append(url.path)
  96. }
  97. self?._updateListData()
  98. }
  99. }
  100. }
  101. self.listItemView_?.itemClick = { [weak self] idx, param in
  102. if let cnt = self?.filePaths_.count, idx < cnt {
  103. self?.filePaths_.remove(at: idx)
  104. self?._updateListData()
  105. }
  106. }
  107. self.listItemView_?.validateDropCallback = { [weak self] info, row, dropOperation in
  108. let datas = self?.filePaths_.count ?? 0
  109. if datas >= 10 {
  110. return NSDragOperation(rawValue: 0)
  111. }
  112. return .generic
  113. }
  114. self.listItemView_?.acceptDropCallback = { [weak self] info, row, dropOperation in
  115. let pborad = info.draggingPasteboard
  116. guard let _ = pborad.availableType(from: [.fileURL]) else {
  117. return false
  118. }
  119. guard let items = pborad.pasteboardItems else {
  120. return false
  121. }
  122. for item in items {
  123. let string = item.propertyList(forType: .fileURL) as? String ?? ""
  124. if let path = URL(string: string)?.path {
  125. let contains = self?._fileFormatIsContains(URL(string: string)!.pathExtension) ?? false
  126. if contains {
  127. self?.filePaths_.append(path)
  128. }
  129. }
  130. }
  131. self?._updateListData()
  132. return true
  133. }
  134. }
  135. override func showWindow(_ sender: Any?) {
  136. super.showWindow(sender)
  137. self.typeItemView_?.comBoBox.stringValue = self.typeString
  138. }
  139. func updateViewColor() {
  140. if KMAppearance.isDarkMode() {
  141. self.window?.backgroundColor = NSColor(red: 40/255.0, green: 40/255.0, blue: 40/255.0, alpha: 1)
  142. self.emailItemView_?.box.fillColor = NSColor(red: 110/255.0, green: 109/255.0, blue: 112/255.0, alpha: 1)
  143. self.typeItemView_?.comBoBox.backgroundColor = NSColor(red: 110/255.0, green: 109/255.0, blue: 112/255.0, alpha: 1)
  144. self.despItemView_?.box.fillColor = NSColor(red: 110/255.0, green: 109/255.0, blue: 112/255.0, alpha: 1)
  145. self.listItemView_?.tipBox.fillColor = NSColor(red: 231/255.0, green: 56/255.0, blue: 91/255.0, alpha: 1)
  146. } else {
  147. self.window?.backgroundColor = .white
  148. self.emailItemView_?.box.fillColor = .white
  149. self.typeItemView_?.comBoBox.backgroundColor = .white
  150. self.despItemView_?.box.fillColor = .white
  151. self.listItemView_?.tipBox.fillColor = NSColor.km_init(hex: "#FEE4EC")
  152. }
  153. }
  154. // MARK: - Noti Methods
  155. @objc func themeChanged(_ notification: Notification) {
  156. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  157. self.updateViewColor()
  158. }
  159. }
  160. // MARK: - Private Methods
  161. @objc private func _cancelButtonAction() {
  162. self.window?.orderOut(nil)
  163. }
  164. @objc private func _comfirmButtonAction() {
  165. if let data = self.listHeaderItemView_?.checkButton.state, data == .on {
  166. let fileaccess = AppSandboxFileAccess()
  167. // /Users/kdanmobile/Library/Logs/DiagnosticReports
  168. let url = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first
  169. let coms = url?.pathComponents ?? []
  170. var filePath: String = ""
  171. for (i, com) in coms.enumerated() {
  172. if i > 2 {
  173. break
  174. } else {
  175. filePath.append("/\(com)")
  176. }
  177. }
  178. let cmd = filePath.appending("/Library/Logs/DiagnosticReports/")
  179. // /Library/Logs/DiagnosticReports/
  180. // fileaccess?.accessFilePath(cmd, persistPermission: true, with: {
  181. //
  182. // })
  183. let logString = self._getLog()
  184. if logString.isEmpty == false {
  185. let bundleIdentifier = Bundle.main.bundleIdentifier ?? "PDF Reader Pro"
  186. if let url = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent(bundleIdentifier) {
  187. if FileManager.default.fileExists(atPath: url.path) == false {
  188. try?FileManager.default.createDirectory(at: url, withIntermediateDirectories: false)
  189. }
  190. let fileUrl = url.appendingPathComponent("Log.txt")
  191. try?logString.write(to: fileUrl, atomically: true, encoding: .utf8)
  192. self.logPath_ = fileUrl.path
  193. }
  194. }
  195. } else {
  196. self.logPath_ = nil
  197. }
  198. self.window?.makeFirstResponder(nil)
  199. let state = self._isConnectionAvailable()
  200. if !state {
  201. self._showHud(msg: NSLocalizedString("Please make sure your internet connection is available.", comment: ""))
  202. return
  203. }
  204. guard let emailString = self.emailItemView_?.string(), emailString.isEmpty == false else {
  205. // 邮箱为空
  206. self.emailItemView_?.showTip(label: NSLocalizedString("Please enter your email", comment: ""))
  207. return
  208. }
  209. if KMValidateEmail(email: emailString) == false {
  210. self.emailItemView_?.showTip(label: NSLocalizedString("Please enter valid email", comment: ""))
  211. return
  212. }
  213. guard let despString = self.despItemView_?.string(), despString.isEmpty == false else {
  214. // 描述信息为空
  215. self.despItemView_?.showTip()
  216. return
  217. }
  218. self.window?.contentView?.beginLoading()
  219. self.comfirmButton.isEnabled = false
  220. var filePaths: [String] = self.filePaths_
  221. if let data = self.listHeaderItemView_?.checkButton.state, data == .on {
  222. if let filePath = self.logPath_, filePath.isEmpty == false {
  223. filePaths.append(filePath)
  224. }
  225. }
  226. self._feekbackAction(filePaths: filePaths) { [weak self] wrapper in
  227. self?.window?.contentView?.endLoading()
  228. self?.comfirmButton.isEnabled = true
  229. if wrapper.success {
  230. self?._showHud(msg: NSLocalizedString("Thank you for your feedback! Customer service will feedback to your email within 1 working day", comment: ""))
  231. DispatchQueue.main.asyncAfter(deadline: .now() + 1.8) {
  232. self?.despItemView_?.textView.string = ""
  233. self?.despItemView_?.textView.placeholderLabel.isHidden = false;
  234. self?.filePaths_.removeAll()
  235. self?._updateListData()
  236. if let data = self?.logPath_, data.isEmpty == false {
  237. if FileManager.default.fileExists(atPath: data) {
  238. try?FileManager.default.removeItem(atPath: data)
  239. }
  240. }
  241. self?.logPath_ = nil
  242. self?.window?.orderOut(nil)
  243. }
  244. } else {
  245. self?._showHud(msg: wrapper.content)
  246. }
  247. }
  248. }
  249. private func _showHelpPopover(_ sender: NSButton) {
  250. if self.popover_ != nil {
  251. return
  252. }
  253. let vc = KMUserFbHelpPopController()
  254. vc.formatSting = self.fileFormatsString
  255. let popover = NSPopover()
  256. popover.contentViewController = vc
  257. popover.animates = true
  258. popover.behavior = .semitransient
  259. popover.delegate = self
  260. popover.setValue(true, forKey: "shouldHideAnchor")
  261. self.popover_ = popover
  262. vc.isDrak = KMAppearance.isDarkMode()
  263. popover.show(relativeTo: sender.bounds, of: sender, preferredEdge: .maxX)
  264. }
  265. private func _hiddenHelpPopover() {
  266. self.popover_?.close()
  267. }
  268. private func _updateListData() {
  269. self.listItemView_?.hiddenTip()
  270. var datas: [KMUserFbListModel] = []
  271. let maxSize: Double = 20 * 1024 * 1024
  272. var fileSize: Double = 0
  273. var filePaths: [String] = []
  274. var showFileSizeLimit = false
  275. var showFileCountLimit = false
  276. for (i, fileP) in self.filePaths_.enumerated() {
  277. let model = KMUserFbListModel()
  278. model.filePath = fileP
  279. let url = URL(fileURLWithPath: fileP)
  280. model.fileName = url.lastPathComponent
  281. let attri = try?FileManager.default.attributesOfItem(atPath: fileP)
  282. model.fileSize = attri?[FileAttributeKey.size] as? Double ?? 0
  283. // fileSize += model.fileSize
  284. fileSize = model.fileSize
  285. if fileSize >= maxSize {
  286. showFileSizeLimit = true
  287. continue
  288. }
  289. if i >= 10 {
  290. showFileCountLimit = true
  291. break
  292. }
  293. model.fileSizeString = self.fileSizeString(model.fileSize) ?? ""
  294. datas.append(model)
  295. filePaths.append(fileP)
  296. }
  297. self.filePaths_ = filePaths
  298. if showFileCountLimit {
  299. self.listItemView_?.showTip(tip: NSLocalizedString("Add failed: upload up to 10 files", comment: ""))
  300. } else if showFileSizeLimit {
  301. self.listItemView_?.showTip(tip: NSLocalizedString("Add failed: attachment size cannot exceed 20M", comment: ""))
  302. }
  303. if datas.count >= 10 {
  304. self.listHeaderItemView_?.addButton.isEnabled = false
  305. } else {
  306. self.listHeaderItemView_?.addButton.isEnabled = true
  307. }
  308. self.listItemView_?.datas = datas
  309. }
  310. private func _showHud(msg: String) {
  311. if let data = self.window?.contentView {
  312. // _ = CustomAlertView(message: msg, from: data, with: .black)
  313. CustomAlertView.alertView(message: msg, fromView: data, withStyle: .black)
  314. }
  315. }
  316. private func _getLog() -> String {
  317. let url = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first
  318. let coms = url?.pathComponents ?? []
  319. var filePath: String = ""
  320. for (i, com) in coms.enumerated() {
  321. if i > 2 {
  322. break
  323. } else {
  324. filePath.append("/\(com)")
  325. }
  326. }
  327. // ls /Library/Logs/DiagnosticReports/PDF*
  328. let cmd = "ls \(filePath)/Library/Logs/DiagnosticReports/PDF*"
  329. let filestrings = _runShellCommand(cmd)
  330. let files = filestrings.components(separatedBy: "\n")
  331. var results: [String] = []
  332. for string in files {
  333. if string.contains("PDF Reader Pro") {
  334. var tempS = string
  335. // tempS.replace(" ", with: "\\ ")
  336. // tempS.replacingCharacters(in: " ", with: "\\ ")
  337. // let ss = tempS.replacing(" ", with: "\\ ")
  338. let ss = tempS.replacingOccurrences(of: " ", with: "\\ ")
  339. results.append(ss)
  340. }
  341. }
  342. if results.isEmpty {
  343. let cmd = "ls \(filePath)/Library/Logs/DiagnosticReports/Retired/PDF*"
  344. let filestrings = _runShellCommand(cmd)
  345. let files = filestrings.components(separatedBy: "\n")
  346. for string in files {
  347. if string.contains("PDF Reader Pro") {
  348. var tempS = string
  349. // tempS.replace(" ", with: "\\ ")
  350. // tempS.replacingCharacters(in: " ", with: "\\ ")
  351. // let ss = tempS.replacing(" ", with: "\\ ")
  352. let ss = tempS.replacingOccurrences(of: " ", with: "\\ ")
  353. results.append(ss)
  354. }
  355. }
  356. }
  357. if let file = results.last {
  358. let cmd = "cat \(file)"
  359. // cat /Library/Logs/DiagnosticReports/PDF*
  360. let logs = _runShellCommand(cmd)
  361. return logs
  362. }
  363. return ""
  364. }
  365. private func _runShellCommand(_ command: String) -> String {
  366. let task = Process()
  367. let pipe = Pipe()
  368. task.standardOutput = pipe
  369. task.standardError = pipe
  370. task.arguments = ["-c", command]
  371. task.launchPath = "/bin/bash"
  372. do {
  373. try task.run()
  374. } catch {
  375. return "Error running command: \(error)"
  376. }
  377. let data = pipe.fileHandleForReading.readDataToEndOfFile()
  378. let output = String(data: data, encoding: .utf8) ?? ""
  379. return output
  380. }
  381. func test() {
  382. var convertString = "TARGET_BUNDLE_IDENTIFIER=\"com.brother.pdfreaderprofree.mac\"\n"
  383. convertString = convertString.appendingFormat("SANDBOX_ROOT=$(osascript -e 'tell application \"System Events\" to get the path of the home folder of (system info)')\n")
  384. convertString = convertString.appendingFormat("CONTAINER_LOG_PATH=$(osascript <<EOF\n")
  385. convertString.append("tell application \"System Events\"\n")
  386. // convertString.append("set isRun to running\n")
  387. convertString.append("set container_path to POSIX path of (the home folder as text) & \"Library:Containers:\" & \"$TARGET_BUNDLE_IDENTIFIER\"\n")
  388. convertString.append("set log_path to container_path & \":Logs:\" & \"Console.app-History\"\n")
  389. convertString.append("return log_path\n")
  390. convertString.append("end tell\n")
  391. convertString.append("EOF)\n")
  392. convertString.append("echo \"日志文件路径: $CONTAINER_LOG_PATH\"\n")
  393. var dic: NSDictionary?
  394. let docScript = NSAppleScript(source: convertString)
  395. docScript?.executeAndReturnError(&dic)
  396. }
  397. func fileSizeString(_ fSize: Double) -> String {
  398. let fileSize = fSize / 1024
  399. let size = fileSize >= 1024 ? (fileSize < 1048576 ? fileSize/1024 : fileSize/1048576.0) : fileSize
  400. let unit = fileSize >= 1024 ? (fileSize < 1048576 ? "M" : "G") : "K"
  401. return String(format: "%0.1f %@", size, unit)
  402. }
  403. private func _feekbackAction(filePaths: [String], complete: @escaping KMRequestServerComplete) {
  404. let urlString = kVerificationServer + "/api/feedback/feedback"
  405. var fileDatas: [Data] = []
  406. for filePath in filePaths {
  407. if let fileData = FileManager.default.contents(atPath: filePath) {
  408. fileDatas.append(fileData)
  409. }
  410. }
  411. let (major, minor, bugFix) = KMTools.getSystemVersion()
  412. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  413. let appVersion = KMTools.getAppVersion()
  414. let appName = KMTools.getAppNameForSupportEmail()
  415. let typeString = (self.typeItemView_?.string() ?? "") + ";" + appName + " - " + appVersion + ";" + versionInfoString
  416. let uuid = GetHardwareUUID()
  417. let params: [String: Any] = ["email": self.emailItemView_?.string() ?? "",
  418. "title": typeString,
  419. "content": self.despItemView_?.string() ?? "",
  420. "unique_sn" : uuid!,
  421. "files[]" : fileDatas]
  422. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  423. for i in 0 ..< fileDatas.count {
  424. let path = filePaths[i]
  425. let fileURL = URL(fileURLWithPath: path)
  426. try? formData.appendPart(withFileURL: fileURL, name: "files[]", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  427. }
  428. } requestSerializer: { requestSerializer in
  429. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  430. } completion: { task, responseObject, error in
  431. if responseObject != nil {
  432. let data: NSDictionary = responseObject as? NSDictionary ?? [:]
  433. // var code: String = responseObject!["code"] as? String ?? "06005"
  434. let code = data["code"] as? Int ?? 06005
  435. if code == 06005 {
  436. // let tempCode: Int = responseObject!["code"] as? Int ?? 0
  437. // if tempCode == 501 {
  438. // code = "501"
  439. // }
  440. }
  441. let message: String = data["message"] as? String ?? "unknown error"
  442. let error = NSError(domain: message, code: code)
  443. if code == 200 {
  444. let wrapper = ResultWrapper(success: true, resultData: data)
  445. // wrapper.content = data["fileKey"] as! String
  446. complete(wrapper)
  447. } else {
  448. let wrapper = ResultWrapper(success: false, resultData: data)
  449. if code == 501 {
  450. wrapper.content = "501"
  451. } else {
  452. wrapper.content = message
  453. }
  454. complete(wrapper)
  455. }
  456. } else {
  457. complete(ResultWrapper(success: false, content: "unknown error"))
  458. }
  459. }
  460. }
  461. private func _isConnectionAvailable() -> Bool {
  462. if Reachability.forInternetConnection().currentReachabilityStatus().rawValue == 0 {
  463. return false
  464. }
  465. return true
  466. }
  467. private func _fileFormatIsContains(_ exn: String) -> Bool {
  468. let _exn = exn.lowercased()
  469. return self.fileFormats_.contains(_exn)
  470. }
  471. }
  472. extension KMUserFeekbackWindowController: NSPopoverDelegate {
  473. func popoverWillClose(_ notification: Notification) {
  474. if let data = self.popover_?.isEqual(to: notification.object), data {
  475. self.popover_ = nil
  476. }
  477. }
  478. }