NCMainCommon.swift 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  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. import ZIPFoundation
  26. //MARK: - Main Common
  27. class NCMainCommon: NSObject, PhotoEditorDelegate, NCAudioRecorderViewControllerDelegate, UIDocumentInteractionControllerDelegate {
  28. @objc static let sharedInstance: NCMainCommon = {
  29. let instance = NCMainCommon()
  30. return instance
  31. }()
  32. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. var metadataEditPhoto: tableMetadata?
  34. var docController: UIDocumentInteractionController?
  35. lazy var operationQueueReloadDatasource: OperationQueue = {
  36. let queue = OperationQueue()
  37. queue.name = "Reload main datasource queue"
  38. queue.maxConcurrentOperationCount = 1
  39. return queue
  40. }()
  41. //MARK: -
  42. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceFileIDIndexPath: NSDictionary, tableView: UITableView, viewController: UIViewController, serverUrlViewController: String?) {
  43. if viewController.viewIfLoaded?.window == nil {
  44. return
  45. }
  46. guard let dic = notification.userInfo else {
  47. return
  48. }
  49. let account = dic["account"] as? NSString ?? ""
  50. let fileID = dic["fileID"] as? NSString ?? ""
  51. let serverUrl = dic["serverUrl"] as? String ?? ""
  52. let status = dic["status"] as? Int ?? Int(k_taskIdentifierDone)
  53. let progress = dic["progress"] as? CGFloat ?? 0
  54. let totalBytes = dic["totalBytes"] as? Double ?? 0
  55. let totalBytesExpected = dic["totalBytesExpected"] as? Double ?? 0
  56. if (account != self.appDelegate.activeAccount! as NSString) && !(viewController is CCTransfers) {
  57. return
  58. }
  59. if serverUrlViewController != nil && serverUrlViewController! != serverUrl {
  60. return
  61. }
  62. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: fileID)
  63. guard let indexPath = sectionDataSourceFileIDIndexPath.object(forKey: fileID) else {
  64. return
  65. }
  66. if isValidIndexPath(indexPath as! IndexPath, view: tableView) {
  67. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  68. var image = ""
  69. if status == k_metadataStatusInDownload {
  70. image = "↓"
  71. } else if status == k_metadataStatusInUpload {
  72. image = "↑"
  73. }
  74. cell.labelInfoFile?.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  75. cell.transferButton?.progress = progress
  76. }
  77. }
  78. }
  79. @objc func cancelTransferMetadata(_ metadata: tableMetadata, reloadDatasource: Bool, uploadStatusForcedStart: Bool) {
  80. var actionReloadDatasource = k_action_NULL
  81. var metadata = metadata
  82. if metadata.session.count == 0 {
  83. return
  84. }
  85. guard let session = CCNetworking.shared().getSessionfromSessionDescription(metadata.session) else {
  86. return
  87. }
  88. // SESSION EXTENSION
  89. if metadata.session == k_download_session_extension || metadata.session == k_upload_session_extension {
  90. if (metadata.session == k_upload_session_extension) {
  91. do {
  92. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  93. } catch { }
  94. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  95. actionReloadDatasource = k_action_DEL
  96. } else {
  97. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  98. actionReloadDatasource = k_action_MOD
  99. }
  100. self.reloadDatasource(ServerUrl: metadata.serverUrl, fileID: metadata.fileID, action: actionReloadDatasource)
  101. return
  102. }
  103. session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  104. var cancel = false
  105. // DOWNLOAD
  106. if metadata.session.count > 0 && metadata.session.contains("download") {
  107. for task in downloadTasks {
  108. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  109. task.cancel()
  110. cancel = true
  111. }
  112. }
  113. if cancel == false {
  114. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  115. }
  116. actionReloadDatasource = k_action_MOD
  117. }
  118. // UPLOAD
  119. if metadata.session.count > 0 && metadata.session.contains("upload") {
  120. for task in uploadTasks {
  121. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  122. if uploadStatusForcedStart {
  123. metadata.status = Int(k_metadataStatusUploadForcedStart)
  124. metadata = NCManageDatabase.sharedInstance.addMetadata(metadata) ?? metadata
  125. }
  126. task.cancel()
  127. cancel = true
  128. }
  129. }
  130. if cancel == false {
  131. do {
  132. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  133. }
  134. catch { }
  135. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  136. }
  137. actionReloadDatasource = k_action_DEL
  138. }
  139. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  140. self.reloadDatasource(ServerUrl: metadata.serverUrl, fileID: metadata.fileID, action: actionReloadDatasource)
  141. }
  142. }
  143. }
  144. @objc func cancelAllTransfer(view: UIView) {
  145. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  146. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError))
  147. NCUtility.sharedInstance.startActivityIndicator(view: view, bottom: 0)
  148. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  149. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "status != %d AND status != %d", k_metadataStatusNormal, k_metadataStatusHide), sorted: "fileName", ascending: true) {
  150. for metadata in metadatas {
  151. // Modify
  152. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  153. metadata.session = ""
  154. metadata.sessionSelector = ""
  155. metadata.status = Int(k_metadataStatusNormal)
  156. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  157. }
  158. // Cancel Task
  159. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  160. self.cancelTransferMetadata(metadata, reloadDatasource: false, uploadStatusForcedStart: false)
  161. }
  162. }
  163. }
  164. }
  165. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  166. self.reloadDatasource(ServerUrl: nil, fileID: nil, action: k_action_NULL)
  167. NCUtility.sharedInstance.stopActivityIndicator()
  168. }
  169. }
  170. //MARK: -
  171. 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) {
  172. var image: UIImage?
  173. var isImagePreviewLoaded = false
  174. // Image Preview
  175. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileName)) {
  176. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileName))
  177. isImagePreviewLoaded = true
  178. } else {
  179. if metadata.iconName.count > 0 {
  180. image = UIImage.init(named: metadata.iconName)
  181. } else {
  182. image = UIImage.init(named: "file")
  183. }
  184. }
  185. // Download preview
  186. if downloadThumbnail {
  187. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: collectionView, indexPath: indexPath)
  188. }
  189. // Share
  190. let sharesLink = appDelegate.sharesLink.object(forKey: serverUrl + metadata.fileName)
  191. let sharesUserAndGroup = appDelegate.sharesUserAndGroup.object(forKey: serverUrl + metadata.fileName)
  192. var isShare = false
  193. var isMounted = false
  194. if metadataFolder != nil {
  195. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  196. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  197. }
  198. if cell is NCListCell {
  199. let cell = cell as! NCListCell
  200. cell.delegate = source as? NCListCellDelegate
  201. cell.fileID = metadata.fileID
  202. cell.indexPath = indexPath
  203. cell.labelTitle.text = metadata.fileNameView
  204. cell.imageStatus.image = nil
  205. cell.imageLocal.image = nil
  206. cell.imageFavorite.image = nil
  207. cell.imageShare.image = nil
  208. cell.hide(buttonMore: hideButtonMore, hideImageShare: true)
  209. if metadata.directory {
  210. if metadata.e2eEncrypted {
  211. image = UIImage.init(named: "folderEncrypted")
  212. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  213. image = UIImage.init(named: "folderAutomaticUpload")
  214. } else if isShare {
  215. image = UIImage.init(named: "folder_shared_with_me")
  216. } else if isMounted {
  217. image = UIImage.init(named: "folder_external")
  218. } else if (sharesUserAndGroup != nil) {
  219. image = UIImage.init(named: "folder_shared_with_me")
  220. } else if (sharesLink != nil) {
  221. image = UIImage.init(named: "folder_public")
  222. } else {
  223. image = UIImage.init(named: "folder")
  224. }
  225. cell.imageItem.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width*2, height: image!.size.height*2, color: NCBrandColor.sharedInstance.brandElement)
  226. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  227. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  228. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  229. // Status image: passcode
  230. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  231. cell.imageStatus.image = UIImage.init(named: "passcode")
  232. }
  233. // Local image: offline
  234. if tableDirectory != nil && tableDirectory!.offline {
  235. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  236. }
  237. } else {
  238. cell.imageItem.image = image
  239. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  240. // image Local
  241. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  242. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  243. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  244. else { cell.imageLocal.image = UIImage.init(named: "local") }
  245. }
  246. // Share
  247. if (isShare) {
  248. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  249. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  250. } else if (isMounted) {
  251. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  252. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  253. } else if (sharesLink != nil) {
  254. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  255. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  256. } else if (sharesUserAndGroup != nil) {
  257. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  258. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  259. }
  260. }
  261. // image Favorite
  262. if metadata.favorite {
  263. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  264. }
  265. if isEditMode {
  266. cell.imageItemLeftConstraint.constant = 45
  267. cell.imageSelect.isHidden = false
  268. if selectFileID.contains(metadata.fileID) {
  269. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  270. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  271. } else {
  272. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedNo"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  273. cell.backgroundView = nil
  274. }
  275. } else {
  276. cell.imageItemLeftConstraint.constant = 10
  277. cell.imageSelect.isHidden = true
  278. cell.backgroundView = nil
  279. }
  280. // Remove last separator
  281. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  282. cell.separator.isHidden = true
  283. } else {
  284. cell.separator.isHidden = false
  285. }
  286. } else if cell is NCGridCell {
  287. let cell = cell as! NCGridCell
  288. cell.delegate = source as? NCGridCellDelegate
  289. cell.fileID = metadata.fileID
  290. cell.indexPath = indexPath
  291. cell.labelTitle.text = metadata.fileNameView
  292. cell.imageStatus.image = nil
  293. cell.imageLocal.image = nil
  294. cell.imageFavorite.image = nil
  295. cell.imageShare.image = nil
  296. cell.hide(buttonMore: hideButtonMore, hideImageShare: true)
  297. if metadata.directory {
  298. if metadata.e2eEncrypted {
  299. image = UIImage.init(named: "folderEncrypted")
  300. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  301. image = UIImage.init(named: "folderAutomaticUpload")
  302. } else if isShare {
  303. image = UIImage.init(named: "folder_shared_with_me")
  304. } else if isMounted {
  305. image = UIImage.init(named: "folder_external")
  306. } else if (sharesUserAndGroup != nil) {
  307. image = UIImage.init(named: "folder_shared_with_me")
  308. } else if (sharesLink != nil) {
  309. image = UIImage.init(named: "folder_public")
  310. } else {
  311. image = UIImage.init(named: "folder")
  312. }
  313. cell.imageItem.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width*2, height: image!.size.height*2, color: NCBrandColor.sharedInstance.brandElement)
  314. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  315. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  316. // Status image: passcode
  317. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  318. cell.imageStatus.image = UIImage.init(named: "passcode")
  319. }
  320. // Local image: offline
  321. if tableDirectory != nil && tableDirectory!.offline {
  322. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  323. }
  324. } else {
  325. cell.imageItem.image = image
  326. if isImagePreviewLoaded == false {
  327. let width = cell.imageItem.image!.size.width * 2
  328. cell.imageItem.image = NCUtility.sharedInstance.resizeImage(image: image!, newWidth: width)
  329. }
  330. // image Local
  331. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  332. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  333. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  334. else { cell.imageLocal.image = UIImage.init(named: "local") }
  335. }
  336. // Share
  337. if (isShare) {
  338. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  339. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  340. } else if (isMounted) {
  341. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  342. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  343. } else if (sharesLink != nil) {
  344. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  345. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  346. } else if (sharesUserAndGroup != nil) {
  347. cell.imageShare.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  348. cell.hide(buttonMore: hideButtonMore, hideImageShare: false)
  349. }
  350. }
  351. // image Favorite
  352. if metadata.favorite {
  353. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  354. }
  355. if isEditMode {
  356. cell.imageSelect.isHidden = false
  357. if selectFileID.contains(metadata.fileID) {
  358. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  359. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  360. } else {
  361. cell.imageSelect.isHidden = true
  362. cell.backgroundView = nil
  363. }
  364. } else {
  365. cell.imageSelect.isHidden = true
  366. cell.backgroundView = nil
  367. }
  368. } else if cell is NCGridMediaCell {
  369. let cell = cell as! NCGridMediaCell
  370. cell.imageStatus.image = nil
  371. cell.imageLocal.image = nil
  372. cell.imageFavorite.image = nil
  373. cell.imageItem.image = image
  374. // image Local
  375. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  376. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  377. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  378. else { cell.imageLocal.image = UIImage.init(named: "local") }
  379. }
  380. // image Favorite
  381. if metadata.favorite {
  382. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  383. }
  384. if isEditMode {
  385. cell.imageSelect.isHidden = false
  386. if selectFileID.contains(metadata.fileID) {
  387. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  388. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  389. } else {
  390. cell.imageSelect.isHidden = true
  391. cell.backgroundView = nil
  392. }
  393. } else {
  394. cell.imageSelect.isHidden = true
  395. cell.backgroundView = nil
  396. }
  397. }
  398. }
  399. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String) -> UITableViewCell {
  400. var image: UIImage?
  401. // Create File System
  402. if metadata.directory {
  403. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID)
  404. } else {
  405. CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView)
  406. }
  407. // CCCell
  408. if metadata.status == k_metadataStatusNormal {
  409. // NORMAL
  410. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  411. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  412. cell.accessoryType = UITableViewCell.AccessoryType.none
  413. cell.file.image = nil
  414. cell.status.image = nil
  415. cell.favorite.image = nil
  416. cell.shared.image = nil
  417. cell.local.image = nil
  418. cell.shared.isUserInteractionEnabled = false
  419. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  420. // change color selection
  421. let selectionColor = UIView()
  422. selectionColor.backgroundColor = NCBrandColor.sharedInstance.getColorSelectBackgrond()
  423. cell.selectedBackgroundView = selectionColor
  424. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  425. cell.labelTitle.textColor = UIColor.black
  426. cell.labelTitle.text = metadata.fileNameView
  427. // Download preview
  428. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: tableView, indexPath: indexPath)
  429. // Share
  430. let sharesLink = appDelegate.sharesLink.object(forKey: serverUrl + metadata.fileName)
  431. let sharesUserAndGroup = appDelegate.sharesUserAndGroup.object(forKey: serverUrl + metadata.fileName)
  432. var isShare = false
  433. var isMounted = false
  434. if metadataFolder != nil {
  435. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  436. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  437. }
  438. if metadata.directory {
  439. // lable Info
  440. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  441. // File Image & Image Title Segue
  442. if metadata.e2eEncrypted {
  443. image = UIImage.init(named: "folderEncrypted")
  444. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  445. image = UIImage.init(named: "folderAutomaticUpload")
  446. } else if isShare {
  447. image = UIImage.init(named: "folder_shared_with_me")
  448. } else if isMounted {
  449. image = UIImage.init(named: "folder_external")
  450. } else if (sharesUserAndGroup != nil) {
  451. image = UIImage.init(named: "folder_shared_with_me")
  452. } else if (sharesLink != nil) {
  453. image = UIImage.init(named: "folder_public")
  454. } else {
  455. image = UIImage.init(named: "folder")
  456. }
  457. cell.file.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width*2, height: image!.size.height*2, color: NCBrandColor.sharedInstance.brandElement)
  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"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  496. } else if (isMounted) {
  497. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "shareMounted"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  498. } else if (sharesLink != nil) {
  499. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  500. } else if (sharesUserAndGroup != nil) {
  501. cell.shared.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 50, height: 50, 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.metadataEditPhoto = 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.metadataEditPhoto 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. //MARK: - OpenIn
  819. @objc func downloadOpenIn(metadata: tableMetadata) {
  820. if CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  821. openIn(metadata: metadata)
  822. } else {
  823. metadata.session = k_download_session
  824. metadata.sessionError = ""
  825. metadata.sessionSelector = selectorOpenIn
  826. metadata.status = Int(k_metadataStatusWaitDownload)
  827. _ = NCManageDatabase.sharedInstance.addMetadata(metadata)
  828. reloadDatasource(ServerUrl: metadata.serverUrl, fileID: metadata.fileID, action: k_action_MOD)
  829. }
  830. }
  831. func openIn(metadata: tableMetadata) {
  832. docController = UIDocumentInteractionController(url: NSURL(fileURLWithPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView)) as URL)
  833. docController?.delegate = self
  834. guard let splitViewController = self.appDelegate.window?.rootViewController as? UISplitViewController else {
  835. return
  836. }
  837. guard let view = splitViewController.viewControllers.first?.view else {
  838. return
  839. }
  840. guard let frame = splitViewController.viewControllers.first?.view.frame else {
  841. return
  842. }
  843. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  844. }
  845. //MARK: - NCAudioRecorder
  846. func startAudioRecorder() {
  847. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  848. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  849. viewController.delegate = self
  850. viewController.createRecorder(fileName: fileName)
  851. viewController.modalTransitionStyle = .crossDissolve
  852. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  853. self.appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  854. }
  855. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  856. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  857. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  858. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  859. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  860. self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  861. }
  862. }
  863. //MARK: - Main TabBarController
  864. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  865. override func viewDidLoad() {
  866. super.viewDidLoad()
  867. delegate = self
  868. }
  869. //Delegate methods
  870. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  871. let tabViewControllers = tabBarController.viewControllers!
  872. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  873. if let vc = viewController as? UINavigationController {
  874. vc.popToRootViewController(animated: true);
  875. }
  876. return false
  877. }
  878. animateToTab(toIndex: toIndex)
  879. return true
  880. }
  881. func animateToTab(toIndex: Int) {
  882. let tabViewControllers = viewControllers!
  883. let fromView = selectedViewController!.view!
  884. let toView = tabViewControllers[toIndex].view!
  885. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  886. guard fromIndex != toIndex else {return}
  887. // Add the toView to the tab bar view
  888. fromView.superview?.addSubview(toView)
  889. fromView.superview?.backgroundColor = UIColor.white
  890. // Position toView off screen (to the left/right of fromView)
  891. let screenWidth = UIScreen.main.bounds.size.width;
  892. let scrollRight = toIndex > fromIndex!;
  893. let offset = (scrollRight ? screenWidth : -screenWidth)
  894. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  895. // Disable interaction during animation
  896. view.isUserInteractionEnabled = false
  897. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  898. // Slide the views by -offset
  899. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  900. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  901. }, completion: { finished in
  902. // Remove the old view from the tabbar view.
  903. fromView.removeFromSuperview()
  904. self.selectedIndex = toIndex
  905. self.view.isUserInteractionEnabled = true
  906. })
  907. }
  908. }
  909. //
  910. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  911. //
  912. extension UITabBar {
  913. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  914. // the Master view controller shows the UITabBarItem icon next to the text
  915. override open var traitCollection: UITraitCollection {
  916. if UIDevice.current.userInterfaceIdiom == .pad {
  917. return UITraitCollection(horizontalSizeClass: .compact)
  918. }
  919. return super.traitCollection
  920. }
  921. }
  922. //MARK: - Networking Main
  923. class NCNetworkingMain: NSObject, CCNetworkingDelegate {
  924. @objc static let sharedInstance: NCNetworkingMain = {
  925. let instance = NCNetworkingMain()
  926. return instance
  927. }()
  928. lazy var operationQueueNetworkingMain: OperationQueue = {
  929. let queue = OperationQueue()
  930. queue.name = "com.nextcloud.operationQueueNetworkingMain"
  931. queue.maxConcurrentOperationCount = 1
  932. return queue
  933. }()
  934. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  935. // DOWNLOAD
  936. func downloadStart(_ fileID: String!, account: String!, task: URLSessionDownloadTask!, serverUrl: String!) {
  937. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  938. appDelegate.updateApplicationIconBadgeNumber()
  939. }
  940. func downloadFileSuccessFailure(_ fileName: String!, fileID: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  941. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  942. return
  943. }
  944. if metadata.account != appDelegate.activeAccount {
  945. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  946. return
  947. }
  948. if errorCode == 0 {
  949. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  950. // Synchronized
  951. if selector == selectorDownloadSynchronize {
  952. appDelegate.updateApplicationIconBadgeNumber()
  953. appDelegate.startLoadAutoDownloadUpload()
  954. return
  955. }
  956. // Modify Photo
  957. if selector == selectorDownloadEditPhoto {
  958. NCMainCommon.sharedInstance.editPhoto(metadata, viewController: appDelegate.activeMain)
  959. return
  960. }
  961. // open View File
  962. if selector == selectorLoadFileView && UIApplication.shared.applicationState == UIApplication.State.active {
  963. var uti = CCUtility.insertTypeFileIconName(metadata.fileNameView, metadata: metadata)
  964. if uti == nil {
  965. uti = ""
  966. } else if uti!.contains("opendocument") && !NCViewerRichdocument.sharedInstance.isRichDocument(metadata) {
  967. metadata.typeFile = k_metadataTypeFile_unknown
  968. }
  969. if metadata.typeFile == k_metadataTypeFile_imagemeter {
  970. do {
  971. let source = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  972. let destination = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  973. try FileManager().unzipItem(at: source, to: destination)
  974. let nameArchiveImagemeter = (metadata.fileNameView as NSString).deletingPathExtension
  975. let pathArchiveImagemeter = CCUtility.getDirectoryProviderStorageFileID(metadata.fileID) + "/" + nameArchiveImagemeter
  976. let annoPath = (pathArchiveImagemeter + "/anno-" + nameArchiveImagemeter + ".imm")
  977. if let fileHandle = FileHandle(forReadingAtPath: annoPath) {
  978. let data = fileHandle.readData(ofLength: 4)
  979. if data.starts(with: [0x50, 0x4b, 0x03, 0x04]) {
  980. do {
  981. try FileManager().unzipItem(at: annoPath.url, to: pathArchiveImagemeter.url)
  982. } catch {
  983. appDelegate.messageNotification("_error_", description: "_error_decompressing_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  984. return
  985. }
  986. }
  987. fileHandle.closeFile()
  988. }
  989. } catch {
  990. appDelegate.messageNotification("_error_", description: "_error_decompressing_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  991. return
  992. }
  993. }
  994. if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  995. NCMainCommon.sharedInstance.openIn(metadata: metadata)
  996. } else {
  997. if appDelegate.activeMain.view.window != nil {
  998. appDelegate.activeMain.shouldPerformSegue(metadata)
  999. }
  1000. if appDelegate.activeFavorites.view.window != nil {
  1001. appDelegate.activeFavorites.shouldPerformSegue(metadata)
  1002. }
  1003. }
  1004. }
  1005. // Open in...
  1006. if selector == selectorOpenIn && UIApplication.shared.applicationState == UIApplication.State.active {
  1007. NCMainCommon.sharedInstance.openIn(metadata: metadata)
  1008. }
  1009. // Save to Photo Album
  1010. if selector == selectorSave {
  1011. appDelegate.activeMain.save(toPhotoAlbum: metadata)
  1012. }
  1013. // Copy File
  1014. if selector == selectorLoadCopy {
  1015. appDelegate.activeMain.copyFile(toPasteboard: metadata)
  1016. }
  1017. // Set as available offline
  1018. if selector == selectorLoadOffline {
  1019. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, offline: true)
  1020. }
  1021. //selectorLoadViewImage
  1022. if selector == selectorLoadViewImage {
  1023. if appDelegate.activeDetail != nil {
  1024. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  1025. }
  1026. }
  1027. appDelegate.startLoadAutoDownloadUpload()
  1028. } else {
  1029. // File do not exists on server, remove in local
  1030. if (errorCode == kOCErrorServerPathNotFound || errorCode == -1011) { // - 1011 = kCFURLErrorBadServerResponse
  1031. do {
  1032. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageFileID(metadata.fileID))
  1033. } catch { }
  1034. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  1035. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  1036. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_DEL))
  1037. }
  1038. if selector == selectorLoadViewImage {
  1039. if appDelegate.activeDetail.view.window != nil {
  1040. appDelegate.activeDetail.downloadPhotoBrowserSuccessFailure(metadata, selector: selector, errorCode: errorCode)
  1041. }
  1042. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1043. }
  1044. }
  1045. appDelegate.startLoadAutoDownloadUpload()
  1046. }
  1047. // UPLOAD
  1048. func uploadStart(_ fileID: String!, account: String!, task: URLSessionUploadTask!, serverUrl: String!) {
  1049. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1050. appDelegate.updateApplicationIconBadgeNumber()
  1051. }
  1052. func uploadFileSuccessFailure(_ fileName: String!, fileID: String!, assetLocalIdentifier: String!, serverUrl: String!, selector: String!, errorMessage: String!, errorCode: Int) {
  1053. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  1054. return
  1055. }
  1056. if metadata.account != appDelegate.activeAccount {
  1057. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1058. return
  1059. }
  1060. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: serverUrl, fileID: fileID, action: Int32(k_action_MOD))
  1061. if errorCode == 0 {
  1062. appDelegate.startLoadAutoDownloadUpload()
  1063. } else {
  1064. if errorCode != -999 && errorCode != kOCErrorServerUnauthorized && errorMessage != "" {
  1065. appDelegate.messageNotification("_upload_file_", description: errorMessage, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  1066. }
  1067. }
  1068. }
  1069. @objc func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath) {
  1070. operationQueueNetworkingMain.addOperation(NCOperationNetworkingMain.init(metadata: metadata, view: view, indexPath: indexPath, networkingFunc: "downloadThumbnail"))
  1071. }
  1072. func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath, closure: @escaping () -> ()) {
  1073. if !metadata.isInvalidated && metadata.hasPreview == 1 && (!CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) || metadata.typeFile == k_metadataTypeFile_document) {
  1074. let width = NCUtility.sharedInstance.getScreenWidthForPreview()
  1075. let height = NCUtility.sharedInstance.getScreenHeightForPreview()
  1076. OCNetworking.sharedManager().downloadPreview(withAccount: metadata.account, metadata: metadata, withWidth: width, andHeight: height, completion: { (account, image, message, errorCode) in
  1077. if errorCode == 0 && account == self.appDelegate.activeAccount && !metadata.isInvalidated && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) {
  1078. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1079. if let cell = (view as! UICollectionView).cellForItem(at: indexPath) {
  1080. if cell is NCListCell {
  1081. (cell as! NCListCell).imageItem.image = image
  1082. } else if cell is NCGridCell {
  1083. (cell as! NCGridCell).imageItem.image = image
  1084. } else if cell is NCGridMediaCell {
  1085. (cell as! NCGridMediaCell).imageItem.image = image
  1086. }
  1087. }
  1088. }
  1089. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  1090. if let cell = (view as! UITableView).cellForRow(at: indexPath) {
  1091. if cell is CCCellMainTransfer {
  1092. (cell as! CCCellMainTransfer).file.image = image
  1093. } else if cell is CCCellMain {
  1094. (cell as! CCCellMain).file.image = image
  1095. }
  1096. }
  1097. }
  1098. }
  1099. return closure()
  1100. })
  1101. }
  1102. return closure()
  1103. }
  1104. }
  1105. //MARK: - Operation Networking Main
  1106. class NCOperationNetworkingMain: Operation {
  1107. private var _executing : Bool = false
  1108. override var isExecuting : Bool {
  1109. get { return _executing }
  1110. set {
  1111. guard _executing != newValue else { return }
  1112. willChangeValue(forKey: "isExecuting")
  1113. _executing = newValue
  1114. didChangeValue(forKey: "isExecuting")
  1115. }
  1116. }
  1117. private var _finished : Bool = false
  1118. override var isFinished : Bool {
  1119. get { return _finished }
  1120. set {
  1121. guard _finished != newValue else { return }
  1122. willChangeValue(forKey: "isFinished")
  1123. _finished = newValue
  1124. didChangeValue(forKey: "isFinished")
  1125. }
  1126. }
  1127. private var metadata: tableMetadata?
  1128. private var view: Any?
  1129. private var indexPath: IndexPath?
  1130. private var networkingFunc: String = ""
  1131. init(metadata: tableMetadata?, view: Any?, indexPath: IndexPath?, networkingFunc: String) {
  1132. super.init()
  1133. if metadata != nil { self.metadata = metadata! }
  1134. if view != nil { self.view = view! }
  1135. if indexPath != nil { self.indexPath = indexPath! }
  1136. self.networkingFunc = networkingFunc
  1137. }
  1138. override func start() {
  1139. if !Thread.isMainThread {
  1140. self.performSelector(onMainThread:#selector(start), with: nil, waitUntilDone: false)
  1141. } else {
  1142. isExecuting = true
  1143. if isCancelled {
  1144. finish()
  1145. } else {
  1146. poolNetworking()
  1147. }
  1148. }
  1149. }
  1150. func finish() {
  1151. isExecuting = false
  1152. isFinished = true
  1153. }
  1154. override func cancel() {
  1155. super.cancel()
  1156. if isExecuting {
  1157. complete()
  1158. }
  1159. }
  1160. func complete() {
  1161. finish()
  1162. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  1163. }
  1164. func poolNetworking() {
  1165. UIApplication.shared.isNetworkActivityIndicatorVisible = true
  1166. switch networkingFunc {
  1167. case "downloadThumbnail":
  1168. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata!, view: view!, indexPath: indexPath!) {
  1169. self.complete()
  1170. }
  1171. default:
  1172. print("error")
  1173. }
  1174. }
  1175. }
  1176. //MARK: - Function Main
  1177. class NCFunctionMain: NSObject {
  1178. @objc static let sharedInstance: NCFunctionMain = {
  1179. let instance = NCFunctionMain()
  1180. return instance
  1181. }()
  1182. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  1183. @objc func synchronizeOffline() {
  1184. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  1185. if (directories != nil) {
  1186. for directory: tableDirectory in directories! {
  1187. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload, account: appDelegate.activeAccount)
  1188. }
  1189. }
  1190. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  1191. if (files != nil) {
  1192. for file: tableLocalFile in files! {
  1193. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", file.fileID)) else {
  1194. continue
  1195. }
  1196. CCSynchronize.shared()?.readFile(metadata.fileID, fileName: metadata.fileName, serverUrl: metadata.serverUrl, selector: selectorReadFileWithDownload, account: appDelegate.activeAccount)
  1197. }
  1198. }
  1199. }
  1200. }