ShareViewController.swift 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. //
  2. // ShareViewController.swift
  3. // AppBuilderShare
  4. //
  5. // Created by Qindi on 11/02/25.
  6. //
  7. import UIKit
  8. import Social
  9. import UniformTypeIdentifiers
  10. import AVFoundation
  11. import QuickLook
  12. class ShareViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UITextViewDelegate, QLPreviewControllerDataSource {
  13. let tableView = UITableView()
  14. let searchBar = UISearchBar()
  15. var contacts: [Contact] = []
  16. var filteredContacts: [Contact] = []
  17. var selectedContact: Contact!
  18. private var textViewBottomConstraint: NSLayoutConstraint?
  19. private var containerBottomConstraint: NSLayoutConstraint?
  20. private var heightTextView: NSLayoutConstraint?
  21. let vcHandleText = UIViewController()
  22. let vcHandleImage = UIViewController()
  23. let vcHandleVideo = UIViewController()
  24. let vcHandleFile = UIViewController()
  25. var textView = UITextView()
  26. var typeShareNum = 0
  27. var selectedImage: URL!
  28. var selectedVideo: URL!
  29. var selectedFile: URL!
  30. var selectedImageTypeImage: UIImage!
  31. private var previewView: VideoPreviewView?
  32. let previewController = QLPreviewController()
  33. private var preparingView: UIView!
  34. private var activityIndicator: UIActivityIndicatorView!
  35. private var preparingLabel: UILabel!
  36. let nameGroupShare = "group.nexilis.share"
  37. override func viewDidLoad() {
  38. super.viewDidLoad()
  39. loadCustomContacts()
  40. registerKeyboardNotifications()
  41. }
  42. deinit {
  43. NotificationCenter.default.removeObserver(self) // Remove observers when view controller deallocates
  44. }
  45. override func viewDidAppear(_ animated: Bool) {
  46. setupUI()
  47. }
  48. private func setupPreparingOverlay() {
  49. // full‐screen semi‐transparent background
  50. preparingView = UIView(frame: view.bounds)
  51. preparingView.backgroundColor = UIColor(white: 0, alpha: 0.5)
  52. preparingView.isHidden = true
  53. // spinner
  54. activityIndicator = UIActivityIndicatorView(style: .large)
  55. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  56. preparingView.addSubview(activityIndicator)
  57. // label
  58. preparingLabel = UILabel()
  59. preparingLabel.translatesAutoresizingMaskIntoConstraints = false
  60. preparingLabel.text = "Preparing…"
  61. preparingLabel.textColor = .white
  62. preparingLabel.font = UIFont.systemFont(ofSize: 17, weight: .medium)
  63. preparingView.addSubview(preparingLabel)
  64. vcHandleVideo.view.addSubview(preparingView)
  65. // constraints: center spinner, label below
  66. NSLayoutConstraint.activate([
  67. activityIndicator.centerXAnchor.constraint(equalTo: preparingView.centerXAnchor),
  68. activityIndicator.centerYAnchor.constraint(equalTo: preparingView.centerYAnchor, constant: -10),
  69. preparingLabel.topAnchor.constraint(equalTo: activityIndicator.bottomAnchor, constant: 12),
  70. preparingLabel.centerXAnchor.constraint(equalTo: preparingView.centerXAnchor)
  71. ])
  72. }
  73. private func showPreparingOverlay(_ show: Bool) {
  74. preparingView.isHidden = !show
  75. if show {
  76. activityIndicator.startAnimating()
  77. self.view.isUserInteractionEnabled = false
  78. } else {
  79. activityIndicator.stopAnimating()
  80. self.view.isUserInteractionEnabled = true
  81. }
  82. }
  83. func setupUI() {
  84. let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelAction))
  85. cancelButton.tintColor = .label
  86. self.navigationItem.leftBarButtonItem = cancelButton
  87. // Search Bar (Right)
  88. searchBar.placeholder = "Search"
  89. searchBar.delegate = self
  90. searchBar.sizeToFit()
  91. self.navigationItem.titleView = searchBar
  92. self.navigationController?.navigationBar.backgroundColor = .systemBackground
  93. self.navigationController?.navigationBar.tintColor = .label
  94. // TableView Setup
  95. tableView.translatesAutoresizingMaskIntoConstraints = false
  96. tableView.delegate = self
  97. tableView.dataSource = self
  98. tableView.register(ContactCell.self, forCellReuseIdentifier: "ContactCell")
  99. tableView.separatorStyle = .singleLine
  100. view.addSubview(tableView)
  101. // Auto Layout Constraints
  102. NSLayoutConstraint.activate([
  103. tableView.topAnchor.constraint(equalTo: view.topAnchor),
  104. tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  105. tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  106. tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  107. ])
  108. }
  109. func loadCustomContacts() {
  110. if let userDefaults = UserDefaults(suiteName: nameGroupShare),
  111. let value = userDefaults.string(forKey: "shareContacts") {
  112. if let jsonData = value.data(using: .utf8) {
  113. do {
  114. if let jsonArray = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String: Any]] {
  115. for json in jsonArray {
  116. let id = json["id"] as? String ?? ""
  117. let name = json["name"] as? String ?? ""
  118. let imageId = json["image"] as? String ?? ""
  119. let type = json["type"] as? Int ?? 0
  120. var profileImage = type == 0 ? UIImage(systemName: "person.fill") : UIImage(systemName: "bubble.right.fill")
  121. if !imageId.isEmpty {
  122. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: nameGroupShare) {
  123. let sharedFileURL = appGroupURL.appendingPathComponent(imageId)
  124. if FileManager.default.fileExists(atPath: sharedFileURL.path) {
  125. profileImage = UIImage(contentsOfFile: sharedFileURL.path)
  126. }
  127. }
  128. }
  129. contacts.append(Contact(id: id, name: name, profileImage: profileImage, imageId: imageId, typeContact: "\(type)"))
  130. }
  131. filteredContacts = contacts
  132. tableView.reloadData()
  133. }
  134. } catch {
  135. print("Error parsing JSON: \(error)")
  136. }
  137. }
  138. }
  139. }
  140. // TableView DataSource Methods
  141. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  142. return filteredContacts.count
  143. }
  144. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  145. return 60
  146. }
  147. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  148. let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath) as! ContactCell
  149. cell.separatorInset = UIEdgeInsets(top: 0, left: 65, bottom: 0, right: 25)
  150. let contact = filteredContacts[indexPath.row]
  151. cell.configure(with: contact)
  152. return cell
  153. }
  154. // Handle Contact Selection
  155. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  156. tableView.deselectRow(at: indexPath, animated: true)
  157. selectedContact = filteredContacts[indexPath.row]
  158. handleSharedContent(selectedContact)
  159. }
  160. // Cancel Button Action
  161. @objc func cancelAction() {
  162. self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
  163. }
  164. @objc func sendAction() {
  165. if let userDefaults = UserDefaults(suiteName: nameGroupShare) {
  166. do {
  167. var dataShared: [String: Any] = [:]
  168. dataShared["typeShare"] = typeShareNum
  169. dataShared["typeContact"] = selectedContact.typeContact
  170. dataShared["idContact"] = selectedContact.id
  171. dataShared["data"] = textView.text
  172. if typeShareNum == TypeShare.image {
  173. let compressedImageName = "Nexilis_image_\(Int(Date().timeIntervalSince1970 * 1000))_\(selectedImage != nil ? selectedImage.lastPathComponent.components(separatedBy: ".")[0] : "SS_Image").jpeg"
  174. let thumbName = "THUMB_Nexilis_image_\(Int(Date().timeIntervalSince1970 * 1000))_\(selectedImage != nil ? selectedImage.lastPathComponent.components(separatedBy: ".")[0] : "SS_Image").jpeg"
  175. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: nameGroupShare) {
  176. let sharedImageURL = appGroupURL.appendingPathComponent(compressedImageName)
  177. let sharedThumbURL = appGroupURL.appendingPathComponent(thumbName)
  178. if selectedImage != nil {
  179. try? UIImage(contentsOfFile: selectedImage.path)?.jpegData(compressionQuality: 0.25)?.write(to: sharedThumbURL)
  180. if let dataImage = UIImage(contentsOfFile: selectedImage.path)?.jpegData(compressionQuality: 1.0) {
  181. if let compressed = compressImageLikeWhatsApp(UIImage(data: dataImage) ?? UIImage()) {
  182. try? compressed.write(to: sharedImageURL)
  183. }
  184. }
  185. } else {
  186. try? selectedImageTypeImage?.jpegData(compressionQuality: 0.25)?.write(to: sharedThumbURL)
  187. if let dataImage = selectedImageTypeImage?.jpegData(compressionQuality: 1.0) {
  188. if let compressed = compressImageLikeWhatsApp(UIImage(data: dataImage) ?? UIImage()) {
  189. try? compressed.write(to: sharedImageURL)
  190. }
  191. }
  192. }
  193. }
  194. dataShared["thumb"] = thumbName
  195. dataShared["image"] = compressedImageName
  196. let jsonData = try JSONSerialization.data(withJSONObject: dataShared, options: .prettyPrinted)
  197. if let jsonString = String(data: jsonData, encoding: .utf8) {
  198. userDefaults.set(jsonString, forKey: "sharedItem")
  199. userDefaults.synchronize()
  200. let notificationName = "realtimeShareExtensionNexilis" as CFString
  201. CFNotificationCenterPostNotification(
  202. CFNotificationCenterGetDarwinNotifyCenter(),
  203. CFNotificationName(notificationName),
  204. nil,
  205. nil,
  206. true
  207. )
  208. }
  209. } else if typeShareNum == TypeShare.video {
  210. showPreparingOverlay(true)
  211. let dispatchGroup = DispatchGroup()
  212. dispatchGroup.enter()
  213. let compressedURL = NSURL.fileURL(withPath: NSTemporaryDirectory() + UUID().uuidString + ".mp4")
  214. compressVideo(inputURL: selectedVideo,outputURL: compressedURL) { exportSession in
  215. guard let session = exportSession else {
  216. return
  217. }
  218. if session.status == .completed {
  219. dispatchGroup.leave()
  220. guard let compressedData = try? Data(contentsOf: compressedURL) else {
  221. return
  222. }
  223. self.sendVideoToMainApp(compressedData, dataShared)
  224. }
  225. }
  226. dispatchGroup.notify(queue: .main) {
  227. self.showPreparingOverlay(false)
  228. }
  229. } else if typeShareNum == TypeShare.file || typeShareNum == TypeShare.audio {
  230. let fileName = selectedFile.lastPathComponent
  231. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: nameGroupShare) {
  232. let sharedFileURL = appGroupURL.appendingPathComponent(fileName)
  233. try? Data(contentsOf: selectedFile).write(to: sharedFileURL)
  234. }
  235. dataShared[typeShareNum == TypeShare.audio ? "audio" : "file"] = fileName
  236. let jsonData = try JSONSerialization.data(withJSONObject: dataShared, options: .prettyPrinted)
  237. if let jsonString = String(data: jsonData, encoding: .utf8) {
  238. userDefaults.set(jsonString, forKey: "sharedItem")
  239. userDefaults.synchronize()
  240. let notificationName = "realtimeShareExtensionNexilis" as CFString
  241. CFNotificationCenterPostNotification(
  242. CFNotificationCenterGetDarwinNotifyCenter(),
  243. CFNotificationName(notificationName),
  244. nil,
  245. nil,
  246. true
  247. )
  248. }
  249. } else {
  250. let jsonData = try JSONSerialization.data(withJSONObject: dataShared, options: .prettyPrinted)
  251. if let jsonString = String(data: jsonData, encoding: .utf8) {
  252. userDefaults.set(jsonString, forKey: "sharedItem")
  253. userDefaults.synchronize()
  254. let notificationName = "realtimeShareExtensionNexilis" as CFString
  255. CFNotificationCenterPostNotification(
  256. CFNotificationCenterGetDarwinNotifyCenter(),
  257. CFNotificationName(notificationName),
  258. nil,
  259. nil,
  260. true
  261. )
  262. }
  263. }
  264. if typeShareNum != TypeShare.video {
  265. self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
  266. }
  267. } catch {
  268. }
  269. }
  270. // self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
  271. }
  272. private func sendVideoToMainApp(_ data: Data, _ dataShared: [String: Any]) {
  273. do {
  274. var dataShared = dataShared
  275. let originalVideoName = self.selectedVideo.lastPathComponent
  276. let renamedVideoName = "Nexilis_video_\(Int(Date().timeIntervalSince1970 * 1000))_\(originalVideoName.components(separatedBy: ".")[0]).mp4"
  277. let thumbName = "THUMB_Nexilis_video_\(Int(Date().timeIntervalSince1970 * 1000))_\(originalVideoName.components(separatedBy: ".")[0]).jpeg"
  278. if let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: nameGroupShare) {
  279. let sharedVideoURL = appGroupURL.appendingPathComponent(renamedVideoName)
  280. let sharedThumbURL = appGroupURL.appendingPathComponent(thumbName)
  281. try? data.write(to: sharedVideoURL)
  282. let asset = AVURLAsset(url: self.selectedVideo, options: nil)
  283. let imgGenerator = AVAssetImageGenerator(asset: asset)
  284. imgGenerator.appliesPreferredTrackTransform = true
  285. let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil)
  286. let thumbnail = UIImage(cgImage: cgImage)
  287. try? thumbnail.jpegData(compressionQuality: 1.0)?.write(to: sharedThumbURL)
  288. dataShared["thumb"] = thumbName
  289. dataShared["video"] = renamedVideoName
  290. let jsonData = try JSONSerialization.data(withJSONObject: dataShared, options: .prettyPrinted)
  291. if let jsonString = String(data: jsonData, encoding: .utf8) {
  292. let userDefaults = UserDefaults(suiteName: nameGroupShare)
  293. userDefaults!.set(jsonString, forKey: "sharedItem")
  294. userDefaults!.synchronize()
  295. let notificationName = "realtimeShareExtensionNexilis" as CFString
  296. CFNotificationCenterPostNotification(
  297. CFNotificationCenterGetDarwinNotifyCenter(),
  298. CFNotificationName(notificationName),
  299. nil,
  300. nil,
  301. true
  302. )
  303. }
  304. }
  305. self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
  306. } catch {
  307. }
  308. }
  309. func compressImageLikeWhatsApp(_ image: UIImage, maxFileSizeMB: Double = 1.0, maxDimension: CGFloat = 1280) -> Data? {
  310. let resizedImage = resizeImage(image: image, maxDimension: maxDimension)
  311. var compressedData = resizedImage.jpegData(compressionQuality: 0.7) ?? Data()
  312. var imageSizeMB = Double(compressedData.count) / (1024.0 * 1024.0)
  313. while imageSizeMB > maxFileSizeMB {
  314. guard let tempImage = UIImage(data: compressedData) else { break }
  315. compressedData = tempImage.jpegData(compressionQuality: 0.5) ?? compressedData
  316. imageSizeMB = Double(compressedData.count) / (1024.0 * 1024.0)
  317. print("Compressed to: \(imageSizeMB) MB")
  318. }
  319. return compressedData
  320. }
  321. func resizeImage(image: UIImage, maxDimension: CGFloat) -> UIImage {
  322. let size = image.size
  323. let aspectRatio = size.width / size.height
  324. var newSize: CGSize
  325. if aspectRatio > 1 {
  326. newSize = CGSize(width: maxDimension, height: maxDimension / aspectRatio)
  327. } else {
  328. newSize = CGSize(width: maxDimension * aspectRatio, height: maxDimension)
  329. }
  330. let renderer = UIGraphicsImageRenderer(size: newSize)
  331. return renderer.image { _ in
  332. image.draw(in: CGRect(origin: .zero, size: newSize))
  333. }
  334. }
  335. func compressVideo(inputURL: URL,
  336. outputURL: URL,
  337. handler:@escaping (_ exportSession: AVAssetExportSession?) -> Void) {
  338. let urlAsset = AVURLAsset(url: inputURL, options: nil)
  339. guard let exportSession = AVAssetExportSession(asset: urlAsset,
  340. presetName: AVAssetExportPresetMediumQuality) else {
  341. handler(nil)
  342. return
  343. }
  344. exportSession.outputURL = outputURL
  345. exportSession.outputFileType = .mp4
  346. exportSession.shouldOptimizeForNetworkUse = true
  347. exportSession.exportAsynchronously {
  348. handler(exportSession)
  349. }
  350. }
  351. @objc func backAction() {
  352. if let previewView = previewView {
  353. previewView.stopVideo()
  354. }
  355. self.dismiss(animated: false, completion: nil)
  356. }
  357. // SearchBar Delegate Methods
  358. func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
  359. if searchText.isEmpty {
  360. filteredContacts = contacts
  361. } else {
  362. filteredContacts = contacts.filter { $0.name.lowercased().contains(searchText.lowercased()) }
  363. }
  364. tableView.reloadData()
  365. }
  366. private func registerKeyboardNotifications() {
  367. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
  368. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
  369. }
  370. @objc private func keyboardWillShow(_ notification: Notification) {
  371. if let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
  372. let keyboardHeight = keyboardFrame.height
  373. let info:NSDictionary = notification.userInfo! as NSDictionary
  374. let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
  375. updateTextViewBottomConstraint(-keyboardHeight - 20, duration)
  376. }
  377. }
  378. @objc private func keyboardWillHide(_ notification: Notification) {
  379. let info:NSDictionary = notification.userInfo! as NSDictionary
  380. let duration: CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber as! CGFloat
  381. updateTextViewBottomConstraint(-20, duration) // Reset bottom constraint
  382. }
  383. private func updateTextViewBottomConstraint(_ constant: CGFloat, _ duration: CGFloat) {
  384. if typeShareNum == TypeShare.text {
  385. textViewBottomConstraint?.constant = constant
  386. } else {
  387. containerBottomConstraint?.constant = constant + 20
  388. }
  389. UIView.animate(withDuration: TimeInterval(duration)) { // Smooth animation
  390. self.view.layoutIfNeeded()
  391. }
  392. }
  393. func textViewDidChange(_ textView: UITextView) {
  394. vcHandleText.navigationItem.rightBarButtonItem?.isEnabled = !textView.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
  395. }
  396. func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  397. if text == "\n" {
  398. textView.resignFirstResponder()
  399. return false
  400. }
  401. return true
  402. }
  403. func textViewDidChangeSelection(_ textView: UITextView) {
  404. if typeShareNum == TypeShare.text {
  405. return
  406. }
  407. let cursorPosition = textView.caretRect(for: textView.selectedTextRange!.start).origin
  408. let doubleCurrentLine = cursorPosition.y / textView.font!.lineHeight
  409. if doubleCurrentLine.isFinite {
  410. let currentLine = Int(doubleCurrentLine)
  411. UIView.animate(withDuration: 0.3) {
  412. let numberOfLines = textView.textContainer.lineBreakMode == .byWordWrapping ? Int(textView.contentSize.height / textView.font!.lineHeight) - 1 : 1
  413. if currentLine == 0 && numberOfLines == 1 {
  414. self.heightTextView?.constant = 45
  415. } else if currentLine >= 4 {
  416. self.heightTextView?.constant = 95.0
  417. } else if currentLine < 4 && numberOfLines < 5 {
  418. self.heightTextView?.constant = textView.contentSize.height
  419. }
  420. }
  421. }
  422. }
  423. func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  424. return 1
  425. }
  426. func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
  427. return selectedFile as QLPreviewItem
  428. }
  429. private func buildAppearance(_ contact: Contact, _ viewVc: UIView) {
  430. viewVc.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .black : .white
  431. let buttonClose = UIButton(type: .system)
  432. buttonClose.setImage(UIImage(systemName: "xmark.circle.fill")?.withConfiguration(UIImage.SymbolConfiguration(pointSize: 40)), for: .normal)
  433. buttonClose.tintColor = .gray.withAlphaComponent(0.8)
  434. buttonClose.imageView?.contentMode = .scaleAspectFit
  435. buttonClose.clipsToBounds = true
  436. buttonClose.addTarget(self, action: #selector(backAction), for: .touchUpInside)
  437. viewVc.addSubview(buttonClose)
  438. buttonClose.translatesAutoresizingMaskIntoConstraints = false
  439. NSLayoutConstraint.activate([
  440. buttonClose.leadingAnchor.constraint(equalTo: viewVc.leadingAnchor, constant: 20.0),
  441. buttonClose.topAnchor.constraint(equalTo: viewVc.topAnchor, constant: 20.0),
  442. buttonClose.widthAnchor.constraint(equalToConstant: 40.0),
  443. buttonClose.heightAnchor.constraint(equalToConstant: 40.0),
  444. ])
  445. let containerView = UIView()
  446. containerView.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .black : .white
  447. viewVc.addSubview(containerView)
  448. containerView.translatesAutoresizingMaskIntoConstraints = false
  449. NSLayoutConstraint.activate([
  450. containerView.leadingAnchor.constraint(equalTo: viewVc.leadingAnchor),
  451. containerView.trailingAnchor.constraint(equalTo: viewVc.trailingAnchor),
  452. containerView.heightAnchor.constraint(equalToConstant: 55)
  453. ])
  454. containerBottomConstraint = containerView.bottomAnchor.constraint(equalTo: viewVc.bottomAnchor)
  455. containerBottomConstraint?.isActive = true
  456. let containerTo = UIView()
  457. containerView.addSubview(containerTo)
  458. containerTo.translatesAutoresizingMaskIntoConstraints = false
  459. containerTo.layer.cornerRadius = 8
  460. containerTo.clipsToBounds = true
  461. containerTo.backgroundColor = .darkGray
  462. NSLayoutConstraint.activate([
  463. containerTo.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 15),
  464. containerTo.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10),
  465. containerTo.heightAnchor.constraint(equalToConstant: 30),
  466. containerTo.widthAnchor.constraint(greaterThanOrEqualToConstant: 50)
  467. ])
  468. let textTo = UILabel()
  469. containerTo.addSubview(textTo)
  470. textTo.text = contact.name
  471. textTo.textColor = .white
  472. textTo.font = .systemFont(ofSize: 15)
  473. textTo.textAlignment = .center
  474. textTo.translatesAutoresizingMaskIntoConstraints = false
  475. NSLayoutConstraint.activate([
  476. textTo.leadingAnchor.constraint(equalTo: containerTo.leadingAnchor, constant: 10),
  477. textTo.trailingAnchor.constraint(equalTo: containerTo.trailingAnchor, constant: -10),
  478. textTo.centerYAnchor.constraint(equalTo: containerTo.centerYAnchor)
  479. ])
  480. let buttonTo = UIButton(type: .system)
  481. buttonTo.setImage(UIImage(systemName: "paperplane.circle.fill")?.withConfiguration(UIImage.SymbolConfiguration(pointSize: 35)), for: .normal)
  482. buttonTo.tintColor = .systemBlue
  483. buttonTo.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
  484. containerView.addSubview(buttonTo)
  485. buttonTo.translatesAutoresizingMaskIntoConstraints = false
  486. NSLayoutConstraint.activate([
  487. buttonTo.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -15),
  488. buttonTo.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10),
  489. buttonTo.widthAnchor.constraint(equalToConstant: 35),
  490. buttonTo.heightAnchor.constraint(equalToConstant: 35),
  491. ])
  492. textView = UITextView()
  493. viewVc.addSubview(textView)
  494. textView.textColor = .label
  495. textView.font = .systemFont(ofSize: 17)
  496. textView.textContainerInset = UIEdgeInsets(top: 10.5, left: 15, bottom: 10.5, right: 15)
  497. textView.translatesAutoresizingMaskIntoConstraints = false
  498. textView.layer.cornerRadius = 22.5
  499. textView.clipsToBounds = true
  500. textView.layer.borderColor = UIColor.gray.cgColor
  501. textView.layer.borderWidth = 1
  502. textView.delegate = self
  503. NSLayoutConstraint.activate([
  504. textView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -15),
  505. textView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 15),
  506. textView.bottomAnchor.constraint(equalTo: containerView.topAnchor, constant: -20),
  507. ])
  508. heightTextView = textView.heightAnchor.constraint(equalToConstant: 45)
  509. heightTextView?.isActive = true
  510. }
  511. func handleSharedContent(_ contact: Contact) {
  512. guard let extensionItem = extensionContext?.inputItems.first as? NSExtensionItem else { return }
  513. for attachment in extensionItem.attachments ?? [] {
  514. if attachment.hasItemConformingToTypeIdentifier(UTType.text.identifier) {
  515. // Handle Text
  516. attachment.loadItem(forTypeIdentifier: UTType.text.identifier, options: nil) { (textItem, error) in
  517. if let sharedText = textItem as? String {
  518. DispatchQueue.main.async { [self] in
  519. typeShareNum = TypeShare.text
  520. if let viewVc = vcHandleText.view {
  521. viewVc.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .black : .white
  522. self.navigationItem.backButtonTitle = ""
  523. let sendButton = UIBarButtonItem(title: "Send", style: .plain, target: self, action: #selector(sendAction))
  524. sendButton.tintColor = .label
  525. vcHandleText.navigationItem.rightBarButtonItem = sendButton
  526. let containerTo = UIView()
  527. viewVc.addSubview(containerTo)
  528. containerTo.translatesAutoresizingMaskIntoConstraints = false
  529. NSLayoutConstraint.activate([
  530. containerTo.topAnchor.constraint(equalTo: viewVc.safeAreaLayoutGuide.topAnchor, constant: 8.0),
  531. containerTo.leadingAnchor.constraint(equalTo: viewVc.leadingAnchor),
  532. containerTo.trailingAnchor.constraint(equalTo: viewVc.trailingAnchor),
  533. containerTo.heightAnchor.constraint(equalToConstant: 44)
  534. ])
  535. containerTo.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .systemBackground : .gray
  536. let textTo = UILabel()
  537. containerTo.addSubview(textTo)
  538. textTo.translatesAutoresizingMaskIntoConstraints = false
  539. NSLayoutConstraint.activate([
  540. textTo.leadingAnchor.constraint(equalTo: viewVc.leadingAnchor, constant: 10.0),
  541. textTo.centerYAnchor.constraint(equalTo: containerTo.centerYAnchor)
  542. ])
  543. textTo.text = "To: \(contact.name)"
  544. textTo.font = .systemFont(ofSize: 13)
  545. textTo.textColor = .label
  546. textView = UITextView()
  547. textView.translatesAutoresizingMaskIntoConstraints = false
  548. textView.isScrollEnabled = true
  549. textView.text = sharedText
  550. textView.textColor = .label
  551. textView.font = .systemFont(ofSize: 16)
  552. textView.backgroundColor = .clear
  553. textView.delegate = self
  554. viewVc.addSubview(textView)
  555. NSLayoutConstraint.activate([
  556. textView.leadingAnchor.constraint(equalTo: viewVc.leadingAnchor),
  557. textView.trailingAnchor.constraint(equalTo: viewVc.trailingAnchor),
  558. textView.topAnchor.constraint(equalTo: containerTo.bottomAnchor, constant: 5)
  559. ])
  560. textViewBottomConstraint = textView.bottomAnchor.constraint(equalTo: viewVc.bottomAnchor, constant: -20)
  561. textViewBottomConstraint?.isActive = true
  562. self.navigationController?.pushViewController(vcHandleText, animated: true)
  563. }
  564. }
  565. }
  566. }
  567. return
  568. } else if attachment.hasItemConformingToTypeIdentifier(UTType.image.identifier) {
  569. // Handle Image
  570. attachment.loadItem(forTypeIdentifier: UTType.image.identifier, options: nil) { (imageItem, error) in
  571. if let imageURL = imageItem as? URL {
  572. DispatchQueue.main.async { [self] in
  573. typeShareNum = TypeShare.image
  574. selectedImage = imageURL
  575. if let viewVc = vcHandleImage.view {
  576. let imageView = UIImageView()
  577. imageView.image = UIImage(contentsOfFile: imageURL.path)
  578. imageView.contentMode = .scaleAspectFit
  579. imageView.clipsToBounds = true
  580. viewVc.addSubview(imageView)
  581. imageView.frame = CGRect(x: 0, y: 70, width: viewVc.bounds.size.width, height: self.view.bounds.height - 150)
  582. buildAppearance(contact, viewVc)
  583. vcHandleImage.modalPresentationStyle = .fullScreen
  584. self.navigationController?.present(vcHandleImage, animated: true)
  585. }
  586. }
  587. } else if let image = imageItem as? UIImage {
  588. DispatchQueue.main.async { [self] in
  589. typeShareNum = TypeShare.image
  590. selectedImageTypeImage = image
  591. if let viewVc = vcHandleImage.view {
  592. let imageView = UIImageView()
  593. imageView.image = image
  594. imageView.contentMode = .scaleAspectFit
  595. imageView.clipsToBounds = true
  596. viewVc.addSubview(imageView)
  597. imageView.frame = CGRect(x: 0, y: 70, width: viewVc.bounds.size.width, height: self.view.bounds.height - 150)
  598. buildAppearance(contact, viewVc)
  599. vcHandleImage.modalPresentationStyle = .fullScreen
  600. self.navigationController?.present(vcHandleImage, animated: true)
  601. }
  602. }
  603. }
  604. }
  605. return
  606. } else if attachment.hasItemConformingToTypeIdentifier(UTType.movie.identifier) {
  607. // Handle Video
  608. attachment.loadItem(forTypeIdentifier: UTType.movie.identifier, options: nil) { (videoItem, error) in
  609. if let videoURL = videoItem as? URL {
  610. DispatchQueue.main.async { [self] in
  611. typeShareNum = TypeShare.video
  612. selectedVideo = videoURL
  613. if let viewVc = vcHandleVideo.view {
  614. previewView = VideoPreviewView(frame: CGRect(x: 0, y: 70, width: viewVc.bounds.size.width, height: self.view.bounds.height - 190))
  615. viewVc.addSubview(previewView!)
  616. previewView!.configure(with: videoURL)
  617. buildAppearance(contact, viewVc)
  618. vcHandleVideo.modalPresentationStyle = .fullScreen
  619. self.navigationController?.present(vcHandleVideo, animated: true)
  620. setupPreparingOverlay()
  621. }
  622. }
  623. }
  624. }
  625. return
  626. } else if isSupportedAudioFormat(attachment: attachment) {
  627. attachment.loadItem(forTypeIdentifier: UTType.data.identifier, options: nil) { (fileItem, error) in
  628. if let fileURL = fileItem as? URL {
  629. self.getExactAudioDuration(url: fileURL) { durationFormatted in
  630. let alert = UIAlertController(title: "Send to: \(contact.name)?", message: "File size: \(self.getExactFileSize(url: fileURL)) KB\nDuration: \(durationFormatted)", preferredStyle: .alert)
  631. alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
  632. alert.addAction(UIAlertAction(title: "Send", style: .default, handler: {[self] _ in
  633. typeShareNum = TypeShare.audio
  634. selectedFile = fileURL
  635. sendAction()
  636. }))
  637. DispatchQueue.main.async {
  638. self.navigationController?.present(alert, animated: true, completion: nil)
  639. }
  640. }
  641. }
  642. }
  643. } else if attachment.hasItemConformingToTypeIdentifier(UTType.data.identifier) {
  644. // Handle Other Files
  645. attachment.loadItem(forTypeIdentifier: UTType.data.identifier, options: nil) { (fileItem, error) in
  646. if let fileURL = fileItem as? URL {
  647. DispatchQueue.main.async { [self] in
  648. typeShareNum = TypeShare.file
  649. selectedFile = fileURL
  650. if let viewVc = vcHandleFile.view {
  651. vcHandleFile.addChild(previewController)
  652. previewController.dataSource = self
  653. previewController.view.frame = CGRect(x: 0, y: 70, width: viewVc.bounds.size.width, height: viewVc.bounds.size.height - 190)
  654. previewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  655. viewVc.addSubview(previewController.view)
  656. previewController.didMove(toParent: vcHandleFile)
  657. buildAppearance(contact, viewVc)
  658. vcHandleFile.modalPresentationStyle = .fullScreen
  659. self.navigationController?.present(vcHandleFile, animated: true)
  660. }
  661. }
  662. } else {
  663. attachment.loadItem(forTypeIdentifier: "public.file-url", options: nil) { (urlData, error) in
  664. if let url = urlData as? URL {
  665. DispatchQueue.main.async { [self] in
  666. typeShareNum = TypeShare.file
  667. selectedFile = url
  668. if let viewVc = vcHandleFile.view {
  669. vcHandleFile.addChild(previewController)
  670. previewController.dataSource = self
  671. previewController.view.frame = CGRect(x: 0, y: 70, width: viewVc.bounds.size.width, height: viewVc.bounds.size.height - 190)
  672. previewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  673. viewVc.addSubview(previewController.view)
  674. previewController.didMove(toParent: vcHandleFile)
  675. buildAppearance(contact, viewVc)
  676. vcHandleFile.modalPresentationStyle = .fullScreen
  677. self.navigationController?.present(vcHandleFile, animated: true)
  678. }
  679. }
  680. }
  681. }
  682. }
  683. }
  684. return
  685. }
  686. }
  687. }
  688. func isSupportedAudioFormat(attachment: NSItemProvider) -> Bool {
  689. var supportedAudioTypes: [UTType] = [
  690. .mpeg4Audio,
  691. .mp3,
  692. .aiff,
  693. .wav,
  694. .appleProtectedMPEG4Audio
  695. ]
  696. if let flacType = UTType(filenameExtension: "flac") {
  697. supportedAudioTypes.append(flacType)
  698. }
  699. if let oggType = UTType(filenameExtension: "ogg") {
  700. supportedAudioTypes.append(oggType)
  701. }
  702. if let cafType = UTType(filenameExtension: "caf") {
  703. supportedAudioTypes.append(cafType)
  704. }
  705. if let opusType = UTType(filenameExtension: "opus") {
  706. supportedAudioTypes.append(opusType)
  707. }
  708. return supportedAudioTypes.contains { attachment.hasItemConformingToTypeIdentifier($0.identifier) }
  709. }
  710. func getExactFileSize(url: URL) -> Int64 {
  711. do {
  712. let fileData = try Data(contentsOf: url)
  713. let fileSizeInBytes = Int64(fileData.count)
  714. return (fileSizeInBytes + 1023) / 1000 // Using 1000 instead of 1024
  715. } catch {
  716. print("Error reading file size: \(error)")
  717. }
  718. return 0
  719. }
  720. func getExactAudioDuration(url: URL, completion: @escaping (String) -> Void) {
  721. let asset = AVURLAsset(url: url)
  722. asset.loadValuesAsynchronously(forKeys: ["duration"]) {
  723. DispatchQueue.main.async {
  724. let durationSeconds = CMTimeGetSeconds(asset.duration)
  725. // Apply rounding logic like WhatsApp
  726. let roundedDuration = Int(durationSeconds.rounded(.up))
  727. let minutes = roundedDuration / 60
  728. let seconds = roundedDuration % 60
  729. let formattedDuration = String(format: "%d:%02d", minutes, seconds)
  730. completion(formattedDuration)
  731. }
  732. }
  733. }
  734. }
  735. struct Contact {
  736. let id: String
  737. let name: String
  738. let profileImage: UIImage?
  739. let imageId: String
  740. let typeContact: String
  741. }
  742. class TypeShare {
  743. static let text = 1
  744. static let image = 2
  745. static let video = 3
  746. static let file = 4
  747. static let audio = 5
  748. }
  749. class VideoPreviewView: UIView {
  750. private var player: AVPlayer?
  751. private var playerLayer: AVPlayerLayer?
  752. private var isPlaying = false
  753. private let playPauseButton: UIButton = {
  754. let button = UIButton(type: .system)
  755. button.setImage(UIImage(systemName: "play.fill"), for: .normal)
  756. button.tintColor = .white
  757. button.backgroundColor = UIColor.black.withAlphaComponent(0.5)
  758. button.layer.cornerRadius = 25
  759. button.clipsToBounds = true
  760. return button
  761. }()
  762. override init(frame: CGRect) {
  763. super.init(frame: frame)
  764. setupUI()
  765. }
  766. required init?(coder: NSCoder) {
  767. super.init(coder: coder)
  768. setupUI()
  769. }
  770. private func setupUI() {
  771. playPauseButton.frame = CGRect(x: (bounds.width - 50) / 2, y: (bounds.height - 50) / 2, width: 50, height: 50)
  772. playPauseButton.addTarget(self, action: #selector(playPauseTapped), for: .touchUpInside)
  773. addSubview(playPauseButton)
  774. }
  775. func configure(with url: URL) {
  776. // Setup AVPlayer
  777. player = AVPlayer(url: url)
  778. playerLayer = AVPlayerLayer(player: player)
  779. playerLayer?.frame = bounds
  780. playerLayer?.videoGravity = .resizeAspect
  781. if let playerLayer = playerLayer {
  782. layer.insertSublayer(playerLayer, below: playPauseButton.layer)
  783. }
  784. // Observe when video ends
  785. NotificationCenter.default.addObserver(self, selector: #selector(videoDidEnd), name: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem)
  786. }
  787. @objc private func playPauseTapped() {
  788. guard let player = player else { return }
  789. if isPlaying {
  790. player.pause()
  791. playPauseButton.setImage(UIImage(systemName: "play.fill"), for: .normal)
  792. } else {
  793. player.play()
  794. playPauseButton.setImage(UIImage(systemName: "pause.fill"), for: .normal)
  795. }
  796. isPlaying.toggle()
  797. }
  798. @objc private func videoDidEnd() {
  799. guard let player = player else { return }
  800. // Replay video from start
  801. player.seek(to: .zero)
  802. player.play()
  803. playPauseButton.setImage(UIImage(systemName: "pause.fill"), for: .normal)
  804. isPlaying = true
  805. }
  806. func stopVideo() {
  807. player?.pause()
  808. player?.seek(to: .zero)
  809. playPauseButton.setImage(UIImage(systemName: "play.fill"), for: .normal)
  810. isPlaying = false
  811. }
  812. deinit {
  813. NotificationCenter.default.removeObserver(self)
  814. }
  815. }
  816. class ContactCell: UITableViewCell {
  817. let profileImageView = UIImageView()
  818. let nameLabel = UILabel()
  819. override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
  820. super.init(style: style, reuseIdentifier: reuseIdentifier)
  821. setupUI()
  822. }
  823. required init?(coder: NSCoder) {
  824. fatalError("init(coder:) has not been implemented")
  825. }
  826. func setupUI() {
  827. profileImageView.translatesAutoresizingMaskIntoConstraints = false
  828. profileImageView.layer.cornerRadius = 25
  829. profileImageView.clipsToBounds = true
  830. profileImageView.contentMode = .center
  831. nameLabel.translatesAutoresizingMaskIntoConstraints = false
  832. nameLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
  833. contentView.addSubview(profileImageView)
  834. contentView.addSubview(nameLabel)
  835. NSLayoutConstraint.activate([
  836. profileImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15),
  837. profileImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
  838. profileImageView.widthAnchor.constraint(equalToConstant: 50),
  839. profileImageView.heightAnchor.constraint(equalToConstant: 50),
  840. nameLabel.leadingAnchor.constraint(equalTo: profileImageView.trailingAnchor, constant: 15),
  841. nameLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
  842. ])
  843. }
  844. func configure(with contact: Contact) {
  845. nameLabel.text = contact.name
  846. profileImageView.image = contact.profileImage ?? UIImage(systemName: "person.circle")
  847. if !contact.imageId.isEmpty {
  848. profileImageView.contentMode = .scaleAspectFill
  849. }
  850. }
  851. }