NCMainCommon.swift 66 KB

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