NCMainCommon.swift 71 KB

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