NCMainCommon.swift 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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. import NCCommunication
  27. //MARK: - Main Common
  28. class NCMainCommon: NSObject, NCAudioRecorderViewControllerDelegate, UIDocumentInteractionControllerDelegate {
  29. @objc static let sharedInstance: NCMainCommon = {
  30. let instance = NCMainCommon()
  31. instance.createImagesThemingColor()
  32. return instance
  33. }()
  34. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  35. var metadataEditPhoto: tableMetadata?
  36. var docController: UIDocumentInteractionController?
  37. lazy var operationQueueReloadDatasource: OperationQueue = {
  38. let queue = OperationQueue()
  39. queue.name = "Reload main datasource queue"
  40. queue.maxConcurrentOperationCount = 1
  41. return queue
  42. }()
  43. //MARK: -
  44. struct NCMainCommonImages {
  45. static var cellSharedImage = UIImage()
  46. static var cellCanShareImage = UIImage()
  47. static var cellShareByLinkImage = UIImage()
  48. static var cellFavouriteImage = UIImage()
  49. static var cellMoreImage = UIImage()
  50. static var cellCommentImage = UIImage()
  51. static var cellFolderEncryptedImage = UIImage()
  52. static var cellFolderSharedWithMeImage = UIImage()
  53. static var cellFolderPublicImage = UIImage()
  54. static var cellFolderGroupImage = UIImage()
  55. static var cellFolderExternalImage = UIImage()
  56. static var cellFolderAutomaticUploadImage = UIImage()
  57. static var cellFolderImage = UIImage()
  58. static var cellPlayImage = UIImage()
  59. }
  60. @objc func createImagesThemingColor() {
  61. NCMainCommonImages.cellSharedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  62. NCMainCommonImages.cellCanShareImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.graySoft)
  63. NCMainCommonImages.cellShareByLinkImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  64. NCMainCommonImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  65. NCMainCommonImages.cellMoreImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  66. NCMainCommonImages.cellCommentImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "comment"), width: 30, height: 30, color: NCBrandColor.sharedInstance.graySoft)
  67. NCMainCommonImages.cellFolderEncryptedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderEncrypted"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  68. NCMainCommonImages.cellFolderSharedWithMeImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  69. NCMainCommonImages.cellFolderPublicImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_public"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  70. NCMainCommonImages.cellFolderGroupImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_group"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  71. NCMainCommonImages.cellFolderExternalImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_external"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  72. NCMainCommonImages.cellFolderAutomaticUploadImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderAutomaticUpload"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  73. NCMainCommonImages.cellFolderImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  74. NCMainCommonImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  75. }
  76. //MARK: -
  77. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceocIdIndexPath: NSDictionary, tableView: UITableView, viewController: UIViewController, serverUrlViewController: String?) {
  78. if viewController.viewIfLoaded?.window == nil {
  79. return
  80. }
  81. guard let dic = notification.userInfo else {
  82. return
  83. }
  84. let account = dic["account"] as? NSString ?? ""
  85. let ocId = dic["ocId"] as? NSString ?? ""
  86. let serverUrl = dic["serverUrl"] as? String ?? ""
  87. let status = dic["status"] as? Int ?? Int(k_taskIdentifierDone)
  88. let progress = dic["progress"] as? CGFloat ?? 0
  89. let totalBytes = dic["totalBytes"] as? Double ?? 0
  90. let totalBytesExpected = dic["totalBytesExpected"] as? Double ?? 0
  91. if (account != self.appDelegate.activeAccount! as NSString) && !(viewController is CCTransfers) {
  92. return
  93. }
  94. if serverUrlViewController != nil && serverUrlViewController! != serverUrl {
  95. return
  96. }
  97. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: ocId)
  98. guard let indexPath = sectionDataSourceocIdIndexPath.object(forKey: ocId) else {
  99. return
  100. }
  101. if isValidIndexPath(indexPath as! IndexPath, view: tableView) {
  102. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  103. var image = ""
  104. if status == k_metadataStatusInDownload {
  105. image = "↓"
  106. } else if status == k_metadataStatusInUpload {
  107. image = "↑"
  108. }
  109. cell.labelInfoFile?.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  110. cell.transferButton?.progress = progress
  111. }
  112. }
  113. }
  114. @objc func cancelTransferMetadata(_ metadata: tableMetadata, reloadDatasource: Bool, uploadStatusForcedStart: Bool) {
  115. var actionReloadDatasource = k_action_NULL
  116. var metadata = metadata
  117. if metadata.session.count == 0 { return }
  118. guard let session = CCNetworking.shared().getSessionfromSessionDescription(metadata.session) else { return }
  119. session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
  120. var cancel = false
  121. // DOWNLOAD
  122. if metadata.session.count > 0 && metadata.session.contains("download") {
  123. for task in downloadTasks {
  124. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  125. task.cancel()
  126. cancel = true
  127. }
  128. }
  129. if cancel == false {
  130. NCManageDatabase.sharedInstance.setMetadataSession("", sessionError: "", sessionSelector: "", sessionTaskIdentifier: Int(k_taskIdentifierDone), status: Int(k_metadataStatusNormal), predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  131. }
  132. actionReloadDatasource = k_action_MOD
  133. }
  134. // UPLOAD
  135. if metadata.session.count > 0 && metadata.session.contains("upload") {
  136. for task in uploadTasks {
  137. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  138. if uploadStatusForcedStart {
  139. metadata.status = Int(k_metadataStatusUploadForcedStart)
  140. metadata = NCManageDatabase.sharedInstance.addMetadata(metadata) ?? metadata
  141. }
  142. task.cancel()
  143. cancel = true
  144. }
  145. }
  146. if cancel == false {
  147. do {
  148. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  149. }
  150. catch { }
  151. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  152. }
  153. actionReloadDatasource = k_action_DEL
  154. }
  155. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  156. self.reloadDatasource(ServerUrl: metadata.serverUrl, ocId: metadata.ocId, action: actionReloadDatasource)
  157. }
  158. }
  159. }
  160. @objc func cancelAllTransfer() {
  161. // Delete k_metadataStatusWaitUpload OR k_metadataStatusUploadError
  162. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "status == %d OR status == %d", appDelegate.activeAccount, k_metadataStatusWaitUpload, k_metadataStatusUploadError))
  163. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  164. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "status != %d", k_metadataStatusNormal), sorted: "fileName", ascending: true) {
  165. for metadata in metadatas {
  166. // Modify
  167. if (metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusDownloadError) {
  168. metadata.session = ""
  169. metadata.sessionSelector = ""
  170. metadata.status = Int(k_metadataStatusNormal)
  171. NCManageDatabase.sharedInstance.addMetadata(metadata)
  172. }
  173. // Cancel Task
  174. if metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusUploading {
  175. self.cancelTransferMetadata(metadata, reloadDatasource: false, uploadStatusForcedStart: false)
  176. }
  177. }
  178. }
  179. }
  180. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  181. return
  182. }
  183. }
  184. //MARK: -
  185. func collectionViewCellForItemAt(_ indexPath: IndexPath, collectionView: UICollectionView, cell: UICollectionViewCell, metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, isEditMode: Bool, selectocId: [String], autoUploadFileName: String, autoUploadDirectory: String, hideButtonMore: Bool, downloadThumbnail: Bool, shares: [tableShare]?, source: UIViewController) {
  186. var tableShare: tableShare?
  187. // Share
  188. if shares != nil {
  189. for share in shares! {
  190. if share.fileName == metadata.fileName {
  191. tableShare = share
  192. break
  193. }
  194. }
  195. }
  196. // Download preview
  197. if downloadThumbnail {
  198. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: collectionView, indexPath: indexPath)
  199. }
  200. var isShare = false
  201. var isMounted = false
  202. if metadataFolder != nil {
  203. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  204. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  205. }
  206. if cell is NCListCell {
  207. let cell = cell as! NCListCell
  208. cell.delegate = source as? NCListCellDelegate
  209. cell.objectId = metadata.ocId
  210. cell.indexPath = indexPath
  211. cell.labelTitle.text = metadata.fileNameView
  212. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  213. cell.imageStatus.image = nil
  214. cell.imageLocal.image = nil
  215. cell.imageFavorite.image = nil
  216. cell.shared.image = nil
  217. if metadata.directory {
  218. if metadata.e2eEncrypted {
  219. cell.imageItem.image = NCMainCommonImages.cellFolderEncryptedImage
  220. } else if isShare {
  221. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  222. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  223. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  224. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  225. cell.imageItem.image = NCMainCommonImages.cellFolderPublicImage
  226. } else if metadata.mountType == "group" {
  227. cell.imageItem.image = NCMainCommonImages.cellFolderGroupImage
  228. } else if isMounted {
  229. cell.imageItem.image = NCMainCommonImages.cellFolderExternalImage
  230. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  231. cell.imageItem.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  232. } else {
  233. cell.imageItem.image = NCMainCommonImages.cellFolderImage
  234. }
  235. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  236. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  237. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  238. // Status image: passcode
  239. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  240. cell.imageStatus.image = UIImage.init(named: "passcode")
  241. }
  242. // Local image: offline
  243. if tableDirectory != nil && tableDirectory!.offline {
  244. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  245. }
  246. } else {
  247. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)) {
  248. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  249. } else {
  250. if metadata.iconName.count > 0 {
  251. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  252. } else {
  253. cell.imageItem.image = UIImage.init(named: "file")
  254. }
  255. }
  256. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  257. // image local
  258. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  259. if size > 0 {
  260. var tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  261. if tableLocalFile == nil && size == metadata.size {
  262. tableLocalFile = NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  263. }
  264. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  265. else { cell.imageLocal.image = UIImage.init(named: "local") }
  266. }
  267. }
  268. // image Favorite
  269. if metadata.favorite {
  270. cell.imageFavorite.image = NCMainCommonImages.cellFavouriteImage
  271. }
  272. // Share image
  273. if (isShare) {
  274. cell.shared.image = NCMainCommonImages.cellSharedImage
  275. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  276. cell.shared.image = NCMainCommonImages.cellShareByLinkImage
  277. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  278. cell.shared.image = NCMainCommonImages.cellSharedImage
  279. } else {
  280. cell.shared.image = NCMainCommonImages.cellCanShareImage
  281. }
  282. if metadata.ownerId != appDelegate.activeUserID {
  283. // Load avatar
  284. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + metadata.ownerId + ".png"
  285. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-avatar-" + metadata.ownerId + ".png"
  286. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  287. cell.shared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  288. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  289. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  290. } else {
  291. NCCommunication.sharedInstance.downloadAvatar(serverUrl: appDelegate.activeUrl, userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size), customUserAgent: nil, addCustomHeaders: nil, account: appDelegate.activeAccount) { (account, data, errorCode, errorMessage) in
  292. if errorCode == 0 && account == self.appDelegate.activeAccount {
  293. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  294. }
  295. }
  296. }
  297. }
  298. if isEditMode {
  299. cell.imageItemLeftConstraint.constant = 45
  300. cell.imageSelect.isHidden = false
  301. if selectocId.contains(metadata.ocId) {
  302. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  303. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  304. } else {
  305. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedNo"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  306. cell.backgroundView = nil
  307. }
  308. } else {
  309. cell.imageItemLeftConstraint.constant = 10
  310. cell.imageSelect.isHidden = true
  311. cell.backgroundView = nil
  312. }
  313. // Remove last separator
  314. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  315. cell.separator.isHidden = true
  316. } else {
  317. cell.separator.isHidden = false
  318. }
  319. } else if cell is NCGridCell {
  320. let cell = cell as! NCGridCell
  321. cell.delegate = source as? NCGridCellDelegate
  322. cell.objectId = metadata.ocId
  323. cell.indexPath = indexPath
  324. cell.labelTitle.text = metadata.fileNameView
  325. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  326. cell.imageStatus.image = nil
  327. cell.imageLocal.image = nil
  328. cell.imageFavorite.image = nil
  329. if metadata.directory {
  330. if metadata.e2eEncrypted {
  331. cell.imageItem.image = NCMainCommonImages.cellFolderEncryptedImage
  332. } else if isShare {
  333. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  334. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  335. cell.imageItem.image = NCMainCommonImages.cellFolderSharedWithMeImage
  336. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  337. cell.imageItem.image = NCMainCommonImages.cellFolderPublicImage
  338. } else if metadata.mountType == "group" {
  339. cell.imageItem.image = NCMainCommonImages.cellFolderGroupImage
  340. } else if isMounted {
  341. cell.imageItem.image = NCMainCommonImages.cellFolderExternalImage
  342. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  343. cell.imageItem.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  344. } else {
  345. cell.imageItem.image = NCMainCommonImages.cellFolderImage
  346. }
  347. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  348. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  349. // Status image: passcode
  350. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  351. cell.imageStatus.image = UIImage.init(named: "passcode")
  352. }
  353. // Local image: offline
  354. if tableDirectory != nil && tableDirectory!.offline {
  355. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  356. }
  357. } else {
  358. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)) {
  359. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  360. } else {
  361. if metadata.iconName.count > 0 {
  362. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  363. } else {
  364. cell.imageItem.image = UIImage.init(named: "file")
  365. }
  366. }
  367. // image Local
  368. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  369. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  370. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  371. else { cell.imageLocal.image = UIImage.init(named: "local") }
  372. }
  373. }
  374. // image Favorite
  375. if metadata.favorite {
  376. cell.imageFavorite.image = NCMainCommonImages.cellFavouriteImage
  377. }
  378. if isEditMode {
  379. cell.imageSelect.isHidden = false
  380. if selectocId.contains(metadata.ocId) {
  381. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  382. cell.backgroundView = NCUtility.sharedInstance.cellBlurEffect(with: cell.bounds)
  383. } else {
  384. cell.imageSelect.isHidden = true
  385. cell.backgroundView = nil
  386. }
  387. } else {
  388. cell.imageSelect.isHidden = true
  389. cell.backgroundView = nil
  390. }
  391. }
  392. }
  393. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String, tableShare: tableShare?) -> UITableViewCell {
  394. // Create File System
  395. if metadata.directory {
  396. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)
  397. } else {
  398. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  399. }
  400. // CCCell
  401. if metadata.status == k_metadataStatusNormal {
  402. // NORMAL
  403. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  404. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  405. cell.accessoryType = UITableViewCell.AccessoryType.none
  406. cell.file.image = nil
  407. cell.status.image = nil
  408. cell.favorite.image = nil
  409. cell.shared.image = nil
  410. cell.local.image = nil
  411. cell.comment.image = nil
  412. cell.shared.isUserInteractionEnabled = false
  413. cell.viewShared.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  414. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  415. // change color selection
  416. let selectionColor = UIView()
  417. selectionColor.backgroundColor = NCBrandColor.sharedInstance.select
  418. cell.selectedBackgroundView = selectionColor
  419. cell.tintColor = NCBrandColor.sharedInstance.brandElement
  420. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  421. cell.labelTitle.text = metadata.fileNameView
  422. // Download preview
  423. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: tableView, indexPath: indexPath)
  424. // Share
  425. var isShare = false
  426. var isMounted = false
  427. if metadataFolder != nil {
  428. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  429. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  430. }
  431. if metadata.directory {
  432. // lable Info
  433. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  434. // File Image & Image Title Segue
  435. if metadata.e2eEncrypted {
  436. cell.file.image = NCMainCommonImages.cellFolderEncryptedImage
  437. } else if isShare {
  438. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  439. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  440. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  441. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  442. cell.file.image = NCMainCommonImages.cellFolderPublicImage
  443. } else if metadata.mountType == "group" {
  444. cell.file.image = NCMainCommonImages.cellFolderGroupImage
  445. } else if isMounted {
  446. cell.file.image = NCMainCommonImages.cellFolderExternalImage
  447. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  448. cell.file.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  449. } else {
  450. cell.file.image = NCMainCommonImages.cellFolderImage
  451. }
  452. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  453. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  454. // Local image: offline
  455. if tableDirectory != nil && tableDirectory!.offline {
  456. cell.local.image = UIImage.init(named: "offlineFlag")
  457. }
  458. // Status image: passcode
  459. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  460. cell.status.image = UIImage.init(named: "passcode")
  461. }
  462. } else {
  463. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  464. // Lable Info
  465. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + ", " + CCUtility.transformedSize(metadata.size)
  466. // File Image
  467. if iconFileExists {
  468. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  469. } else {
  470. if metadata.iconName.count > 0 {
  471. cell.file.image = UIImage.init(named: metadata.iconName)
  472. } else {
  473. cell.file.image = UIImage.init(named: "file")
  474. }
  475. }
  476. // Local Image - Offline
  477. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  478. if size > 0 {
  479. var tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  480. if tableLocalFile == nil && size == metadata.size {
  481. tableLocalFile = NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  482. }
  483. if tableLocalFile != nil && tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  484. else { cell.local.image = UIImage.init(named: "local") }
  485. }
  486. // Status image: encrypted
  487. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.activeAccount, metadata.fileName))
  488. if tableE2eEncryption != nil && NCUtility.sharedInstance.isEncryptedMetadata(metadata) {
  489. cell.status.image = UIImage.init(named: "encrypted")
  490. }
  491. }
  492. //
  493. // File & Directory
  494. //
  495. // Favorite
  496. if metadata.favorite {
  497. cell.favorite.image = NCMainCommonImages.cellFavouriteImage
  498. }
  499. // Share image
  500. if !(metadataFolder?.e2eEncrypted ?? false) && !metadata.e2eEncrypted {
  501. if (isShare) {
  502. cell.shared.image = NCMainCommonImages.cellSharedImage
  503. } else if (tableShare != nil && tableShare!.shareType == Int(shareTypeLink.rawValue)) {
  504. cell.shared.image = NCMainCommonImages.cellShareByLinkImage
  505. } else if (tableShare != nil && tableShare!.shareType != Int(shareTypeLink.rawValue)) {
  506. cell.shared.image = NCMainCommonImages.cellSharedImage
  507. } else {
  508. cell.shared.image = NCMainCommonImages.cellCanShareImage
  509. }
  510. if metadata.ownerId != appDelegate.activeUserID {
  511. // Load avatar
  512. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-" + metadata.ownerId + ".png"
  513. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.activeUser, activeUrl: appDelegate.activeUrl) + "-avatar-" + metadata.ownerId + ".png"
  514. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  515. if let avatar = UIImage(contentsOfFile: fileNameSourceAvatar) {
  516. cell.shared.image = avatar
  517. }
  518. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  519. if let avatar = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar) {
  520. cell.shared.image = avatar
  521. }
  522. } else {
  523. NCCommunication.sharedInstance.downloadAvatar(serverUrl: appDelegate.activeUrl, userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size), customUserAgent: nil, addCustomHeaders: nil, account: appDelegate.activeAccount) { (account, data, errorCode, errorMessage) in
  524. if errorCode == 0 && account == self.appDelegate.activeAccount {
  525. cell.shared.image = NCUtility.sharedInstance.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  526. }
  527. }
  528. }
  529. }
  530. }
  531. // Comment
  532. if metadata.commentsUnread {
  533. cell.comment.image = NCMainCommonImages.cellCommentImage
  534. cell.labelTitleTrailingConstraint.constant = 160
  535. } else {
  536. cell.labelTitleTrailingConstraint.constant = 110
  537. }
  538. // More Image
  539. cell.more.image = NCMainCommonImages.cellMoreImage
  540. return cell
  541. } else {
  542. // TRASNFER
  543. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  544. cell.separatorInset = UIEdgeInsets.init(top: 0, left: 60, bottom: 0, right: 0)
  545. cell.accessoryType = UITableViewCell.AccessoryType.none
  546. cell.file.image = nil
  547. cell.status.image = nil
  548. cell.user.image = nil
  549. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  550. cell.labelTitle.text = metadata.fileNameView
  551. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  552. cell.transferButton.tintColor = NCBrandColor.sharedInstance.optionItem
  553. var progress: CGFloat = 0.0
  554. var totalBytes: Double = 0.0
  555. //var totalBytesExpected : Double = 0
  556. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  557. if progressArray != nil && progressArray?.count == 3 {
  558. progress = progressArray?.object(at: 0) as! CGFloat
  559. totalBytes = progressArray?.object(at: 1) as! Double
  560. //totalBytesExpected = progressArray?.object(at: 2) as! Double
  561. }
  562. // Write status on Label Info
  563. switch metadata.status {
  564. case Int(k_metadataStatusWaitDownload):
  565. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  566. progress = 0.0
  567. break
  568. case Int(k_metadataStatusInDownload):
  569. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  570. progress = 0.0
  571. break
  572. case Int(k_metadataStatusDownloading):
  573. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  574. break
  575. case Int(k_metadataStatusWaitUpload):
  576. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  577. progress = 0.0
  578. break
  579. case Int(k_metadataStatusInUpload):
  580. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  581. progress = 0.0
  582. break
  583. case Int(k_metadataStatusUploading):
  584. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  585. break
  586. default:
  587. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  588. progress = 0.0
  589. }
  590. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  591. if iconFileExists {
  592. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  593. } else {
  594. if metadata.iconName.count > 0 {
  595. cell.file.image = UIImage.init(named: metadata.iconName)
  596. } else {
  597. cell.file.image = UIImage.init(named: "file")
  598. }
  599. }
  600. // Session Upload Extension
  601. if metadata.session == k_upload_session_extension {
  602. cell.labelTitle.isEnabled = false
  603. cell.labelInfoFile.isEnabled = false
  604. } else {
  605. cell.labelTitle.isEnabled = true
  606. cell.labelInfoFile.isEnabled = true
  607. }
  608. // downloadFile
  609. if metadata.status == k_metadataStatusWaitDownload || metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status == k_metadataStatusDownloadError {
  610. //
  611. }
  612. // downloadFile Error
  613. if metadata.status == k_metadataStatusDownloadError {
  614. cell.status.image = UIImage.init(named: "statuserror")
  615. if metadata.sessionError.count == 0 {
  616. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  617. } else {
  618. cell.labelInfoFile.text = metadata.sessionError
  619. }
  620. }
  621. // uploadFile
  622. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  623. if (!iconFileExists) {
  624. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  625. }
  626. cell.labelTitle.isEnabled = false
  627. }
  628. // uploadFileError
  629. if metadata.status == k_metadataStatusUploadError {
  630. cell.labelTitle.isEnabled = false
  631. cell.status.image = UIImage.init(named: "statuserror")
  632. if !iconFileExists {
  633. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "uploadCloud"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  634. }
  635. if metadata.sessionError.count == 0 {
  636. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  637. } else {
  638. cell.labelInfoFile.text = metadata.sessionError
  639. }
  640. }
  641. // Progress
  642. cell.transferButton.progress = progress
  643. // User
  644. if metadata.account != appDelegate.activeAccount {
  645. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  646. if tableAccount != nil {
  647. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(tableAccount!.user, activeUrl: tableAccount!.url) + "-" + tableAccount!.user + ".png"
  648. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  649. if avatar != nil {
  650. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  651. let imageSize = avatarImageView?.bounds.size
  652. UIGraphicsBeginImageContext(imageSize!)
  653. let context = UIGraphicsGetCurrentContext()
  654. avatarImageView?.layer.render(in: context!)
  655. avatar = UIGraphicsGetImageFromCurrentImageContext()
  656. UIGraphicsEndImageContext()
  657. cell.user.image = avatar
  658. }
  659. }
  660. }
  661. return cell
  662. }
  663. }
  664. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  665. guard let indexPath = indexPath else {
  666. return nil
  667. }
  668. guard let sectionDataSource = sectionDataSource else {
  669. return nil
  670. }
  671. let section = indexPath.section + 1
  672. let row = indexPath.row + 1
  673. let totSections = sectionDataSource.sections.count
  674. if totSections < section || section > totSections {
  675. return nil
  676. }
  677. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  678. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  679. return nil
  680. }
  681. let totRows = filesID.count
  682. if totRows < row || row > totRows {
  683. return nil
  684. }
  685. let ocId = filesID.object(at: indexPath.row)
  686. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: ocId) as? tableMetadata
  687. return metadata
  688. }
  689. @objc func reloadDatasource(ServerUrl: String?, ocId: String?, action: Int32) {
  690. if operationQueueReloadDatasource.operationCount > 0 {
  691. return
  692. }
  693. if self.appDelegate.activeMain != nil && ServerUrl != nil && self.appDelegate.activeMain.serverUrl == ServerUrl {
  694. self.operationQueueReloadDatasource.addOperation {
  695. DispatchQueue.main.async {
  696. self.appDelegate.activeMain.reloadDatasource(ServerUrl, ocId: ocId, action: Int(action))
  697. }
  698. }
  699. }
  700. if self.appDelegate.activeFavorites != nil && self.appDelegate.activeFavorites.viewIfLoaded?.window != nil {
  701. self.operationQueueReloadDatasource.addOperation {
  702. DispatchQueue.main.async {
  703. self.appDelegate.activeFavorites.reloadDatasource(ocId, action: Int(action))
  704. }
  705. }
  706. }
  707. if self.appDelegate.activeTransfers != nil && self.appDelegate.activeTransfers.viewIfLoaded?.window != nil {
  708. self.operationQueueReloadDatasource.addOperation {
  709. DispatchQueue.main.async {
  710. self.appDelegate.activeTransfers.reloadDatasource(ocId, action: Int(action))
  711. }
  712. }
  713. }
  714. }
  715. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  716. if view is UICollectionView {
  717. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  718. }
  719. if view is UITableView {
  720. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  721. }
  722. return true
  723. }
  724. //MARK: - download Open Selector
  725. @objc func downloadOpen(metadata: tableMetadata, selector: String) {
  726. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  727. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_downloadedFile), object: nil, userInfo: ["metadata": metadata, "selector": selector, "errorCode": 0, "errorDescription": "" ])
  728. } else {
  729. metadata.session = k_download_session
  730. metadata.sessionError = ""
  731. metadata.sessionSelector = selector //selectorOpenIn
  732. metadata.status = Int(k_metadataStatusWaitDownload)
  733. NCManageDatabase.sharedInstance.addMetadata(metadata)
  734. reloadDatasource(ServerUrl: metadata.serverUrl, ocId: metadata.ocId, action: k_action_MOD)
  735. }
  736. }
  737. //MARK: - OpenIn
  738. func openIn(metadata: tableMetadata, selector: String) {
  739. docController = UIDocumentInteractionController(url: NSURL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) as URL)
  740. docController?.delegate = self
  741. if selector == selectorOpenInDetail {
  742. guard let barButtonItem = appDelegate.activeDetail.navigationItem.rightBarButtonItem else { return }
  743. guard let buttonItemView = barButtonItem.value(forKey: "view") as? UIView else { return }
  744. docController?.presentOptionsMenu(from: buttonItemView.frame, in: buttonItemView, animated: true)
  745. } else {
  746. guard let splitViewController = self.appDelegate.window?.rootViewController as? UISplitViewController, let view = splitViewController.viewControllers.first?.view, let frame = splitViewController.viewControllers.first?.view.frame else {
  747. return }
  748. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  749. }
  750. }
  751. //MARK: - OpenShare
  752. @objc func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  753. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  754. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  755. shareViewController.metadata = metadata
  756. shareViewController.indexPage = indexPage
  757. shareNavigationController.modalPresentationStyle = .formSheet
  758. ViewController.present(shareNavigationController, animated: true, completion: nil)
  759. }
  760. //MARK: - NCAudioRecorder
  761. func startAudioRecorder() {
  762. let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
  763. let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
  764. viewController.delegate = self
  765. viewController.createRecorder(fileName: fileName)
  766. viewController.modalTransitionStyle = .crossDissolve
  767. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  768. self.appDelegate.window.rootViewController?.present(viewController, animated: true, completion: nil)
  769. }
  770. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  771. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() else { return }
  772. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  773. let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadVoiceNote
  774. viewController.setup(serverUrl: appDelegate.activeMain.serverUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  775. self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
  776. }
  777. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  778. }
  779. }
  780. //MARK: - Main TabBarController
  781. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  782. override func viewDidLoad() {
  783. super.viewDidLoad()
  784. delegate = self
  785. }
  786. //Delegate methods
  787. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  788. let tabViewControllers = tabBarController.viewControllers!
  789. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  790. if let vc = viewController as? UINavigationController {
  791. vc.popToRootViewController(animated: true);
  792. }
  793. return false
  794. }
  795. animateToTab(toIndex: toIndex)
  796. return true
  797. }
  798. func animateToTab(toIndex: Int) {
  799. let tabViewControllers = viewControllers!
  800. let fromView = selectedViewController!.view!
  801. let toView = tabViewControllers[toIndex].view!
  802. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  803. guard fromIndex != toIndex else {return}
  804. // Add the toView to the tab bar view
  805. fromView.superview?.addSubview(toView)
  806. fromView.superview?.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  807. // Position toView off screen (to the left/right of fromView)
  808. let screenWidth = UIScreen.main.bounds.size.width;
  809. let scrollRight = toIndex > fromIndex!;
  810. let offset = (scrollRight ? screenWidth : -screenWidth)
  811. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  812. // Disable interaction during animation
  813. view.isUserInteractionEnabled = false
  814. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  815. // Slide the views by -offset
  816. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  817. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  818. }, completion: { finished in
  819. // Remove the old view from the tabbar view.
  820. fromView.removeFromSuperview()
  821. self.selectedIndex = toIndex
  822. self.view.isUserInteractionEnabled = true
  823. })
  824. }
  825. }
  826. //
  827. // https://stackoverflow.com/questions/44822558/ios-11-uitabbar-uitabbaritem-positioning-issue/46348796#46348796
  828. //
  829. extension UITabBar {
  830. // Workaround for iOS 11's new UITabBar behavior where on iPad, the UITabBar inside
  831. // the Master view controller shows the UITabBarItem icon next to the text
  832. override open var traitCollection: UITraitCollection {
  833. if UIDevice.current.userInterfaceIdiom == .pad {
  834. return UITraitCollection(horizontalSizeClass: .compact)
  835. }
  836. return super.traitCollection
  837. }
  838. }
  839. //MARK: - Networking Main
  840. class NCNetworkingMain: NSObject, IMImagemeterViewerDelegate {
  841. @objc static let sharedInstance: NCNetworkingMain = {
  842. let instance = NCNetworkingMain()
  843. return instance
  844. }()
  845. lazy var operationQueueNetworkingMain: OperationQueue = {
  846. let queue = OperationQueue()
  847. queue.name = "com.nextcloud.operationQueueNetworkingMain"
  848. queue.maxConcurrentOperationCount = 1
  849. return queue
  850. }()
  851. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  852. #if HC
  853. // IMImagemeterViewerDelegate
  854. func closeImagemeterViewer(metadata: tableMetadata?, bundleDirectory: String) {
  855. guard let metadata = metadata else { return }
  856. let ocIdTemp = NSUUID().uuidString.lowercased()
  857. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: metadata.fileName)!
  858. let bundleDirectoryURL = URL(fileURLWithPath: bundleDirectory)
  859. let fileNameZipUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(ocIdTemp, fileNameView: metadata.fileName))
  860. // Create IMI
  861. try? FileManager.default.removeItem(at: fileNameZipUrl)
  862. do {
  863. try FileManager().zipItem(at: bundleDirectoryURL, to:fileNameZipUrl)
  864. } catch {
  865. NCContentPresenter.shared.messageNotification("_error_", description: "Creation of IMI archive failed with error", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  866. return
  867. }
  868. // Verify if is changed
  869. if IMUtility.shared.IMIsChange(metadata: metadata, fileNameZipUrl: fileNameZipUrl) {
  870. let com = IMCommunication.init()
  871. _ = com.uploadFileIMI(serverUrl: metadata.serverUrl, fileName: metadata.fileName, fileNameLocalPath: fileNameLocalPath, ocId: ocIdTemp)
  872. }
  873. // Remove bundle directory
  874. try? FileManager.default.removeItem(atPath: bundleDirectory)
  875. }
  876. #endif
  877. @objc func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath) {
  878. operationQueueNetworkingMain.addOperation(NCOperationNetworkingMain.init(metadata: metadata, view: view, indexPath: indexPath, networkingFunc: "downloadThumbnail"))
  879. }
  880. func downloadThumbnail(with metadata: tableMetadata, view: Any, indexPath: IndexPath, closure: @escaping () -> ()) {
  881. if !metadata.isInvalidated && metadata.hasPreview && (!CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) || metadata.typeFile == k_metadataTypeFile_document) {
  882. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, activeUrl: appDelegate.activeUrl)!
  883. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  884. NCCommunication.sharedInstance.downloadPreview(serverUrl: appDelegate.activeUrl, fileNamePath: fileNamePath, fileNameLocalPath: fileNameLocalPath, width: Int(k_sizePreview), height: Int(k_sizePreview), customUserAgent: nil, addCustomHeaders: nil, account: metadata.account) { (account, data, errorCode, errorMessage) in
  885. if errorCode == 0 && data != nil {
  886. if let image = UIImage.init(data: data!) {
  887. if view is UICollectionView && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  888. if let cell = (view as! UICollectionView).cellForItem(at: indexPath) {
  889. if cell is NCListCell {
  890. (cell as! NCListCell).imageItem.image = image
  891. } else if cell is NCGridCell {
  892. (cell as! NCGridCell).imageItem.image = image
  893. } else if cell is NCGridMediaCell {
  894. (cell as! NCGridMediaCell).imageItem.image = image
  895. }
  896. }
  897. }
  898. if view is UITableView && CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileName) && NCMainCommon.sharedInstance.isValidIndexPath(indexPath, view: view) {
  899. if let cell = (view as! UITableView).cellForRow(at: indexPath) {
  900. if cell is CCCellMainTransfer {
  901. (cell as! CCCellMainTransfer).file.image = image
  902. } else if cell is CCCellMain {
  903. (cell as! CCCellMain).file.image = image
  904. }
  905. }
  906. }
  907. }
  908. }
  909. return closure()
  910. }
  911. }
  912. return closure()
  913. }
  914. }
  915. //MARK: - Operation Networking Main
  916. class NCOperationNetworkingMain: Operation {
  917. private var _executing : Bool = false
  918. override var isExecuting : Bool {
  919. get { return _executing }
  920. set {
  921. guard _executing != newValue else { return }
  922. willChangeValue(forKey: "isExecuting")
  923. _executing = newValue
  924. didChangeValue(forKey: "isExecuting")
  925. }
  926. }
  927. private var _finished : Bool = false
  928. override var isFinished : Bool {
  929. get { return _finished }
  930. set {
  931. guard _finished != newValue else { return }
  932. willChangeValue(forKey: "isFinished")
  933. _finished = newValue
  934. didChangeValue(forKey: "isFinished")
  935. }
  936. }
  937. private var metadata: tableMetadata?
  938. private var view: Any?
  939. private var indexPath: IndexPath?
  940. private var networkingFunc: String = ""
  941. init(metadata: tableMetadata?, view: Any?, indexPath: IndexPath?, networkingFunc: String) {
  942. super.init()
  943. if metadata != nil { self.metadata = metadata! }
  944. if view != nil { self.view = view! }
  945. if indexPath != nil { self.indexPath = indexPath! }
  946. self.networkingFunc = networkingFunc
  947. }
  948. override func start() {
  949. if !Thread.isMainThread {
  950. self.performSelector(onMainThread:#selector(start), with: nil, waitUntilDone: false)
  951. } else {
  952. isExecuting = true
  953. if isCancelled {
  954. finish()
  955. } else {
  956. poolNetworking()
  957. }
  958. }
  959. }
  960. func finish() {
  961. isExecuting = false
  962. isFinished = true
  963. }
  964. override func cancel() {
  965. super.cancel()
  966. if isExecuting {
  967. complete()
  968. }
  969. }
  970. func complete() {
  971. finish()
  972. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  973. }
  974. func poolNetworking() {
  975. UIApplication.shared.isNetworkActivityIndicatorVisible = true
  976. switch networkingFunc {
  977. case "downloadThumbnail":
  978. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata!, view: view!, indexPath: indexPath!) {
  979. self.complete()
  980. }
  981. default:
  982. print("error")
  983. }
  984. }
  985. }
  986. //MARK: - Function Main
  987. class NCFunctionMain: NSObject {
  988. @objc static let sharedInstance: NCFunctionMain = {
  989. let instance = NCFunctionMain()
  990. return instance
  991. }()
  992. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  993. @objc func synchronizeOffline() {
  994. let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true)
  995. if (directories != nil) {
  996. for directory: tableDirectory in directories! {
  997. CCSynchronize.shared()?.readFolder(directory.serverUrl, selector: selectorReadFolderWithDownload, account: appDelegate.activeAccount)
  998. }
  999. }
  1000. let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true)
  1001. if (files != nil) {
  1002. for file: tableLocalFile in files! {
  1003. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", file.ocId)) else {
  1004. continue
  1005. }
  1006. CCSynchronize.shared()?.readFile(metadata.ocId, fileName: metadata.fileName, serverUrl: metadata.serverUrl, selector: selectorReadFileWithDownload, account: appDelegate.activeAccount)
  1007. }
  1008. }
  1009. }
  1010. }