NCMainCommon.swift 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  1. //
  2. // NCMainCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 18/07/18.
  6. // Copyright © 2018 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 Foundation
  24. import TLPhotoPicker
  25. class NCMainCommon: NSObject, PhotoEditorDelegate, NCAudioRecorderViewControllerDelegate {
  26. @objc static let sharedInstance: NCMainCommon = {
  27. let instance = NCMainCommon()
  28. return instance
  29. }()
  30. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  31. var metadata: tableMetadata?
  32. lazy var operationQueueReloadDatasource: OperationQueue = {
  33. let queue = OperationQueue()
  34. queue.name = "Reload main datasource queue"
  35. queue.maxConcurrentOperationCount = 1
  36. return queue
  37. }()
  38. //MARK: -
  39. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceFileIDIndexPath: NSDictionary, tableView: UITableView, viewController: UIViewController, serverUrlViewController: String?) {
  40. if viewController.viewIfLoaded?.window == nil {
  41. return
  42. }
  43. guard let dic = notification.userInfo else {
  44. return
  45. }
  46. let account = dic["account"] as? NSString ?? ""
  47. let fileID = dic["fileID"] as? NSString ?? ""
  48. let serverUrl = dic["serverUrl"] as? String ?? ""
  49. let status = dic["status"] as? Int ?? Int(k_taskIdentifierDone)
  50. let progress = dic["progress"] as? CGFloat ?? 0
  51. let totalBytes = dic["totalBytes"] as? Double ?? 0
  52. let totalBytesExpected = dic["totalBytesExpected"] as? Double ?? 0
  53. if (account != self.appDelegate.activeAccount! as NSString) && !(viewController is CCTransfers) {
  54. return
  55. }
  56. if serverUrlViewController != nil && serverUrlViewController! != serverUrl {
  57. return
  58. }
  59. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: fileID)
  60. guard let indexPath = sectionDataSourceFileIDIndexPath.object(forKey: fileID) else {
  61. return
  62. }
  63. if isValidIndexPath(indexPath as! IndexPath, view: tableView) {
  64. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  65. var image = ""
  66. if status == k_metadataStatusInDownload {
  67. image = "↓"
  68. } else if status == k_metadataStatusInUpload {
  69. image = "↑"
  70. }
  71. cell.labelInfoFile?.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  72. cell.transferButton?.progress = progress
  73. }
  74. }
  75. }
  76. @objc func cancelTransferMetadata(_ metadata: tableMetadata, reloadDatasource: Bool) {
  77. var actionReloadDatasource = k_action_NULL
  78. if metadata.session.count == 0 {
  79. return
  80. }
  81. guard let session = CCNetworking.shared().getSessionfromSessionDescription(metadata.session) else {
  82. return
  83. }
  84. // SESSION EXTENSION
  85. if metadata.session == k_download_session_extension || metadata.session == k_upload_session_extension {
  86. if (metadata.session == k_upload_session_extension) {
  87. do {
  88. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  89. } catch { }
  90. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  91. actionReloadDatasource = k_action_DEL
  92. } else {
  93. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  94. actionReloadDatasource = k_action_MOD
  95. }
  96. self.reloadDatasource(ServerUrl: metadata.serverUrl, fileID: metadata.fileID, action: actionReloadDatasource)
  97. return
  98. }
  99. session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  100. var cancel = false
  101. // DOWNLOAD
  102. if metadata.session.count > 0 && metadata.session.contains("download") {
  103. for task in downloadTasks {
  104. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  105. task.cancel()
  106. cancel = true
  107. }
  108. }
  109. if cancel == false {
  110. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  111. }
  112. actionReloadDatasource = k_action_MOD
  113. }
  114. // UPLOAD
  115. if metadata.session.count > 0 && metadata.session.contains("upload") {
  116. for task in uploadTasks {
  117. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  118. task.cancel()
  119. cancel = true
  120. }
  121. }
  122. if cancel == false {
  123. do {
  124. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  125. }
  126. catch { }
  127. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  128. }
  129. actionReloadDatasource = k_action_DEL
  130. }
  131. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  132. self.reloadDatasource(ServerUrl: metadata.serverUrl, fileID: metadata.fileID, action: actionReloadDatasource)
  133. }
  134. }
  135. }
  136. @objc func cancelAllTransfer(view: UIView) {
  137. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  138. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError))
  139. NCUtility.sharedInstance.startActivityIndicator(view: view, bottom: 0)
  140. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  141. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "status != %d AND status != %d", k_metadataStatusNormal, k_metadataStatusHide), sorted: "fileName", ascending: true) {
  142. for metadata in metadatas {
  143. // Modify
  144. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  145. metadata.session = ""
  146. metadata.sessionSelector = ""
  147. metadata.status = Int(k_metadataStatusNormal)
  148. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  149. }
  150. // Cancel Task
  151. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  152. self.cancelTransferMetadata(metadata, reloadDatasource: false)
  153. }
  154. }
  155. }
  156. }
  157. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  158. self.reloadDatasource(ServerUrl: nil, fileID: nil, action: k_action_NULL)
  159. NCUtility.sharedInstance.stopActivityIndicator()
  160. }
  161. }
  162. //MARK: -
  163. func collectionViewCellForItemAt(_ indexPath: IndexPath, collectionView: UICollectionView, cell: UICollectionViewCell, metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, isEditMode: Bool, selectFileID: [String], autoUploadFileName: String, autoUploadDirectory: String, hideButtonMore: Bool, downloadThumbnail: Bool,source: UIViewController) {
  164. var image: UIImage?
  165. var isImagePreviewLoaded = false
  166. // Image Preview
  167. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileName)) {
  168. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileName))
  169. isImagePreviewLoaded = true
  170. } else {
  171. if metadata.iconName.count > 0 {
  172. image = UIImage.init(named: metadata.iconName)
  173. } else {
  174. image = UIImage.init(named: "file")
  175. }
  176. }
  177. // Download preview
  178. if downloadThumbnail {
  179. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: collectionView, indexPath: indexPath)
  180. }
  181. // Share
  182. let sharesLink = appDelegate.sharesLink.object(forKey: serverUrl + metadata.fileName)
  183. let sharesUserAndGroup = appDelegate.sharesUserAndGroup.object(forKey: serverUrl + metadata.fileName)
  184. var isShare = false
  185. var isMounted = false
  186. if metadataFolder != nil {
  187. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  188. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  189. }
  190. if cell is NCListCell {
  191. let cell = cell as! NCListCell
  192. cell.delegate = source as? NCListCellDelegate
  193. cell.fileID = metadata.fileID
  194. cell.indexPath = indexPath
  195. cell.labelTitle.text = metadata.fileNameView
  196. cell.imageStatus.image = nil
  197. cell.imageLocal.image = nil
  198. cell.imageFavorite.image = nil
  199. cell.imageShare.image = nil
  200. cell.hide(buttonMore: hideButtonMore, hideImageShare: true)
  201. if metadata.directory {
  202. if metadata.e2eEncrypted {
  203. image = UIImage.init(named: "folderEncrypted")
  204. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  205. image = UIImage.init(named: "folderAutomaticUpload")
  206. } else if isShare {
  207. image = UIImage.init(named: "folder_shared_with_me")
  208. } else if isMounted {
  209. image = UIImage.init(named: "folder_external")
  210. } else if (sharesUserAndGroup != nil) {
  211. image = UIImage.init(named: "folder_shared_with_me")
  212. } else if (sharesLink != nil) {
  213. image = UIImage.init(named: "folder_public")
  214. } else {
  215. image = UIImage.init(named: "folder")
  216. }
  217. cell.imageItem.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width, height: image!.size.height, color: NCBrandColor.sharedInstance.brandElement)
  218. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  219. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  220. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  221. // Status image: passcode
  222. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  223. cell.imageStatus.image = UIImage.init(named: "passcode")
  224. }
  225. // Local image: offline
  226. if tableDirectory != nil && tableDirectory!.offline {
  227. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  228. }
  229. } else {
  230. cell.imageItem.image = image
  231. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  232. // image Local
  233. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  234. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  235. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  236. else { cell.imageLocal.image = UIImage.init(named: "local") }
  237. }
  238. // Share
  239. if (isShare) {
  240. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  241. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  242. } else if (isMounted) {
  243. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  244. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  245. } else if (sharesLink != nil) {
  246. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  247. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  248. } else if (sharesUserAndGroup != nil) {
  249. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  250. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  251. }
  252. }
  253. // image Favorite
  254. if metadata.favorite {
  255. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  256. }
  257. if isEditMode {
  258. cell.imageItemLeftConstraint.constant = 45
  259. cell.imageSelect.isHidden = false
  260. if selectFileID.contains(metadata.fileID) {
  261. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: NCBrandColor.sharedInstance.brand)
  262. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  263. } else {
  264. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedNo"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  265. cell.backgroundView = nil
  266. }
  267. } else {
  268. cell.imageItemLeftConstraint.constant = 10
  269. cell.imageSelect.isHidden = true
  270. cell.backgroundView = nil
  271. }
  272. // Remove last separator
  273. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  274. cell.separator.isHidden = true
  275. } else {
  276. cell.separator.isHidden = false
  277. }
  278. } else if cell is NCGridCell {
  279. let cell = cell as! NCGridCell
  280. cell.delegate = source as? NCGridCellDelegate
  281. cell.fileID = metadata.fileID
  282. cell.indexPath = indexPath
  283. cell.labelTitle.text = metadata.fileNameView
  284. cell.imageStatus.image = nil
  285. cell.imageLocal.image = nil
  286. cell.imageFavorite.image = nil
  287. cell.imageShare.image = nil
  288. cell.hide(buttonMore: hideButtonMore, hideImageShare: true)
  289. if metadata.directory {
  290. if metadata.e2eEncrypted {
  291. image = UIImage.init(named: "folderEncrypted")
  292. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  293. image = UIImage.init(named: "folderAutomaticUpload")
  294. } else if isShare {
  295. image = UIImage.init(named: "folder_shared_with_me")
  296. } else if isMounted {
  297. image = UIImage.init(named: "folder_external")
  298. } else if (sharesUserAndGroup != nil) {
  299. image = UIImage.init(named: "folder_shared_with_me")
  300. } else if (sharesLink != nil) {
  301. image = UIImage.init(named: "folder_public")
  302. } else {
  303. image = UIImage.init(named: "folder")
  304. }
  305. cell.imageItem.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width, height: image!.size.height, color: NCBrandColor.sharedInstance.brandElement)
  306. cell.imageItem.contentMode = .center
  307. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  308. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  309. // Status image: passcode
  310. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  311. cell.imageStatus.image = UIImage.init(named: "passcode")
  312. }
  313. // Local image: offline
  314. if tableDirectory != nil && tableDirectory!.offline {
  315. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  316. }
  317. } else {
  318. cell.imageItem.image = image
  319. if isImagePreviewLoaded == false {
  320. let width = cell.imageItem.image!.size.width * 2
  321. //let scale = UIScreen.main.scale
  322. cell.imageItem.image = NCUtility.sharedInstance.resizeImage(image: image!, newWidth: width)
  323. cell.imageItem.contentMode = .center
  324. }
  325. // image Local
  326. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  327. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  328. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  329. else { cell.imageLocal.image = UIImage.init(named: "local") }
  330. }
  331. // Share
  332. if (isShare) {
  333. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  334. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  335. } else if (isMounted) {
  336. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  337. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  338. } else if (sharesLink != nil) {
  339. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  340. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  341. } else if (sharesUserAndGroup != nil) {
  342. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  343. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  344. }
  345. }
  346. // image Favorite
  347. if metadata.favorite {
  348. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  349. }
  350. if isEditMode {
  351. cell.imageSelect.isHidden = false
  352. if selectFileID.contains(metadata.fileID) {
  353. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: UIColor.white)
  354. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  355. } else {
  356. cell.imageSelect.isHidden = true
  357. cell.backgroundView = nil
  358. }
  359. } else {
  360. cell.imageSelect.isHidden = true
  361. cell.backgroundView = nil
  362. }
  363. } else if cell is NCGridMediaCell {
  364. let cell = cell as! NCGridMediaCell
  365. cell.imageStatus.image = nil
  366. cell.imageLocal.image = nil
  367. cell.imageFavorite.image = nil
  368. cell.imageItem.image = image
  369. if isImagePreviewLoaded {
  370. // Preview
  371. cell.imageItem.contentMode = .scaleAspectFill
  372. } else {
  373. // Default xcassets
  374. cell.imageItem.contentMode = .scaleAspectFit
  375. }
  376. // image Local
  377. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  378. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  379. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  380. else { cell.imageLocal.image = UIImage.init(named: "local") }
  381. }
  382. // image Favorite
  383. if metadata.favorite {
  384. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  385. }
  386. if isEditMode {
  387. cell.imageSelect.isHidden = false
  388. if selectFileID.contains(metadata.fileID) {
  389. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: NCBrandColor.sharedInstance.brand)
  390. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  391. } else {
  392. cell.imageSelect.isHidden = true
  393. cell.backgroundView = nil
  394. }
  395. } else {
  396. cell.imageSelect.isHidden = true
  397. cell.backgroundView = nil
  398. }
  399. }
  400. }
  401. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String) -> UITableViewCell {
  402. var image: UIImage?
  403. // Create File System
  404. if metadata.directory {
  405. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID)
  406. } else {
  407. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView)
  408. }
  409. // CCCell
  410. if metadata.status == k_metadataStatusNormal {
  411. // NORMAL
  412. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  413. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  414. cell.accessoryType = UITableViewCell.AccessoryType.none
  415. cell.file.image = nil
  416. cell.status.image = nil
  417. cell.favorite.image = nil
  418. cell.shared.image = nil
  419. cell.local.image = nil
  420. cell.shared.isUserInteractionEnabled = false
  421. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  422. // change color selection
  423. let selectionColor = UIView()
  424. selectionColor.backgroundColor = NCBrandColor.sharedInstance.getColorSelectBackgrond()
  425. cell.selectedBackgroundView = selectionColor
  426. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  427. cell.labelTitle.textColor = UIColor.black
  428. cell.labelTitle.text = metadata.fileNameView
  429. // Download preview
  430. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: tableView, indexPath: indexPath)
  431. // Share
  432. let sharesLink = appDelegate.sharesLink.object(forKey: serverUrl + metadata.fileName)
  433. let sharesUserAndGroup = appDelegate.sharesUserAndGroup.object(forKey: serverUrl + metadata.fileName)
  434. var isShare = false
  435. var isMounted = false
  436. if metadataFolder != nil {
  437. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  438. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  439. }
  440. if metadata.directory {
  441. // lable Info
  442. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  443. // File Image & Image Title Segue
  444. if metadata.e2eEncrypted {
  445. image = UIImage.init(named: "folderEncrypted")
  446. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  447. image = UIImage.init(named: "folderAutomaticUpload")
  448. } else if isShare {
  449. image = UIImage.init(named: "folder_shared_with_me")
  450. } else if isMounted {
  451. image = UIImage.init(named: "folder_external")
  452. } else if (sharesUserAndGroup != nil) {
  453. image = UIImage.init(named: "folder_shared_with_me")
  454. } else if (sharesLink != nil) {
  455. image = UIImage.init(named: "folder_public")
  456. } else {
  457. image = UIImage.init(named: "folder")
  458. }
  459. cell.file.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width, height: image!.size.height, color: NCBrandColor.sharedInstance.brandElement)
  460. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  461. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  462. // Local image: offline
  463. if tableDirectory != nil && tableDirectory!.offline {
  464. cell.local.image = UIImage.init(named: "offlineFlag")
  465. }
  466. // Status image: passcode
  467. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  468. cell.status.image = UIImage.init(named: "passcode")
  469. }
  470. } else {
  471. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  472. // Lable Info
  473. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  474. // File Image
  475. if iconFileExists {
  476. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  477. } else {
  478. if metadata.iconName.count > 0 {
  479. cell.file.image = UIImage.init(named: metadata.iconName)
  480. } else {
  481. cell.file.image = UIImage.init(named: "file")
  482. }
  483. }
  484. // Local Image - Offline
  485. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  486. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  487. if tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  488. else { cell.local.image = UIImage.init(named: "local") }
  489. }
  490. // Status image: encrypted
  491. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  492. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  493. cell.status.image = UIImage.init(named: "encrypted")
  494. }
  495. // Share
  496. if (isShare) {
  497. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  498. } else if (isMounted) {
  499. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  500. } else if (sharesLink != nil) {
  501. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  502. } else if (sharesUserAndGroup != nil) {
  503. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  504. }
  505. }
  506. //
  507. // File & Directory
  508. //
  509. // Favorite
  510. if metadata.favorite {
  511. cell.favorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  512. }
  513. // More Image
  514. cell.more.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), multiplier: 1, color: NCBrandColor.sharedInstance.optionItem)
  515. return cell
  516. } else {
  517. // TRASNFER
  518. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  519. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  520. cell.accessoryType = UITableViewCell.AccessoryType.none
  521. cell.file.image = nil
  522. cell.status.image = nil
  523. cell.user.image = nil
  524. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  525. cell.labelTitle.textColor = UIColor.black
  526. cell.labelTitle.text = metadata.fileNameView
  527. cell.transferButton.tintColor = NCBrandColor.sharedInstance.optionItem
  528. var progress: CGFloat = 0.0
  529. var totalBytes: Double = 0.0
  530. //var totalBytesExpected : Double = 0
  531. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.fileID) as? NSArray
  532. if progressArray != nil && progressArray?.count == 3 {
  533. progress = progressArray?.object(at: 0) as! CGFloat
  534. totalBytes = progressArray?.object(at: 1) as! Double
  535. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  536. }
  537. // Write status on Label Info
  538. switch metadata.status {
  539. case Int(k_metadataStatusWaitDownload):
  540. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  541. progress = 0.0
  542. break
  543. case Int(k_metadataStatusInDownload):
  544. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  545. progress = 0.0
  546. break
  547. case Int(k_metadataStatusDownloading):
  548. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  549. break
  550. case Int(k_metadataStatusWaitUpload):
  551. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  552. progress = 0.0
  553. break
  554. case Int(k_metadataStatusInUpload):
  555. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  556. progress = 0.0
  557. break
  558. case Int(k_metadataStatusUploading):
  559. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  560. break
  561. default:
  562. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  563. progress = 0.0
  564. }
  565. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  566. if iconFileExists {
  567. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  568. } else {
  569. if metadata.iconName.count > 0 {
  570. cell.file.image = UIImage.init(named: metadata.iconName)
  571. } else {
  572. cell.file.image = UIImage.init(named: "file")
  573. }
  574. }
  575. // Session Upload Extension
  576. if metadata.session == k_upload_session_extension && (metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading) {
  577. cell.labelTitle.isEnabled = false
  578. cell.labelInfoFile.isEnabled = false
  579. } else {
  580. cell.labelTitle.isEnabled = true
  581. cell.labelInfoFile.isEnabled = true
  582. }
  583. // downloadFile
  584. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  585. //
  586. }
  587. // downloadFile Error
  588. if metadata.status == k_metadataStatusDownloadError {
  589. cell.status.image = UIImage.init(named: "statuserror")
  590. if metadata.sessionError.count == 0 {
  591. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  592. } else {
  593. cell.labelInfoFile.text = metadata.sessionError
  594. }
  595. }
  596. // uploadFile
  597. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  598. if (!iconFileExists) {
  599. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  600. }
  601. cell.labelTitle.isEnabled = false
  602. }
  603. // uploadFileError
  604. if metadata.status == k_metadataStatusUploadError {
  605. cell.labelTitle.isEnabled = false
  606. cell.status.image = UIImage.init(named: "statuserror")
  607. if !iconFileExists {
  608. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  609. }
  610. if metadata.sessionError.count == 0 {
  611. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  612. } else {
  613. cell.labelInfoFile.text = metadata.sessionError
  614. }
  615. }
  616. // Progress
  617. cell.transferButton.progress = progress
  618. // User
  619. if metadata.account != appDelegate.activeAccount {
  620. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  621. if tableAccount != nil {
  622. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(tableAccount!.user, activeUrl: tableAccount!.url) + "-" + tableAccount!.user + ".png"
  623. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  624. if avatar != nil {
  625. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  626. let imageSize = avatarImageView?.bounds.size
  627. UIGraphicsBeginImageContext(imageSize!)
  628. let context = UIGraphicsGetCurrentContext()
  629. avatarImageView?.layer.render(in: context!)
  630. avatar = UIGraphicsGetImageFromCurrentImageContext()
  631. UIGraphicsEndImageContext()
  632. cell.user.image = avatar
  633. }
  634. }
  635. }
  636. return cell
  637. }
  638. }
  639. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  640. guard let indexPath = indexPath else {
  641. return nil
  642. }
  643. guard let sectionDataSource = sectionDataSource else {
  644. return nil
  645. }
  646. let section = indexPath.section + 1
  647. let row = indexPath.row + 1
  648. let totSections = sectionDataSource.sections.count
  649. if totSections < section || section > totSections {
  650. return nil
  651. }
  652. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  653. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  654. return nil
  655. }
  656. let totRows = filesID.count
  657. if totRows < row || row > totRows {
  658. return nil
  659. }
  660. let fileID = filesID.object(at: indexPath.row)
  661. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: fileID) as? tableMetadata
  662. return metadata
  663. }
  664. @objc func reloadDatasource(ServerUrl: String?, fileID: String?, action: Int32) {
  665. if operationQueueReloadDatasource.operationCount > 0 {
  666. return
  667. }
  668. if self.appDelegate.activeMain != nil && ServerUrl != nil && self.appDelegate.activeMain.serverUrl == ServerUrl {
  669. self.operationQueueReloadDatasource.addOperation {
  670. DispatchQueue.main.async {
  671. self.appDelegate.activeMain.reloadDatasource(ServerUrl, fileID: fileID, action: Int(action))
  672. }
  673. }
  674. }
  675. if self.appDelegate.activeFavorites != nil && self.appDelegate.activeFavorites.viewIfLoaded?.window != nil {
  676. self.operationQueueReloadDatasource.addOperation {
  677. DispatchQueue.main.async {
  678. self.appDelegate.activeFavorites.reloadDatasource(fileID, action: Int(action))
  679. }
  680. }
  681. }
  682. if self.appDelegate.activeTransfers != nil && self.appDelegate.activeTransfers.viewIfLoaded?.window != nil {
  683. self.operationQueueReloadDatasource.addOperation {
  684. DispatchQueue.main.async {
  685. self.appDelegate.activeTransfers.reloadDatasource(fileID, action: Int(action))
  686. }
  687. }
  688. }
  689. }
  690. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  691. if view is UICollectionView {
  692. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  693. }
  694. if view is UITableView {
  695. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  696. }
  697. return true
  698. }
  699. //MARK: -
  700. @objc func deleteFile(metadatas: NSArray, e2ee: Bool, serverUrl: String, folderFileID: String, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  701. var copyMetadatas = [tableMetadata]()
  702. for metadata in metadatas {
  703. copyMetadatas.append(tableMetadata.init(value: metadata))
  704. }
  705. if e2ee {
  706. DispatchQueue.global().async {
  707. let error = NCNetworkingEndToEnd.sharedManager().lockFolderEncrypted(onServerUrl: serverUrl, fileID: folderFileID, user: self.appDelegate.activeUser, userID: self.appDelegate.activeUserID, password: self.appDelegate.activePassword, url: self.appDelegate.activeUrl)
  708. DispatchQueue.main.async {
  709. if error == nil {
  710. self.delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  711. } else {
  712. self.appDelegate.messageNotification("_delete_", description: error?.localizedDescription, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  713. return
  714. }
  715. }
  716. }
  717. } else {
  718. delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  719. }
  720. }
  721. private func delete(metadatas: [tableMetadata], serverUrl: String, e2ee: Bool, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  722. var count: Int = 0
  723. var completionErrorCode: Int = 0
  724. var completionMessage = ""
  725. for metadata in metadatas {
  726. self.appDelegate.filterFileID.add(metadata.fileID)
  727. let path = metadata.serverUrl + "/" + metadata.fileName
  728. OCNetworking.sharedManager().deleteFileOrFolder(withAccount: appDelegate.activeAccount, path: path, completion: { (account, message, errorCode) in
  729. if account == self.appDelegate.activeAccount {
  730. count += 1
  731. if errorCode == 0 || errorCode == kOCErrorServerPathNotFound {
  732. do {
  733. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  734. } catch { }
  735. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  736. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  737. if metadata.directory {
  738. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName), account: metadata.account)
  739. }
  740. if (e2ee) {
  741. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, serverUrl, metadata.fileName))
  742. }
  743. self.appDelegate.filterFileID.remove(metadata.fileID)
  744. } else {
  745. completionErrorCode = errorCode
  746. completionMessage = ""
  747. if message != nil {
  748. completionMessage = message!
  749. }
  750. self.appDelegate.filterFileID.remove(metadata.fileID)
  751. }
  752. if count == metadatas.count {
  753. if e2ee {
  754. DispatchQueue.global().async {
  755. NCNetworkingEndToEnd.sharedManager().rebuildAndSendMetadata(onServerUrl: serverUrl, account: self.appDelegate.activeAccount, user: self.appDelegate.activeUser, userID: self.appDelegate.activeUserID, password: self.appDelegate.activePassword, url: self.appDelegate.activeUrl)
  756. DispatchQueue.main.async {
  757. completion(completionErrorCode, completionMessage)
  758. }
  759. }
  760. } else {
  761. completion(completionErrorCode, completionMessage)
  762. }
  763. }
  764. }
  765. })
  766. }
  767. self.reloadDatasource(ServerUrl: serverUrl, fileID: nil, action: k_action_NULL)
  768. }
  769. @objc func editPhoto(_ metadata: tableMetadata, viewController: UIViewController) {
  770. guard let path = CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView) else {
  771. return
  772. }
  773. guard let image = UIImage(contentsOfFile: path) else {
  774. return
  775. }
  776. self.metadata = metadata
  777. let photoEditor = PhotoEditorViewController(nibName:"PhotoEditorViewController",bundle: Bundle(for: PhotoEditorViewController.self))
  778. photoEditor.image = image
  779. photoEditor.photoEditorDelegate = self
  780. photoEditor.hiddenControls = [.save, .share, .sticker]
  781. photoEditor.cancelButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCancel")!, multiplier:2, color: .white)
  782. photoEditor.cropButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCrop")!, multiplier:2, color: .white)
  783. photoEditor.drawButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDraw")!, multiplier:2, color: .white)
  784. photoEditor.textButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorText")!, multiplier:2, color: .white)
  785. photoEditor.clearButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorClear")!, multiplier:2, color: .white)
  786. photoEditor.continueButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDone")!, multiplier:2, color: .white)
  787. viewController.present(photoEditor, animated: true, completion: nil)
  788. }
  789. func doneEditing(image: UIImage) {
  790. guard let metadata = self.metadata else {
  791. return
  792. }
  793. guard let path = CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView) else {
  794. return
  795. }
  796. guard let filetype = NCUtility.sharedInstance.isEditImage(metadata.fileNameView as NSString) else {
  797. return
  798. }
  799. if filetype == "PNG" {
  800. do {
  801. try image.pngData()?.write(to: path.url, options: .atomic)
  802. } catch { return }
  803. } else if filetype == "JPG" {
  804. let imageData = image.jpegData(compressionQuality: 1)
  805. do {
  806. try imageData?.write(to: path.url)
  807. } catch { return }
  808. }
  809. // write icon
  810. CCGraphics.createNewImage(from: metadata.fileNameView, fileID: metadata.fileID, extension: filetype, filterGrayScale: false, typeFile: metadata.typeFile, writeImage: true)
  811. // upload
  812. metadata.session = k_upload_session
  813. metadata.sessionSelector = selectorUploadFile
  814. metadata.status = Int(k_metadataStatusWaitUpload)
  815. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  816. }
  817. func canceledEditing() {
  818. print("Canceled")
  819. }
  820. //MARK: - NCAudioRecorder
  821. func startAudioRecorder() {
  822. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  823. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  824. viewController.delegate = self
  825. viewController.createRecorder(fileName: fileName)
  826. viewController.modalTransitionStyle = .crossDissolve
  827. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  828. self.appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  829. }
  830. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  831. let metadata = tableMetadata()
  832. metadata.account = appDelegate.activeAccount
  833. metadata.date = NSDate()
  834. metadata.fileID = CCUtility.createMetadataID(fromAccount: appDelegate.activeAccount, serverUrl: appDelegate.activeMain.serverUrl, fileNameView: fileName, directory: false)
  835. metadata.fileName = fileName
  836. metadata.fileNameView = fileName
  837. metadata.serverUrl = appDelegate.activeMain.serverUrl
  838. metadata.session = k_upload_session
  839. metadata.sessionSelector = selectorUploadFile
  840. metadata.status = Int(k_metadataStatusWaitUpload)
  841. CCUtility.copyFile(atPath: NSTemporaryDirectory() + fileName, toPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: fileName))
  842. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  843. self.reloadDatasource(ServerUrl: appDelegate.activeMain.serverUrl, fileID: metadata.fileID, action: k_action_NULL)
  844. }
  845. }
  846. //MARK: -
  847. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  848. override func viewDidLoad() {
  849. super.viewDidLoad()
  850. delegate = self
  851. }
  852. //Delegate methods
  853. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  854. let tabViewControllers = tabBarController.viewControllers!
  855. guard let toIndex = tabViewControllers.index(of: viewController) else {
  856. if let vc = viewController as? UINavigationController {
  857. vc.popToRootViewController(animated: true);
  858. }
  859. return false
  860. }
  861. animateToTab(toIndex: toIndex)
  862. return true
  863. }
  864. func animateToTab(toIndex: Int) {
  865. let tabViewControllers = viewControllers!
  866. let fromView = selectedViewController!.view!
  867. let toView = tabViewControllers[toIndex].view!
  868. let fromIndex = tabViewControllers.index(of: selectedViewController!)
  869. guard fromIndex != toIndex else {return}
  870. // Add the toView to the tab bar view
  871. fromView.superview?.addSubview(toView)
  872. fromView.superview?.backgroundColor = UIColor.white
  873. // Position toView off screen (to the left/right of fromView)
  874. let screenWidth = UIScreen.main.bounds.size.width;
  875. let scrollRight = toIndex > fromIndex!;
  876. let offset = (scrollRight ? screenWidth : -screenWidth)
  877. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  878. // Disable interaction during animation
  879. view.isUserInteractionEnabled = false
  880. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  881. // Slide the views by -offset
  882. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  883. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  884. }, completion: { finished in
  885. // Remove the old view from the tabbar view.
  886. fromView.removeFromSuperview()
  887. self.selectedIndex = toIndex
  888. self.view.isUserInteractionEnabled = true
  889. })
  890. }
  891. }
  892. //
  893. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  894. //
  895. extension UITabBar {
  896. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  897. // the Master view controller shows the UITabBarItem icon next to the text
  898. override open var traitCollection: UITraitCollection {
  899. if UIDevice.current.userInterfaceIdiom == .pad {
  900. return UITraitCollection(horizontalSizeClass: .compact)
  901. }
  902. return super.traitCollection
  903. }
  904. }
  905. //MARK: -
  906. class NCNetworkingMain: NSObject, CCNetworkingDelegate {
  907. @objc static let sharedInstance: NCNetworkingMain = {
  908. let instance = NCNetworkingMain()
  909. return instance
  910. }()
  911. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  912. // DOWNLOAD
  913. func downloadStart(_ fileID: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  914. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  915. appDelegate.updateApplicationIconBadgeNumber()
  916. }
  917. func downloadFileSuccessFailure(_ fileName: String!, fileID: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  918. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  919. return
  920. }
  921. if metadata.account != appDelegate.activeAccount {
  922. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  923. return
  924. }
  925. if errorCode == 0 {
  926. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  927. // Synchronized
  928. if selector == selectorDownloadSynchronize {
  929. appDelegate.updateApplicationIconBadgeNumber()
  930. appDelegate.loadAutoDownloadUpload()
  931. return
  932. }
  933. // Modify Photo
  934. if selector == selectorDownloadEditPhoto {
  935. NCMainCommon.sharedInstance.editPhoto(metadata, viewController: appDelegate.activeMain)
  936. return
  937. }
  938. // open View File
  939. if selector == selectorLoadFileView && UIApplication.shared.applicationState == UIApplication.State.active {
  940. var uti = CCUtility.insertTypeFileIconName(metadata.fileNameView, metadata: metadata)
  941. if uti == nil {
  942. uti = ""
  943. } else if uti!.contains("opendocument") && !NCViewerRichdocument.sharedInstance.isRichDocument(metadata) {
  944. metadata.typeFile = k_metadataTypeFile_unknown
  945. }
  946. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  947. if appDelegate.activeMain.view.window != nil {
  948. appDelegate.activeMain.open(in: metadata)
  949. }
  950. if appDelegate.activeFavorites.view.window != nil {
  951. appDelegate.activeFavorites.open(in: metadata)
  952. }
  953. } else {
  954. if appDelegate.activeMain.view.window != nil {
  955. appDelegate.activeMain.shouldPerformSegue(metadata)
  956. }
  957. if appDelegate.activeFavorites.view.window != nil {
  958. appDelegate.activeFavorites.shouldPerformSegue(metadata)
  959. }
  960. }
  961. }
  962. // Open in...
  963. if selector == selectorOpenIn && UIApplication.shared.applicationState == UIApplication.State.active {
  964. if appDelegate.activeMain.view.window != nil {
  965. appDelegate.activeMain.open(in: metadata)
  966. }
  967. if appDelegate.activeFavorites.view.window != nil {
  968. appDelegate.activeFavorites.open(in: metadata)
  969. }
  970. }
  971. // Save to Photo Album
  972. if selector == selectorSave {
  973. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  974. }
  975. // Copy File
  976. if selector == selectorLoadCopy {
  977. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  978. }
  979. // Set as available offline
  980. if selector == selectorLoadOffline {
  981. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, offline: true)
  982. }
  983. //selectorLoadViewImage
  984. if selector == selectorLoadViewImage {
  985. if appDelegate.activeDetail != nil {
  986. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  987. }
  988. }
  989. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  990. } else {
  991. // File do not exists on server, remove in local
  992. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  993. do {
  994. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  995. } catch { }
  996. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  997. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  998. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_DEL))
  999. }
  1000. if selector == selectorLoadViewImage {
  1001. if appDelegate.activeDetail.view.window != nil {
  1002. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  1003. }
  1004. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1005. }
  1006. }
  1007. appDelegate.loadAutoDownloadUpload()
  1008. }
  1009. // UPLOAD
  1010. func uploadStart(_ fileID: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  1011. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1012. appDelegate.updateApplicationIconBadgeNumber()
  1013. }
  1014. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  1015. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  1016. return
  1017. }
  1018. if metadata.account != appDelegate.activeAccount {
  1019. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1020. return
  1021. }
  1022. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1023. if errorCode == 0 {
  1024. if self.appDelegate.timerProcessAutoDownloadUpload.isValid {
  1025. self.appDelegate.performSelector(onMainThread: #selector(self.appDelegate.loadAutoDownloadUpload), with: nil, waitUntilDone: true)
  1026. }
  1027. } else {
  1028. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  1029. appDelegate.messageNotification("_upload_file_", description: errorMessage, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  1030. }
  1031. }
  1032. }
  1033. @objc func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath) {
  1034. if !metadata.isInvalidated && metadata.hasPreview == 1 && (!CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) || metadata.typeFile == k_metadataTypeFile_document) {
  1035. let width = NCUtility.sharedInstance.getScreenWidthForPreview()
  1036. let height = NCUtility.sharedInstance.getScreenHeightForPreview()
  1037. OCNetworking.sharedManager().downloadPreview(withAccount: appDelegate.activeAccount, metadata: metadata, withWidth: width, andHeight: height, completion: { (account, image, message, errorCode) in
  1038. if errorCode == 0 && account == self.appDelegate.activeAccount && !metadata.isInvalidated && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) {
  1039. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1040. if let cell = (view as! UICollectionView).cellForItem(at: indexPath) {
  1041. if cell is NCListCell {
  1042. (cell as! NCListCell).imageItem.image = image
  1043. (cell as! NCListCell).imageItem.contentMode = .scaleAspectFill
  1044. } else if cell is NCGridCell {
  1045. (cell as! NCGridCell).imageItem.image = image
  1046. (cell as! NCGridCell).imageItem.contentMode = .scaleAspectFill
  1047. } else if cell is NCGridMediaCell {
  1048. (cell as! NCGridMediaCell).imageItem.image = image
  1049. (cell as! NCGridMediaCell).imageItem.contentMode = .scaleAspectFill
  1050. }
  1051. }
  1052. }
  1053. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1054. if let cell = (view as! UITableView).cellForRow(at: indexPath) {
  1055. if cell is CCCellMainTransfer {
  1056. (cell as! CCCellMainTransfer).file.image = image
  1057. (cell as! CCCellMainTransfer).file.contentMode = .scaleAspectFill
  1058. } else if cell is CCCellMain {
  1059. (cell as! CCCellMain).file.image = image
  1060. (cell as! CCCellMain).file.contentMode = .scaleAspectFill
  1061. }
  1062. }
  1063. }
  1064. }
  1065. })
  1066. }
  1067. }
  1068. }
  1069. //MARK: -
  1070. class NCFunctionMain: NSObject {
  1071. @objc static let sharedInstance: NCFunctionMain = {
  1072. let instance = NCFunctionMain()
  1073. return instance
  1074. }()
  1075. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  1076. @objc func synchronizeOffline() {
  1077. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  1078. if (directories != nil) {
  1079. for directory: tableDirectory in directories! {
  1080. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload, account: appDelegate.activeAccount)
  1081. }
  1082. }
  1083. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  1084. if (files != nil) {
  1085. for file: tableLocalFile in files! {
  1086. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", file.fileID)) else {
  1087. continue
  1088. }
  1089. CCSynchronize.shared()?.readFile(metadata.fileID, fileName: metadata.fileName, serverUrl: metadata.serverUrl, selector: selectorReadFileWithDownload, account: appDelegate.activeAccount)
  1090. }
  1091. }
  1092. }
  1093. }