NCMainCommon.swift 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  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*2, height: image!.size.height*2, 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*2, height: image!.size.height*2, color: NCBrandColor.sharedInstance.brandElement)
  306. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  307. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  308. // Status image: passcode
  309. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  310. cell.imageStatus.image = UIImage.init(named: "passcode")
  311. }
  312. // Local image: offline
  313. if tableDirectory != nil && tableDirectory!.offline {
  314. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  315. }
  316. } else {
  317. cell.imageItem.image = image
  318. if isImagePreviewLoaded == false {
  319. let width = cell.imageItem.image!.size.width * 2
  320. cell.imageItem.image = NCUtility.sharedInstance.resizeImage(image: image!, newWidth: width)
  321. }
  322. // image Local
  323. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  324. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  325. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  326. else { cell.imageLocal.image = UIImage.init(named: "local") }
  327. }
  328. // Share
  329. if (isShare) {
  330. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  331. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  332. } else if (isMounted) {
  333. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  334. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  335. } else if (sharesLink != nil) {
  336. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  337. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  338. } else if (sharesUserAndGroup != nil) {
  339. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  340. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  341. }
  342. }
  343. // image Favorite
  344. if metadata.favorite {
  345. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  346. }
  347. if isEditMode {
  348. cell.imageSelect.isHidden = false
  349. if selectFileID.contains(metadata.fileID) {
  350. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: UIColor.white)
  351. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  352. } else {
  353. cell.imageSelect.isHidden = true
  354. cell.backgroundView = nil
  355. }
  356. } else {
  357. cell.imageSelect.isHidden = true
  358. cell.backgroundView = nil
  359. }
  360. } else if cell is NCGridMediaCell {
  361. let cell = cell as! NCGridMediaCell
  362. cell.imageStatus.image = nil
  363. cell.imageLocal.image = nil
  364. cell.imageFavorite.image = nil
  365. cell.imageItem.image = image
  366. // image Local
  367. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  368. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  369. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  370. else { cell.imageLocal.image = UIImage.init(named: "local") }
  371. }
  372. // image Favorite
  373. if metadata.favorite {
  374. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  375. }
  376. if isEditMode {
  377. cell.imageSelect.isHidden = false
  378. if selectFileID.contains(metadata.fileID) {
  379. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: NCBrandColor.sharedInstance.brand)
  380. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  381. } else {
  382. cell.imageSelect.isHidden = true
  383. cell.backgroundView = nil
  384. }
  385. } else {
  386. cell.imageSelect.isHidden = true
  387. cell.backgroundView = nil
  388. }
  389. }
  390. }
  391. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String) -> UITableViewCell {
  392. var image: UIImage?
  393. // Create File System
  394. if metadata.directory {
  395. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID)
  396. } else {
  397. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView)
  398. }
  399. // CCCell
  400. if metadata.status == k_metadataStatusNormal {
  401. // NORMAL
  402. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  403. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  404. cell.accessoryType = UITableViewCell.AccessoryType.none
  405. cell.file.image = nil
  406. cell.status.image = nil
  407. cell.favorite.image = nil
  408. cell.shared.image = nil
  409. cell.local.image = nil
  410. cell.shared.isUserInteractionEnabled = false
  411. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  412. // change color selection
  413. let selectionColor = UIView()
  414. selectionColor.backgroundColor = NCBrandColor.sharedInstance.getColorSelectBackgrond()
  415. cell.selectedBackgroundView = selectionColor
  416. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  417. cell.labelTitle.textColor = UIColor.black
  418. cell.labelTitle.text = metadata.fileNameView
  419. // Download preview
  420. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: tableView, indexPath: indexPath)
  421. // Share
  422. let sharesLink = appDelegate.sharesLink.object(forKey: serverUrl + metadata.fileName)
  423. let sharesUserAndGroup = appDelegate.sharesUserAndGroup.object(forKey: serverUrl + metadata.fileName)
  424. var isShare = false
  425. var isMounted = false
  426. if metadataFolder != nil {
  427. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  428. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  429. }
  430. if metadata.directory {
  431. // lable Info
  432. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  433. // File Image & Image Title Segue
  434. if metadata.e2eEncrypted {
  435. image = UIImage.init(named: "folderEncrypted")
  436. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  437. image = UIImage.init(named: "folderAutomaticUpload")
  438. } else if isShare {
  439. image = UIImage.init(named: "folder_shared_with_me")
  440. } else if isMounted {
  441. image = UIImage.init(named: "folder_external")
  442. } else if (sharesUserAndGroup != nil) {
  443. image = UIImage.init(named: "folder_shared_with_me")
  444. } else if (sharesLink != nil) {
  445. image = UIImage.init(named: "folder_public")
  446. } else {
  447. image = UIImage.init(named: "folder")
  448. }
  449. cell.file.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width*2, height: image!.size.height*2, color: NCBrandColor.sharedInstance.brandElement)
  450. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  451. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  452. // Local image: offline
  453. if tableDirectory != nil && tableDirectory!.offline {
  454. cell.local.image = UIImage.init(named: "offlineFlag")
  455. }
  456. // Status image: passcode
  457. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  458. cell.status.image = UIImage.init(named: "passcode")
  459. }
  460. } else {
  461. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  462. // Lable Info
  463. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  464. // File Image
  465. if iconFileExists {
  466. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  467. } else {
  468. if metadata.iconName.count > 0 {
  469. cell.file.image = UIImage.init(named: metadata.iconName)
  470. } else {
  471. cell.file.image = UIImage.init(named: "file")
  472. }
  473. }
  474. // Local Image - Offline
  475. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  476. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  477. if tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  478. else { cell.local.image = UIImage.init(named: "local") }
  479. }
  480. // Status image: encrypted
  481. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  482. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  483. cell.status.image = UIImage.init(named: "encrypted")
  484. }
  485. // Share
  486. if (isShare) {
  487. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  488. } else if (isMounted) {
  489. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  490. } else if (sharesLink != nil) {
  491. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  492. } else if (sharesUserAndGroup != nil) {
  493. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  494. }
  495. }
  496. //
  497. // File & Directory
  498. //
  499. // Favorite
  500. if metadata.favorite {
  501. cell.favorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  502. }
  503. // More Image
  504. cell.more.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), multiplier: 1, color: NCBrandColor.sharedInstance.optionItem)
  505. return cell
  506. } else {
  507. // TRASNFER
  508. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  509. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  510. cell.accessoryType = UITableViewCell.AccessoryType.none
  511. cell.file.image = nil
  512. cell.status.image = nil
  513. cell.user.image = nil
  514. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  515. cell.labelTitle.textColor = UIColor.black
  516. cell.labelTitle.text = metadata.fileNameView
  517. cell.transferButton.tintColor = NCBrandColor.sharedInstance.optionItem
  518. var progress: CGFloat = 0.0
  519. var totalBytes: Double = 0.0
  520. //var totalBytesExpected : Double = 0
  521. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.fileID) as? NSArray
  522. if progressArray != nil && progressArray?.count == 3 {
  523. progress = progressArray?.object(at: 0) as! CGFloat
  524. totalBytes = progressArray?.object(at: 1) as! Double
  525. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  526. }
  527. // Write status on Label Info
  528. switch metadata.status {
  529. case Int(k_metadataStatusWaitDownload):
  530. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  531. progress = 0.0
  532. break
  533. case Int(k_metadataStatusInDownload):
  534. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  535. progress = 0.0
  536. break
  537. case Int(k_metadataStatusDownloading):
  538. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  539. break
  540. case Int(k_metadataStatusWaitUpload):
  541. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  542. progress = 0.0
  543. break
  544. case Int(k_metadataStatusInUpload):
  545. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  546. progress = 0.0
  547. break
  548. case Int(k_metadataStatusUploading):
  549. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  550. break
  551. default:
  552. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  553. progress = 0.0
  554. }
  555. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  556. if iconFileExists {
  557. cell.file.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  558. } else {
  559. if metadata.iconName.count > 0 {
  560. cell.file.image = UIImage.init(named: metadata.iconName)
  561. } else {
  562. cell.file.image = UIImage.init(named: "file")
  563. }
  564. }
  565. // Session Upload Extension
  566. if metadata.session == k_upload_session_extension && (metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading) {
  567. cell.labelTitle.isEnabled = false
  568. cell.labelInfoFile.isEnabled = false
  569. } else {
  570. cell.labelTitle.isEnabled = true
  571. cell.labelInfoFile.isEnabled = true
  572. }
  573. // downloadFile
  574. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  575. //
  576. }
  577. // downloadFile Error
  578. if metadata.status == k_metadataStatusDownloadError {
  579. cell.status.image = UIImage.init(named: "statuserror")
  580. if metadata.sessionError.count == 0 {
  581. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  582. } else {
  583. cell.labelInfoFile.text = metadata.sessionError
  584. }
  585. }
  586. // uploadFile
  587. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  588. if (!iconFileExists) {
  589. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  590. }
  591. cell.labelTitle.isEnabled = false
  592. }
  593. // uploadFileError
  594. if metadata.status == k_metadataStatusUploadError {
  595. cell.labelTitle.isEnabled = false
  596. cell.status.image = UIImage.init(named: "statuserror")
  597. if !iconFileExists {
  598. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  599. }
  600. if metadata.sessionError.count == 0 {
  601. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  602. } else {
  603. cell.labelInfoFile.text = metadata.sessionError
  604. }
  605. }
  606. // Progress
  607. cell.transferButton.progress = progress
  608. // User
  609. if metadata.account != appDelegate.activeAccount {
  610. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  611. if tableAccount != nil {
  612. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(tableAccount!.user, activeUrl: tableAccount!.url) + "-" + tableAccount!.user + ".png"
  613. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  614. if avatar != nil {
  615. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  616. let imageSize = avatarImageView?.bounds.size
  617. UIGraphicsBeginImageContext(imageSize!)
  618. let context = UIGraphicsGetCurrentContext()
  619. avatarImageView?.layer.render(in: context!)
  620. avatar = UIGraphicsGetImageFromCurrentImageContext()
  621. UIGraphicsEndImageContext()
  622. cell.user.image = avatar
  623. }
  624. }
  625. }
  626. return cell
  627. }
  628. }
  629. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  630. guard let indexPath = indexPath else {
  631. return nil
  632. }
  633. guard let sectionDataSource = sectionDataSource else {
  634. return nil
  635. }
  636. let section = indexPath.section + 1
  637. let row = indexPath.row + 1
  638. let totSections = sectionDataSource.sections.count
  639. if totSections < section || section > totSections {
  640. return nil
  641. }
  642. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  643. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  644. return nil
  645. }
  646. let totRows = filesID.count
  647. if totRows < row || row > totRows {
  648. return nil
  649. }
  650. let fileID = filesID.object(at: indexPath.row)
  651. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: fileID) as? tableMetadata
  652. return metadata
  653. }
  654. @objc func reloadDatasource(ServerUrl: String?, fileID: String?, action: Int32) {
  655. if operationQueueReloadDatasource.operationCount > 0 {
  656. return
  657. }
  658. if self.appDelegate.activeMain != nil && ServerUrl != nil && self.appDelegate.activeMain.serverUrl == ServerUrl {
  659. self.operationQueueReloadDatasource.addOperation {
  660. DispatchQueue.main.async {
  661. self.appDelegate.activeMain.reloadDatasource(ServerUrl, fileID: fileID, action: Int(action))
  662. }
  663. }
  664. }
  665. if self.appDelegate.activeFavorites != nil && self.appDelegate.activeFavorites.viewIfLoaded?.window != nil {
  666. self.operationQueueReloadDatasource.addOperation {
  667. DispatchQueue.main.async {
  668. self.appDelegate.activeFavorites.reloadDatasource(fileID, action: Int(action))
  669. }
  670. }
  671. }
  672. if self.appDelegate.activeTransfers != nil && self.appDelegate.activeTransfers.viewIfLoaded?.window != nil {
  673. self.operationQueueReloadDatasource.addOperation {
  674. DispatchQueue.main.async {
  675. self.appDelegate.activeTransfers.reloadDatasource(fileID, action: Int(action))
  676. }
  677. }
  678. }
  679. }
  680. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  681. if view is UICollectionView {
  682. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  683. }
  684. if view is UITableView {
  685. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  686. }
  687. return true
  688. }
  689. //MARK: -
  690. @objc func deleteFile(metadatas: NSArray, e2ee: Bool, serverUrl: String, folderFileID: String, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  691. var copyMetadatas = [tableMetadata]()
  692. for metadata in metadatas {
  693. copyMetadatas.append(tableMetadata.init(value: metadata))
  694. }
  695. if e2ee {
  696. DispatchQueue.global().async {
  697. 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)
  698. DispatchQueue.main.async {
  699. if error == nil {
  700. self.delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  701. } else {
  702. self.appDelegate.messageNotification("_delete_", description: error?.localizedDescription, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  703. return
  704. }
  705. }
  706. }
  707. } else {
  708. delete(metadatas: copyMetadatas, serverUrl:serverUrl, e2ee: e2ee, completion: completion)
  709. }
  710. }
  711. private func delete(metadatas: [tableMetadata], serverUrl: String, e2ee: Bool, completion: @escaping (_ errorCode: Int, _ message: String)->()) {
  712. var count: Int = 0
  713. var completionErrorCode: Int = 0
  714. var completionMessage = ""
  715. for metadata in metadatas {
  716. self.appDelegate.filterFileID.add(metadata.fileID)
  717. let path = metadata.serverUrl + "/" + metadata.fileName
  718. OCNetworking.sharedManager().deleteFileOrFolder(withAccount: appDelegate.activeAccount, path: path, completion: { (account, message, errorCode) in
  719. if account == self.appDelegate.activeAccount {
  720. count += 1
  721. if errorCode == 0 || errorCode == kOCErrorServerPathNotFound {
  722. do {
  723. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  724. } catch { }
  725. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  726. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  727. if metadata.directory {
  728. NCManageDatabase.sharedInstance.deleteDirectoryAndSubDirectory(serverUrl: CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName), account: metadata.account)
  729. }
  730. if (e2ee) {
  731. NCManageDatabase.sharedInstance.deleteE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", metadata.account, serverUrl, metadata.fileName))
  732. }
  733. self.appDelegate.filterFileID.remove(metadata.fileID)
  734. } else {
  735. completionErrorCode = errorCode
  736. completionMessage = ""
  737. if message != nil {
  738. completionMessage = message!
  739. }
  740. self.appDelegate.filterFileID.remove(metadata.fileID)
  741. }
  742. if count == metadatas.count {
  743. if e2ee {
  744. DispatchQueue.global().async {
  745. 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)
  746. DispatchQueue.main.async {
  747. completion(completionErrorCode, completionMessage)
  748. }
  749. }
  750. } else {
  751. completion(completionErrorCode, completionMessage)
  752. }
  753. }
  754. }
  755. })
  756. }
  757. self.reloadDatasource(ServerUrl: serverUrl, fileID: nil, action: k_action_NULL)
  758. }
  759. @objc func editPhoto(_ metadata: tableMetadata, viewController: UIViewController) {
  760. guard let path = CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView) else {
  761. return
  762. }
  763. guard let image = UIImage(contentsOfFile: path) else {
  764. return
  765. }
  766. self.metadata = metadata
  767. let photoEditor = PhotoEditorViewController(nibName:"PhotoEditorViewController",bundle: Bundle(for: PhotoEditorViewController.self))
  768. photoEditor.image = image
  769. photoEditor.photoEditorDelegate = self
  770. photoEditor.hiddenControls = [.save, .share, .sticker]
  771. photoEditor.cancelButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCancel")!, multiplier:2, color: .white)
  772. photoEditor.cropButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCrop")!, multiplier:2, color: .white)
  773. photoEditor.drawButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDraw")!, multiplier:2, color: .white)
  774. photoEditor.textButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorText")!, multiplier:2, color: .white)
  775. photoEditor.clearButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorClear")!, multiplier:2, color: .white)
  776. photoEditor.continueButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDone")!, multiplier:2, color: .white)
  777. viewController.present(photoEditor, animated: true, completion: nil)
  778. }
  779. func doneEditing(image: UIImage) {
  780. guard let metadata = self.metadata else {
  781. return
  782. }
  783. guard let path = CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView) else {
  784. return
  785. }
  786. guard let filetype = NCUtility.sharedInstance.isEditImage(metadata.fileNameView as NSString) else {
  787. return
  788. }
  789. if filetype == "PNG" {
  790. do {
  791. try image.pngData()?.write(to: path.url, options: .atomic)
  792. } catch { return }
  793. } else if filetype == "JPG" {
  794. let imageData = image.jpegData(compressionQuality: 1)
  795. do {
  796. try imageData?.write(to: path.url)
  797. } catch { return }
  798. }
  799. // write icon
  800. CCGraphics.createNewImage(from: metadata.fileNameView, fileID: metadata.fileID, extension: filetype, filterGrayScale: false, typeFile: metadata.typeFile, writeImage: true)
  801. // upload
  802. metadata.session = k_upload_session
  803. metadata.sessionSelector = selectorUploadFile
  804. metadata.status = Int(k_metadataStatusWaitUpload)
  805. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  806. }
  807. func canceledEditing() {
  808. print("Canceled")
  809. }
  810. //MARK: - NCAudioRecorder
  811. func startAudioRecorder() {
  812. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  813. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  814. viewController.delegate = self
  815. viewController.createRecorder(fileName: fileName)
  816. viewController.modalTransitionStyle = .crossDissolve
  817. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  818. self.appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  819. }
  820. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  821. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  822. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  823. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  824. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  825. self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  826. }
  827. }
  828. //MARK: -
  829. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  830. override func viewDidLoad() {
  831. super.viewDidLoad()
  832. delegate = self
  833. }
  834. //Delegate methods
  835. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  836. let tabViewControllers = tabBarController.viewControllers!
  837. guard let toIndex = tabViewControllers.index(of: viewController) else {
  838. if let vc = viewController as? UINavigationController {
  839. vc.popToRootViewController(animated: true);
  840. }
  841. return false
  842. }
  843. animateToTab(toIndex: toIndex)
  844. return true
  845. }
  846. func animateToTab(toIndex: Int) {
  847. let tabViewControllers = viewControllers!
  848. let fromView = selectedViewController!.view!
  849. let toView = tabViewControllers[toIndex].view!
  850. let fromIndex = tabViewControllers.index(of: selectedViewController!)
  851. guard fromIndex != toIndex else {return}
  852. // Add the toView to the tab bar view
  853. fromView.superview?.addSubview(toView)
  854. fromView.superview?.backgroundColor = UIColor.white
  855. // Position toView off screen (to the left/right of fromView)
  856. let screenWidth = UIScreen.main.bounds.size.width;
  857. let scrollRight = toIndex > fromIndex!;
  858. let offset = (scrollRight ? screenWidth : -screenWidth)
  859. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  860. // Disable interaction during animation
  861. view.isUserInteractionEnabled = false
  862. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  863. // Slide the views by -offset
  864. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  865. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  866. }, completion: { finished in
  867. // Remove the old view from the tabbar view.
  868. fromView.removeFromSuperview()
  869. self.selectedIndex = toIndex
  870. self.view.isUserInteractionEnabled = true
  871. })
  872. }
  873. }
  874. //
  875. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  876. //
  877. extension UITabBar {
  878. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  879. // the Master view controller shows the UITabBarItem icon next to the text
  880. override open var traitCollection: UITraitCollection {
  881. if UIDevice.current.userInterfaceIdiom == .pad {
  882. return UITraitCollection(horizontalSizeClass: .compact)
  883. }
  884. return super.traitCollection
  885. }
  886. }
  887. //MARK: -
  888. class NCNetworkingMain: NSObject, CCNetworkingDelegate {
  889. @objc static let sharedInstance: NCNetworkingMain = {
  890. let instance = NCNetworkingMain()
  891. return instance
  892. }()
  893. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  894. // DOWNLOAD
  895. func downloadStart(_ fileID: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  896. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  897. appDelegate.updateApplicationIconBadgeNumber()
  898. }
  899. func downloadFileSuccessFailure(_ fileName: String!, fileID: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  900. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  901. return
  902. }
  903. if metadata.account != appDelegate.activeAccount {
  904. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  905. return
  906. }
  907. if errorCode == 0 {
  908. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  909. // Synchronized
  910. if selector == selectorDownloadSynchronize {
  911. appDelegate.updateApplicationIconBadgeNumber()
  912. appDelegate.startLoadAutoDownloadUpload()
  913. return
  914. }
  915. // Modify Photo
  916. if selector == selectorDownloadEditPhoto {
  917. NCMainCommon.sharedInstance.editPhoto(metadata, viewController: appDelegate.activeMain)
  918. return
  919. }
  920. // open View File
  921. if selector == selectorLoadFileView && UIApplication.shared.applicationState == UIApplication.State.active {
  922. var uti = CCUtility.insertTypeFileIconName(metadata.fileNameView, metadata: metadata)
  923. if uti == nil {
  924. uti = ""
  925. } else if uti!.contains("opendocument") && !NCViewerRichdocument.sharedInstance.isRichDocument(metadata) {
  926. metadata.typeFile = k_metadataTypeFile_unknown
  927. }
  928. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  929. if appDelegate.activeMain.view.window != nil {
  930. appDelegate.activeMain.open(in: metadata)
  931. }
  932. if appDelegate.activeFavorites.view.window != nil {
  933. appDelegate.activeFavorites.open(in: metadata)
  934. }
  935. } else {
  936. if appDelegate.activeMain.view.window != nil {
  937. appDelegate.activeMain.shouldPerformSegue(metadata)
  938. }
  939. if appDelegate.activeFavorites.view.window != nil {
  940. appDelegate.activeFavorites.shouldPerformSegue(metadata)
  941. }
  942. }
  943. }
  944. // Open in...
  945. if selector == selectorOpenIn && UIApplication.shared.applicationState == UIApplication.State.active {
  946. if appDelegate.activeMain.view.window != nil {
  947. appDelegate.activeMain.open(in: metadata)
  948. }
  949. if appDelegate.activeFavorites.view.window != nil {
  950. appDelegate.activeFavorites.open(in: metadata)
  951. }
  952. }
  953. // Save to Photo Album
  954. if selector == selectorSave {
  955. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  956. }
  957. // Copy File
  958. if selector == selectorLoadCopy {
  959. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  960. }
  961. // Set as available offline
  962. if selector == selectorLoadOffline {
  963. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, offline: true)
  964. }
  965. //selectorLoadViewImage
  966. if selector == selectorLoadViewImage {
  967. if appDelegate.activeDetail != nil {
  968. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  969. }
  970. }
  971. appDelegate.startLoadAutoDownloadUpload()
  972. } else {
  973. // File do not exists on server, remove in local
  974. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  975. do {
  976. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  977. } catch { }
  978. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  979. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  980. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_DEL))
  981. }
  982. if selector == selectorLoadViewImage {
  983. if appDelegate.activeDetail.view.window != nil {
  984. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  985. }
  986. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  987. }
  988. }
  989. appDelegate.startLoadAutoDownloadUpload()
  990. }
  991. // UPLOAD
  992. func uploadStart(_ fileID: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  993. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  994. appDelegate.updateApplicationIconBadgeNumber()
  995. }
  996. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  997. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  998. return
  999. }
  1000. if metadata.account != appDelegate.activeAccount {
  1001. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1002. return
  1003. }
  1004. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1005. if errorCode == 0 {
  1006. appDelegate.startLoadAutoDownloadUpload()
  1007. } else {
  1008. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  1009. appDelegate.messageNotification("_upload_file_", description: errorMessage, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  1010. }
  1011. }
  1012. }
  1013. @objc func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath) {
  1014. if !metadata.isInvalidated && metadata.hasPreview == 1 && (!CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) || metadata.typeFile == k_metadataTypeFile_document) {
  1015. let width = NCUtility.sharedInstance.getScreenWidthForPreview()
  1016. let height = NCUtility.sharedInstance.getScreenHeightForPreview()
  1017. OCNetworking.sharedManager().downloadPreview(withAccount: appDelegate.activeAccount, metadata: metadata, withWidth: width, andHeight: height, completion: { (account, image, message, errorCode) in
  1018. if errorCode == 0 && account == self.appDelegate.activeAccount && !metadata.isInvalidated && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) {
  1019. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1020. if let cell = (view as! UICollectionView).cellForItem(at: indexPath) {
  1021. if cell is NCListCell {
  1022. (cell as! NCListCell).imageItem.image = image
  1023. } else if cell is NCGridCell {
  1024. (cell as! NCGridCell).imageItem.image = image
  1025. } else if cell is NCGridMediaCell {
  1026. (cell as! NCGridMediaCell).imageItem.image = image
  1027. }
  1028. }
  1029. }
  1030. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1031. if let cell = (view as! UITableView).cellForRow(at: indexPath) {
  1032. if cell is CCCellMainTransfer {
  1033. (cell as! CCCellMainTransfer).file.image = image
  1034. } else if cell is CCCellMain {
  1035. (cell as! CCCellMain).file.image = image
  1036. }
  1037. }
  1038. }
  1039. }
  1040. })
  1041. }
  1042. }
  1043. }
  1044. //MARK: -
  1045. class NCFunctionMain: NSObject {
  1046. @objc static let sharedInstance: NCFunctionMain = {
  1047. let instance = NCFunctionMain()
  1048. return instance
  1049. }()
  1050. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  1051. @objc func synchronizeOffline() {
  1052. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  1053. if (directories != nil) {
  1054. for directory: tableDirectory in directories! {
  1055. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload, account: appDelegate.activeAccount)
  1056. }
  1057. }
  1058. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  1059. if (files != nil) {
  1060. for file: tableLocalFile in files! {
  1061. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", file.fileID)) else {
  1062. continue
  1063. }
  1064. CCSynchronize.shared()?.readFile(metadata.fileID, fileName: metadata.fileName, serverUrl: metadata.serverUrl, selector: selectorReadFileWithDownload, account: appDelegate.activeAccount)
  1065. }
  1066. }
  1067. }
  1068. }