BackupRestoreView.swift 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. //
  2. // BackupRestoreView.swift
  3. // NexilisLite
  4. //
  5. // Created by Akhmad Al Qindi Irsyam on 16/02/23.
  6. //
  7. import UIKit
  8. import QuickLook
  9. //import Zip
  10. import NotificationBannerSwift
  11. import ZIPFoundation
  12. public class BackupRestoreView: UIViewController, UITableViewDataSource, UITableViewDelegate {
  13. private var tableView: UITableView!
  14. var centerLogo = UIImageView()
  15. var centerLogoIsRotated = false
  16. let activityIndicatorBackup = UIActivityIndicatorView(style: .medium)
  17. let activityIndicatorRestore = UIActivityIndicatorView(style: .medium)
  18. let titleBackup = UILabel()
  19. let titleRestore = UILabel()
  20. let titleLastBackup = UILabel()
  21. let titleTotalSize = UILabel()
  22. let labelRestoring = UILabel()
  23. let labelPreparing = UILabel()
  24. var isBackupStart = false
  25. var isRestoreStart = false
  26. var valueLastBackup = ""
  27. var valuesizeBackup = ""
  28. var dayLastBackup = ""
  29. var timeLastBackup = ""
  30. var choosenOption = "M"
  31. var fileIdBackup = ""
  32. var recordSizeBackup = ""
  33. var optionBackup = ""
  34. var recordSizeRestore: Int64 = 0
  35. let separator = String(unicodeCodepoint: 0x06) ?? ""
  36. public override func viewDidLoad() {
  37. super.viewDidLoad()
  38. navigationController?.navigationBar.topItem?.backButtonTitle = "Back".localized()
  39. tableView = UITableView()
  40. view.addSubview(tableView)
  41. tableView.anchor(top: view.safeAreaLayoutGuide.topAnchor, left: view.leftAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.rightAnchor)
  42. tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellBackupRestore")
  43. tableView.dataSource = self
  44. tableView.delegate = self
  45. tableView.separatorStyle = .none
  46. if #available(iOS 15.0, *) {
  47. tableView.sectionHeaderTopPadding = 0
  48. }
  49. let center: NotificationCenter = NotificationCenter.default
  50. center.addObserver(self, selector: #selector(backupAvailability(notification:)), name: NSNotification.Name(rawValue: "backupAvailability"), object: nil)
  51. requestBackupAvailability()
  52. }
  53. public override func viewDidAppear(_ animated: Bool) {
  54. self.navigationController?.navigationBar.topItem?.title = "Backup & Restore".localized()
  55. self.navigationController?.navigationBar.setNeedsLayout()
  56. self.title = "Backup & Restore".localized()
  57. }
  58. @objc private func backupAvailability(notification: NSNotification) {
  59. DispatchQueue.main.async { [self] in
  60. let data:[AnyHashable : Any] = notification.userInfo!
  61. if let message = data["message"] as? TMessage {
  62. fileIdBackup = message.getBody(key: CoreMessage_TMessageKey.FILE_ID, default_value: "")
  63. recordSizeBackup = message.getBody(key: CoreMessage_TMessageKey.RECORD_SIZE, default_value: "0")
  64. optionBackup = message.getBody(key: CoreMessage_TMessageKey.TYPE, default_value: "")
  65. let filesize = message.getBody(key: CoreMessage_TMessageKey.FILE_SIZE, default_value: "0")
  66. let createdDate = message.getBody(key: CoreMessage_TMessageKey.CREATED_DATE, default_value: "\(Date().currentTimeMillis())")
  67. if optionBackup != "AUTO" {
  68. let date = Date(milliseconds: Int64(createdDate)!)
  69. let calendar = Calendar.current
  70. if (calendar.isDateInToday(date)) {
  71. dayLastBackup = "Today".localized()
  72. } else {
  73. let startOfNow = calendar.startOfDay(for: Date())
  74. let startOfTimeStamp = calendar.startOfDay(for: date)
  75. let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
  76. let day = -(components.day!)
  77. if day == 1{
  78. dayLastBackup = "Yesterday".localized()
  79. } else {
  80. let formatter = DateFormatter()
  81. formatter.dateFormat = "dd MMMM yyyy"
  82. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  83. if lang == "id" {
  84. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  85. }
  86. let stringFormat = formatter.string(from: date as Date)
  87. dayLastBackup = stringFormat
  88. }
  89. }
  90. let formatter = DateFormatter()
  91. formatter.dateFormat = "HH:mm"
  92. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  93. timeLastBackup = formatter.string(from: date as Date)
  94. valueLastBackup = dayLastBackup.localized() + ", " + timeLastBackup
  95. valuesizeBackup = Units(bytes: Int64(filesize)!).getReadableUnit()
  96. tableView.beginUpdates()
  97. tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none)
  98. tableView.endUpdates()
  99. } else {
  100. valueLastBackup = "-"
  101. valuesizeBackup = "-"
  102. tableView.beginUpdates()
  103. tableView.reloadRows(at: [IndexPath(row: 0, section: 0), IndexPath(row: 0, section: 2)], with: .none)
  104. tableView.endUpdates()
  105. }
  106. }
  107. }
  108. }
  109. private func requestBackupAvailability() {
  110. DispatchQueue.global().async {
  111. _ = Nexilis.write(message: CoreMessage_TMessageBank.getBackupAvailability())
  112. }
  113. }
  114. private func getFileName(option: String = "", fileId: String = "", withoutZIP: Bool = false) -> String {
  115. if !fileId.isEmpty {
  116. if withoutZIP {
  117. return "\(User.getMyPin()!)_\(option)_\(fileId)"
  118. }
  119. return "\(User.getMyPin()!)_\(option)_\(fileId).zip"
  120. }
  121. return "\(User.getMyPin()!).zip"
  122. }
  123. public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  124. if section == 2 && isBackupStart {
  125. let container = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 20))
  126. container.addSubview(labelPreparing)
  127. labelPreparing.anchor(left: container.leftAnchor, paddingLeft: 10, centerY: container.centerYAnchor)
  128. labelPreparing.textColor = .gray
  129. labelPreparing.font = .systemFont(ofSize: 12)
  130. return container
  131. } else if section == 3 && isRestoreStart {
  132. let container = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 20))
  133. container.addSubview(labelRestoring)
  134. labelRestoring.anchor(left: container.leftAnchor, paddingLeft: 10, centerY: container.centerYAnchor)
  135. labelRestoring.textColor = .gray
  136. labelRestoring.font = .systemFont(ofSize: 12)
  137. return container
  138. }
  139. return UIView()
  140. }
  141. public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  142. if section == 2 && isBackupStart {
  143. return 30
  144. } else if section == 3 && isRestoreStart {
  145. return 30
  146. }
  147. return 20
  148. }
  149. public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
  150. .leastNormalMagnitude
  151. }
  152. public func numberOfSections(in tableView: UITableView) -> Int {
  153. return 4
  154. }
  155. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  156. if section == 1 {
  157. return 2
  158. } else if section == 3 {
  159. return 0
  160. }
  161. return 1
  162. }
  163. public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  164. let cell = tableView.dequeueReusableCell(withIdentifier: "cellBackupRestore", for: indexPath as IndexPath)
  165. makeViewBackup(cell: cell, indexPath: indexPath)
  166. return cell
  167. }
  168. public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  169. tableView.deselectRow(at: indexPath, animated: true)
  170. if indexPath.section == 1 && indexPath.row == 0 {
  171. let controller = BackupRestoreOption()
  172. controller.selected = choosenOption
  173. controller.isSelected = { choosen in
  174. self.choosenOption = choosen
  175. tableView.beginUpdates()
  176. tableView.reloadRows(at: [indexPath], with: .none)
  177. tableView.endUpdates()
  178. }
  179. navigationController?.show(controller, sender: nil)
  180. } else if indexPath.section == 1 && indexPath.row == 1 {
  181. if isBackupStart || isRestoreStart {
  182. return
  183. }
  184. if !CheckConnection.isConnectedToNetwork() {
  185. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  186. imageView.tintColor = .white
  187. let banner = FloatingNotificationBanner(title: "Check your connection".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  188. banner.show()
  189. return
  190. }
  191. isBackupStart = true
  192. labelPreparing.text = "Preparing...".localized();
  193. tableView.beginUpdates()
  194. tableView.reloadRows(at: [indexPath], with: .none)
  195. tableView.reloadSections(IndexSet(integer: 2), with: .none)
  196. tableView.endUpdates()
  197. animateBackup()
  198. backupData(indexPath: indexPath)
  199. } else if indexPath.section == 2 {
  200. if isBackupStart || isRestoreStart || valueLastBackup == "-" {
  201. return
  202. }
  203. if !CheckConnection.isConnectedToNetwork() {
  204. let imageView = UIImageView(image: UIImage(systemName: "xmark.circle.fill"))
  205. imageView.tintColor = .white
  206. let banner = FloatingNotificationBanner(title: "Check your connection".localized(), subtitle: nil, titleFont: UIFont.systemFont(ofSize: 16), titleColor: nil, titleTextAlign: .left, subtitleFont: nil, subtitleColor: nil, subtitleTextAlign: nil, leftView: imageView, rightView: nil, style: .danger, colors: nil, iconPosition: .center)
  207. banner.show()
  208. return
  209. }
  210. isRestoreStart = true
  211. labelRestoring.text = "Downloading...".localized();
  212. tableView.beginUpdates()
  213. tableView.reloadRows(at: [indexPath, IndexPath(row: 1, section: 1)], with: .none)
  214. tableView.reloadSections(IndexSet(integer: 3), with: .none)
  215. tableView.endUpdates()
  216. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  217. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  218. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  219. if let dirPath = paths.first {
  220. let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent(getFileName(option: optionBackup, fileId: fileIdBackup))
  221. if !FileManager.default.fileExists(atPath: fileURL.path) {
  222. Download().startHTTP(forKey: getFileName(option: optionBackup, fileId: fileIdBackup), isImage: false) { (name, progress) in
  223. DispatchQueue.main.async { [self] in
  224. guard progress == 100 else {
  225. labelRestoring.text = "Downloading...".localized() + " \(progress)%"
  226. return
  227. }
  228. labelRestoring.text = "Restoring...".localized()
  229. restoreData(file: fileURL, dirPath: dirPath, indexPath: indexPath)
  230. }
  231. }
  232. } else {
  233. labelRestoring.text = "Restoring...".localized()
  234. restoreData(file: fileURL, dirPath: dirPath, indexPath: indexPath)
  235. }
  236. }
  237. }
  238. }
  239. private func animateBackup() {
  240. UIView.animate(withDuration: 2, animations: { [self] in
  241. centerLogo.transform = centerLogo.transform.rotated(by: .pi)
  242. })
  243. UIView.animate(withDuration: 2, animations: { [self] in
  244. centerLogo.transform = centerLogo.transform.rotated(by: .pi)
  245. })
  246. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { [self] in
  247. if isBackupStart {
  248. animateBackup()
  249. }
  250. })
  251. }
  252. private func enableButtonBackup() {
  253. titleBackup.text = "Back Up Now".localized()
  254. titleBackup.textColor = .systemBlue
  255. activityIndicatorBackup.stopAnimating()
  256. }
  257. private func disableButtonBackup(isRestore: Bool = false) {
  258. titleBackup.textColor = .gray
  259. if !isRestore{
  260. titleBackup.text = "Backing Up...".localized()
  261. activityIndicatorBackup.startAnimating()
  262. }
  263. }
  264. private func enableButtonRestore() {
  265. titleRestore.text = "Restore Now".localized()
  266. titleRestore.textColor = .systemBlue
  267. activityIndicatorRestore.stopAnimating()
  268. }
  269. private func disableButtonRestore(isBackup: Bool = false) {
  270. titleRestore.textColor = .gray
  271. if !isBackup && !activityIndicatorRestore.isAnimating {
  272. titleRestore.text = "Restoring...".localized()
  273. activityIndicatorRestore.startAnimating()
  274. } else {
  275. titleRestore.text = "Restore Now".localized()
  276. activityIndicatorRestore.stopAnimating()
  277. }
  278. }
  279. private func makeViewBackup(cell: UITableViewCell, indexPath: IndexPath) {
  280. cell.contentView.subviews.forEach { $0.removeFromSuperview() }
  281. if indexPath.section == 0 {
  282. cell.selectionStyle = .none
  283. let container = UIView()
  284. container.addTopBorder(with: .lightGray.withAlphaComponent(0.5), andWidth: 1)
  285. container.addBottomBorder(with: .lightGray.withAlphaComponent(0.5), andWidth: 1)
  286. let content = cell.contentView
  287. content.addSubview(container)
  288. container.anchor(top: content.topAnchor, left: content.leftAnchor, bottom: content.bottomAnchor, right: content.rightAnchor)
  289. let containerLogo = UIView()
  290. containerLogo.layer.borderWidth = 1
  291. containerLogo.layer.borderColor = UIColor.lightGray.cgColor
  292. containerLogo.layer.cornerRadius = 8
  293. containerLogo.clipsToBounds = true
  294. container.addSubview(containerLogo)
  295. containerLogo.anchor(top: container.topAnchor, left: container.leftAnchor, paddingTop: 10, paddingLeft: 10, width: 70, height: 70)
  296. let logo = UIImageView()
  297. logo.image = UIImage(systemName: "icloud")
  298. logo.contentMode = .scaleAspectFit
  299. logo.tintColor = .systemBlue
  300. containerLogo.addSubview(logo)
  301. logo.anchor(centerX: containerLogo.centerXAnchor, centerY: containerLogo.centerYAnchor, width: 60, height: 60)
  302. centerLogo.image = UIImage(systemName: "arrow.clockwise")
  303. centerLogo.contentMode = .scaleAspectFit
  304. centerLogo.tintColor = .systemBlue
  305. if !isBackupStart {
  306. if !centerLogoIsRotated{
  307. centerLogoIsRotated = true
  308. centerLogo.transform = centerLogo.transform.rotated(by: .pi / 2)
  309. //print("LOHE \(centerLogo.transform)")
  310. }
  311. }
  312. logo.addSubview(centerLogo)
  313. centerLogo.anchor(top: logo.topAnchor, left: logo.leftAnchor, paddingTop: 22, paddingLeft: 23)
  314. container.addSubview(titleLastBackup)
  315. titleLastBackup.anchor(top: container.topAnchor, left: containerLogo.rightAnchor, paddingTop: 25, paddingLeft: 10)
  316. titleLastBackup.text = "Last Backup".localized() + ": " + valueLastBackup
  317. titleLastBackup.textColor = .gray
  318. titleLastBackup.font = .systemFont(ofSize: 12)
  319. container.addSubview(titleTotalSize)
  320. titleTotalSize.anchor(top: titleLastBackup.bottomAnchor, left: containerLogo.rightAnchor, paddingLeft: 10)
  321. titleTotalSize.text = "Total Size".localized() + ": " + valuesizeBackup
  322. titleTotalSize.textColor = .gray
  323. titleTotalSize.font = .systemFont(ofSize: 12)
  324. let descBackup = UILabel()
  325. container.addSubview(descBackup)
  326. descBackup.anchor(top: containerLogo.bottomAnchor, left: container.leftAnchor, bottom: container.bottomAnchor, right: container.rightAnchor, paddingTop: 2, paddingLeft: 10, paddingBottom: 10, paddingRight: 10)
  327. descBackup.text = "Back up your chat history to server so if you lose your phone or switch to a new one or logout your account, your chat history is safe. You can restore your chat history when you relogin your account.".localized()
  328. descBackup.numberOfLines = 0
  329. descBackup.textColor = self.traitCollection.userInterfaceStyle == .dark ? .white : .black
  330. descBackup.font = .systemFont(ofSize: 12)
  331. } else if indexPath.section == 1 {
  332. if indexPath.row == 0 {
  333. let container = UIView()
  334. container.addTopBorder(with: .lightGray.withAlphaComponent(0.5), andWidth: 1)
  335. container.addBottomBorder(with: .lightGray.withAlphaComponent(0.5), andWidth: 0.5, x: 10)
  336. let content = cell.contentView
  337. content.addSubview(container)
  338. container.anchor(top: content.topAnchor, left: content.leftAnchor, bottom: content.bottomAnchor, right: content.rightAnchor)
  339. let titleBackupOption = UILabel()
  340. container.addSubview(titleBackupOption)
  341. titleBackupOption.anchor(left: container.leftAnchor, paddingLeft: 10, centerY: container.centerYAnchor)
  342. titleBackupOption.text = "Back Up Option".localized()
  343. titleBackupOption.textColor = .systemBlue
  344. titleBackupOption.font = .systemFont(ofSize: 14)
  345. let arrowRight = UIImageView()
  346. arrowRight.tintColor = .gray
  347. arrowRight.image = UIImage(systemName: "chevron.right")
  348. container.addSubview(arrowRight)
  349. arrowRight.anchor(right: container.rightAnchor, paddingRight: 10, centerY: container.centerYAnchor)
  350. let titleChoosenOption = UILabel()
  351. container.addSubview(titleChoosenOption)
  352. titleChoosenOption.anchor(right: arrowRight.leftAnchor, paddingRight: 10, centerY: container.centerYAnchor)
  353. titleChoosenOption.text = BackupRestoreOption().convertSelectedOptionWithCode(code: choosenOption)
  354. titleChoosenOption.textColor = .lightGray
  355. titleChoosenOption.font = .systemFont(ofSize: 14)
  356. } else {
  357. let container = UIView()
  358. container.addBottomBorder(with: .lightGray.withAlphaComponent(0.5), andWidth: 1)
  359. let content = cell.contentView
  360. content.addSubview(container)
  361. container.anchor(top: content.topAnchor, left: content.leftAnchor, bottom: content.bottomAnchor, right: content.rightAnchor)
  362. container.addSubview(titleBackup)
  363. titleBackup.anchor(left: container.leftAnchor, paddingLeft: 10, centerY: container.centerYAnchor)
  364. titleBackup.font = .systemFont(ofSize: 14)
  365. container.addSubview(activityIndicatorBackup)
  366. activityIndicatorBackup.anchor(right: container.rightAnchor, paddingRight: 10, centerY: container.centerYAnchor)
  367. if isBackupStart || isRestoreStart {
  368. cell.selectionStyle = .none
  369. disableButtonBackup(isRestore: isRestoreStart)
  370. } else {
  371. cell.selectionStyle = .default
  372. enableButtonBackup()
  373. }
  374. }
  375. } else {
  376. let container = UIView()
  377. container.addTopBorder(with: .lightGray.withAlphaComponent(0.5), andWidth: 1)
  378. container.addBottomBorder(with: .lightGray.withAlphaComponent(0.5), andWidth: 1)
  379. let content = cell.contentView
  380. content.addSubview(container)
  381. container.anchor(top: content.topAnchor, left: content.leftAnchor, bottom: content.bottomAnchor, right: content.rightAnchor)
  382. container.addSubview(titleRestore)
  383. titleRestore.anchor(left: container.leftAnchor, paddingLeft: 10, centerY: container.centerYAnchor)
  384. titleRestore.font = .systemFont(ofSize: 14)
  385. container.addSubview(activityIndicatorRestore)
  386. activityIndicatorRestore.anchor(right: container.rightAnchor, paddingRight: 10, centerY: container.centerYAnchor)
  387. if isBackupStart || isRestoreStart || valueLastBackup == "-" {
  388. cell.selectionStyle = .none
  389. disableButtonRestore(isBackup: isBackupStart || valueLastBackup == "-")
  390. } else {
  391. cell.selectionStyle = .default
  392. enableButtonRestore()
  393. }
  394. }
  395. }
  396. private func restoreMessage(nameColumn: [String], message: [String]) {
  397. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  398. do {
  399. var cValues: [String: Any] = [:]
  400. var columnNameMessage: [String] = []
  401. if let tableInfo = Database.shared.getRecords(fmdb: fmdb,query: "PRAGMA table_info(MESSAGE)") {
  402. while tableInfo.next() {
  403. columnNameMessage.append(tableInfo.string(forColumn: "name")!)
  404. }
  405. tableInfo.close()
  406. }
  407. for i in 0..<message.count {
  408. if i > nameColumn.count - 1 {
  409. continue
  410. }
  411. if columnNameMessage.contains(nameColumn[i]) {
  412. cValues[nameColumn[i]] = message[i] == "<empty>" || message[i] == "null" ? "" : message[i]
  413. }
  414. }
  415. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE", cvalues: cValues, replace: true)
  416. if !(cValues["thumb_id"] as? String ?? "").isEmpty {
  417. let thumbId = cValues["thumb_id"] as! String
  418. let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  419. let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  420. let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  421. if let dirPath = paths.first {
  422. let thumbURL = URL(fileURLWithPath: dirPath).appendingPathComponent(thumbId)
  423. if !FileManager.default.fileExists(atPath: thumbURL.path) {
  424. Download().startHTTP(forKey: thumbId) { (name, progress) in}
  425. }
  426. }
  427. }
  428. recordSizeRestore += 1
  429. } catch {
  430. rollback.pointee = true
  431. print("Access database error: \(error.localizedDescription)")
  432. }
  433. })
  434. }
  435. private func restoreUcList(dataUcList: [String]) {
  436. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  437. do {
  438. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", cvalues: [
  439. "l_pin" : dataUcList[0],
  440. "message_id" : dataUcList[1],
  441. "counter" : 0
  442. ], replace: true)
  443. recordSizeRestore += 1
  444. } catch {
  445. rollback.pointee = true
  446. print("Access database error: \(error.localizedDescription)")
  447. }
  448. })
  449. }
  450. private func restoreFormData(nameColumn: [String], data: [String]) {
  451. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  452. do {
  453. var cValues: [String: Any] = [:]
  454. var columnNameMessage: [String] = []
  455. if let tableInfo = Database.shared.getRecords(fmdb: fmdb,query: "PRAGMA table_info(FORM_DATA)") {
  456. while tableInfo.next() {
  457. columnNameMessage.append(tableInfo.string(forColumn: "name")!)
  458. }
  459. tableInfo.close()
  460. }
  461. for i in 0..<data.count {
  462. if columnNameMessage.contains(nameColumn[i]) {
  463. cValues[nameColumn[i]] = data[i] == "<empty>" || data[i] == "null" ? "" : data[i]
  464. }
  465. }
  466. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "FORM_DATA", cvalues: cValues, replace: true)
  467. recordSizeRestore += 1
  468. } catch {
  469. rollback.pointee = true
  470. print("Access database error: \(error.localizedDescription)")
  471. }
  472. })
  473. }
  474. private func restoreTaskPIC(nameColumn: [String], data: [String]) {
  475. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  476. do {
  477. var cValues: [String: Any] = [:]
  478. var columnNameMessage: [String] = []
  479. if let tableInfo = Database.shared.getRecords(fmdb: fmdb,query: "PRAGMA table_info(TASK_PIC)") {
  480. while tableInfo.next() {
  481. columnNameMessage.append(tableInfo.string(forColumn: "name")!)
  482. }
  483. tableInfo.close()
  484. }
  485. for i in 0..<data.count {
  486. if columnNameMessage.contains(nameColumn[i]) {
  487. cValues[nameColumn[i]] = data[i] == "<empty>" || data[i] == "null" ? "" : data[i]
  488. }
  489. }
  490. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "TASK_PIC", cvalues: cValues, replace: true)
  491. recordSizeRestore += 1
  492. } catch {
  493. rollback.pointee = true
  494. print("Access database error: \(error.localizedDescription)")
  495. }
  496. })
  497. }
  498. private func restoreTaskDetail(nameColumn: [String], data: [String]) {
  499. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  500. do {
  501. var cValues: [String: Any] = [:]
  502. var columnNameMessage: [String] = []
  503. if let tableInfo = Database.shared.getRecords(fmdb: fmdb,query: "PRAGMA table_info(TASK_DETAIL)") {
  504. while tableInfo.next() {
  505. columnNameMessage.append(tableInfo.string(forColumn: "name")!)
  506. }
  507. tableInfo.close()
  508. }
  509. for i in 0..<data.count {
  510. if columnNameMessage.contains(nameColumn[i]) {
  511. cValues[nameColumn[i]] = data[i] == "<empty>" || data[i] == "null" ? "" : data[i]
  512. }
  513. }
  514. _ = try Database.shared.insertRecord(fmdb: fmdb, table: "TASK_DETAIL", cvalues: cValues, replace: true)
  515. recordSizeRestore += 1
  516. } catch {
  517. rollback.pointee = true
  518. print("Access database error: \(error.localizedDescription)")
  519. }
  520. })
  521. }
  522. private func restoreData(file: URL, dirPath: String, indexPath: IndexPath) {
  523. recordSizeRestore = 0
  524. let fileManager = FileManager()
  525. var destinationURL = URL(fileURLWithPath: dirPath)
  526. destinationURL.appendPathComponent("unzipItem\(Date().currentTimeMillis())")
  527. do {
  528. try fileManager.createDirectory(at: destinationURL, withIntermediateDirectories: true, attributes: nil)
  529. // try Zip.unzipFile(file, destination: destinationURL, overwrite: true, password: nil)
  530. try fileManager.unzipItem(at: file, to: destinationURL)
  531. let files = try FileManager.default.contentsOfDirectory(atPath: destinationURL.path)
  532. for file in files {
  533. let nameFile = (file as NSString).lastPathComponent
  534. let fileURL = destinationURL.appendingPathComponent(nameFile)
  535. var newFileExt: URL?
  536. newFileExt = fileURL.deletingPathExtension().appendingPathExtension("txt")
  537. try FileManager.default.moveItem(at: fileURL, to: newFileExt!)
  538. var textReading = try String(contentsOf: newFileExt ?? fileURL, encoding: .utf8)
  539. textReading = textReading.replacingOccurrences(of: "<NL>", with: "\n").replacingOccurrences(of: "<CR>", with: "\r")
  540. let valueText = textReading.components(separatedBy: "\n")
  541. if nameFile.trimmingCharacters(in: .whitespacesAndNewlines) == "MESSAGE" {
  542. let nameColumn = valueText[0].components(separatedBy: separator)
  543. for i in 1..<valueText.count - 1 {
  544. let dataMessage = valueText[i].components(separatedBy: separator)
  545. restoreMessage(nameColumn: nameColumn, message: dataMessage)
  546. }
  547. } else if nameFile.trimmingCharacters(in: .whitespacesAndNewlines) == "UC_LIST" {
  548. for i in 1..<valueText.count - 1 {
  549. let dataUcList = valueText[i].components(separatedBy: separator)
  550. restoreUcList(dataUcList: dataUcList)
  551. }
  552. } else if nameFile.trimmingCharacters(in: .whitespacesAndNewlines) == "FORM_DATA" {
  553. let nameColumn = valueText[0].components(separatedBy: separator)
  554. for i in 1..<valueText.count - 1 {
  555. let dataFormData = valueText[i].components(separatedBy: separator)
  556. restoreFormData(nameColumn: nameColumn, data: dataFormData)
  557. }
  558. } else if nameFile.trimmingCharacters(in: .whitespacesAndNewlines) == "TASK_PIC" {
  559. let nameColumn = valueText[0].components(separatedBy: separator)
  560. for i in 1..<valueText.count - 1 {
  561. let dataTaskPIC = valueText[i].components(separatedBy: separator)
  562. restoreTaskPIC(nameColumn: nameColumn, data: dataTaskPIC)
  563. }
  564. }
  565. else if nameFile.trimmingCharacters(in: .whitespacesAndNewlines) == "TASK_DETAIL" {
  566. let nameColumn = valueText[0].components(separatedBy: separator)
  567. for i in 1..<valueText.count - 1 {
  568. let dataTaskDetail = valueText[i].components(separatedBy: separator)
  569. restoreTaskDetail(nameColumn: nameColumn, data: dataTaskDetail)
  570. }
  571. }
  572. }
  573. if recordSizeRestore < Int64(recordSizeBackup) ?? 0 {
  574. labelRestoring.text = "Backup files are corrupted".localized()
  575. tableView.reloadSections(IndexSet(integer: 3), with: .none)
  576. } else {
  577. labelRestoring.text = "Successfully Restored Data".localized()
  578. }
  579. // DispatchQueue.global().async { [self] in
  580. // _ = Nexilis.write(message: CoreMessage_TMessageBank.getBackupRestored(option: optionBackup, fileid: fileIdBackup))
  581. // }
  582. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { [self] in
  583. isRestoreStart = false
  584. valueLastBackup = "-"
  585. valuesizeBackup = "-"
  586. tableView.beginUpdates()
  587. tableView.reloadRows(at: [indexPath, IndexPath(row: 1, section: 1), IndexPath(row: 0, section: 0), IndexPath(row: 0, section: 2)], with: .none)
  588. tableView.reloadSections(IndexSet(integer: 3), with: .none)
  589. tableView.endUpdates()
  590. })
  591. } catch {
  592. //print(error)
  593. self.view.makeToast("Backup files are corrupted".localized(), duration: 3)
  594. // DispatchQueue.global().async { [self] in
  595. // _ = Nexilis.write(message: CoreMessage_TMessageBank.getBackupRestored(option: optionBackup, fileid: fileIdBackup))
  596. // }
  597. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { [self] in
  598. isRestoreStart = false
  599. valueLastBackup = "-"
  600. valuesizeBackup = "-"
  601. tableView.beginUpdates()
  602. tableView.reloadRows(at: [indexPath, IndexPath(row: 1, section: 1), IndexPath(row: 0, section: 0), IndexPath(row: 0, section: 2)], with: .none)
  603. tableView.reloadSections(IndexSet(integer: 3), with: .none)
  604. tableView.endUpdates()
  605. })
  606. }
  607. }
  608. private func backupData(indexPath: IndexPath) {
  609. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  610. do {
  611. let documentDirectoryUrl = try! FileManager.default.url(
  612. for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true
  613. )
  614. var recordSize: Int64 = 0
  615. //Make File MESSAGE
  616. let file_message = documentDirectoryUrl.appendingPathComponent("MESSAGE").appendingPathExtension("")
  617. if let tableInfo = Database.shared.getRecords(fmdb: fmdb,query: "PRAGMA table_info(MESSAGE)") {
  618. var text_message = ""
  619. while tableInfo.next() {
  620. if text_message.isEmpty {
  621. text_message.append(tableInfo.string(forColumn: "name")!)
  622. } else {
  623. text_message.append(separator)
  624. text_message.append(tableInfo.string(forColumn: "name")!)
  625. }
  626. }
  627. text_message.append("\n")
  628. tableInfo.close()
  629. if let cursorData = Database.shared.getRecords(fmdb: fmdb,query: "SELECT * FROM MESSAGE") {
  630. let columnCount = cursorData.columnCount
  631. var value_m = ""
  632. while cursorData.next() {
  633. for i in 0..<columnCount {
  634. value_m.append(cursorData.string(forColumnIndex: i) == nil ? "null" : cursorData.string(forColumnIndex: i)!.isEmpty ? "<empty>" : cursorData.string(forColumnIndex: i)!)
  635. value_m.append(separator)
  636. }
  637. value_m.append("\n")
  638. recordSize += 1
  639. }
  640. text_message.append(value_m)
  641. cursorData.close()
  642. }
  643. do {
  644. try text_message.write(to: file_message, atomically: true, encoding: .utf8)
  645. }
  646. catch {
  647. //print(error)
  648. }
  649. }
  650. //Make File UC_LIST
  651. let file_uc_list = documentDirectoryUrl.appendingPathComponent("UC_LIST").appendingPathExtension("")
  652. if let tableInfo = Database.shared.getRecords(fmdb: fmdb,query: "PRAGMA table_info(MESSAGE_SUMMARY)") {
  653. var text_uc_list = ""
  654. while tableInfo.next() {
  655. if tableInfo.string(forColumn: "name")! == "counter" {
  656. continue
  657. }
  658. if text_uc_list.isEmpty {
  659. text_uc_list.append(tableInfo.string(forColumn: "name")! == "l_pin" ? "opposite" : tableInfo.string(forColumn: "name")!)
  660. } else {
  661. text_uc_list.append(separator)
  662. text_uc_list.append(tableInfo.string(forColumn: "name")! == "l_pin" ? "opposite" : tableInfo.string(forColumn: "name")!)
  663. }
  664. }
  665. text_uc_list.append("\n")
  666. tableInfo.close()
  667. if let cursorData = Database.shared.getRecords(fmdb: fmdb,query: "SELECT * FROM MESSAGE_SUMMARY") {
  668. let columnCount = cursorData.columnCount
  669. var value_m = ""
  670. while cursorData.next() {
  671. for i in 0..<columnCount - 1 {
  672. value_m.append(cursorData.string(forColumnIndex: i) == nil ? "null" : cursorData.string(forColumnIndex: i)!.isEmpty ? "<empty>" : cursorData.string(forColumnIndex: i)!)
  673. value_m.append(separator)
  674. }
  675. value_m.append("\n")
  676. recordSize += 1
  677. }
  678. text_uc_list.append(value_m)
  679. cursorData.close()
  680. }
  681. do {
  682. try text_uc_list.write(to: file_uc_list, atomically: true, encoding: .utf8)
  683. }
  684. catch {//print(error)
  685. }
  686. }
  687. //Make File FORM_DATA
  688. let file_form_data = documentDirectoryUrl.appendingPathComponent("FORM_DATA").appendingPathExtension("")
  689. if let tableInfo = Database.shared.getRecords(fmdb: fmdb,query: "PRAGMA table_info(FORM_DATA)") {
  690. var text_form_data = ""
  691. while tableInfo.next() {
  692. if text_form_data.isEmpty {
  693. text_form_data.append(tableInfo.string(forColumn: "name")!)
  694. } else {
  695. text_form_data.append(separator)
  696. text_form_data.append(tableInfo.string(forColumn: "name")!)
  697. }
  698. }
  699. text_form_data.append("\n")
  700. tableInfo.close()
  701. if let cursorData = Database.shared.getRecords(fmdb: fmdb,query: "SELECT * FROM FORM_DATA") {
  702. let columnCount = cursorData.columnCount
  703. var value_m = ""
  704. while cursorData.next() {
  705. for i in 0..<columnCount - 1 {
  706. value_m.append(cursorData.string(forColumnIndex: i) == nil ? "null" : cursorData.string(forColumnIndex: i)!.isEmpty ? "<empty>" : cursorData.string(forColumnIndex: i)!)
  707. value_m.append(separator)
  708. }
  709. value_m.append("\n")
  710. recordSize += 1
  711. }
  712. text_form_data.append(value_m)
  713. cursorData.close()
  714. }
  715. do {
  716. try text_form_data.write(to: file_form_data, atomically: true, encoding: .utf8)
  717. }
  718. catch {//print(error)
  719. }
  720. }
  721. //Make File TASK_PIC
  722. let file_task_pic = documentDirectoryUrl.appendingPathComponent("TASK_PIC").appendingPathExtension("")
  723. if let tableInfo = Database.shared.getRecords(fmdb: fmdb,query: "PRAGMA table_info(TASK_PIC)") {
  724. var text_task_pic = ""
  725. while tableInfo.next() {
  726. if text_task_pic.isEmpty {
  727. text_task_pic.append(tableInfo.string(forColumn: "name")!)
  728. } else {
  729. text_task_pic.append(separator)
  730. text_task_pic.append(tableInfo.string(forColumn: "name")!)
  731. }
  732. }
  733. text_task_pic.append("\n")
  734. tableInfo.close()
  735. if let cursorData = Database.shared.getRecords(fmdb: fmdb,query: "SELECT * FROM TASK_PIC") {
  736. let columnCount = cursorData.columnCount
  737. var value_m = ""
  738. while cursorData.next() {
  739. for i in 0..<columnCount - 1 {
  740. value_m.append(cursorData.string(forColumnIndex: i) == nil ? "null" : cursorData.string(forColumnIndex: i)!.isEmpty ? "<empty>" : cursorData.string(forColumnIndex: i)!)
  741. value_m.append(separator)
  742. }
  743. value_m.append("\n")
  744. recordSize += 1
  745. }
  746. text_task_pic.append(value_m)
  747. cursorData.close()
  748. }
  749. do {
  750. try text_task_pic.write(to: file_task_pic, atomically: true, encoding: .utf8)
  751. }
  752. catch {//print(error)
  753. }
  754. }
  755. //Make File TASK_DETAIL
  756. let file_task_detail = documentDirectoryUrl.appendingPathComponent("TASK_DETAIL").appendingPathExtension("")
  757. if let tableInfo = Database.shared.getRecords(fmdb: fmdb,query: "PRAGMA table_info(TASK_DETAIL)") {
  758. var text_task_detail = ""
  759. while tableInfo.next() {
  760. if text_task_detail.isEmpty {
  761. text_task_detail.append(tableInfo.string(forColumn: "name")!)
  762. } else {
  763. text_task_detail.append(separator)
  764. text_task_detail.append(tableInfo.string(forColumn: "name")!)
  765. }
  766. }
  767. text_task_detail.append("\n")
  768. tableInfo.close()
  769. if let cursorData = Database.shared.getRecords(fmdb: fmdb,query: "SELECT * FROM TASK_DETAIL") {
  770. let columnCount = cursorData.columnCount
  771. var value_m = ""
  772. while cursorData.next() {
  773. for i in 0..<columnCount - 1 {
  774. value_m.append(cursorData.string(forColumnIndex: i) == nil ? "null" : cursorData.string(forColumnIndex: i)!.isEmpty ? "<empty>" : cursorData.string(forColumnIndex: i)!)
  775. value_m.append(separator)
  776. }
  777. value_m.append("\n")
  778. recordSize += 1
  779. }
  780. text_task_detail.append(value_m)
  781. cursorData.close()
  782. }
  783. do {
  784. try text_task_detail.write(to: file_task_detail, atomically: true, encoding: .utf8)
  785. }
  786. catch {//print(error)
  787. }
  788. }
  789. //ZIP ALL FILES
  790. let fileManager = FileManager()
  791. var destinationURL = documentDirectoryUrl
  792. destinationURL.appendPathComponent("zipItem\(Date().currentTimeMillis())")
  793. // let listFiles: [URL] = [file_message, file_uc_list, file_form_data, file_task_pic, file_task_detail]
  794. do {
  795. try fileManager.createDirectory(at: destinationURL, withIntermediateDirectories: true, attributes: nil)
  796. let zipFiles = destinationURL.appendingPathComponent(getFileName(option: choosenOption, fileId: fileIdBackup, withoutZIP: true)).appendingPathExtension("zip")
  797. // try Zip.zipFiles(paths: listFiles, zipFilePath: zipFiles, password: nil, progress: {progress in
  798. // self.labelPreparing.text = "Preparing...".localized() + " \(progress * 100)%"
  799. // })
  800. let unzipProgress = Progress()
  801. let observation = unzipProgress.observe(\.fractionCompleted) { progress, _ in
  802. self.labelPreparing.text = "Preparing...".localized() + " \(progress.fractionCompleted * 100)%"
  803. }
  804. try fileManager.zipItem(at: file_message, to: zipFiles, progress: unzipProgress)
  805. guard let archive = Archive(url: zipFiles, accessMode: .update) else {
  806. return
  807. }
  808. do {
  809. try archive.addEntry(with: file_uc_list.lastPathComponent, relativeTo: file_uc_list.deletingLastPathComponent())
  810. try archive.addEntry(with: file_form_data.lastPathComponent, relativeTo: file_form_data.deletingLastPathComponent())
  811. try archive.addEntry(with: file_task_pic.lastPathComponent, relativeTo: file_task_pic.deletingLastPathComponent())
  812. try archive.addEntry(with: file_task_detail.lastPathComponent, relativeTo: file_task_detail.deletingLastPathComponent())
  813. } catch {
  814. //print("Adding entry to ZIP archive failed with error:\(error)")
  815. }
  816. self.labelPreparing.text = "Uploading...".localized()
  817. Network().uploadHTTP(fileUrl: zipFiles, completion: { result,progress,response in
  818. if result {
  819. DispatchQueue.main.async { [self] in
  820. labelPreparing.text = "Uploading...".localized() + " \(progress)%"
  821. if progress == 100 {
  822. do {
  823. let path = zipFiles.path
  824. let attrib = try FileManager.default.attributesOfItem(atPath: path)
  825. let fileSize = attrib[.size] as! Int64
  826. DispatchQueue.global().async { [self] in
  827. _ = Nexilis.write(message: CoreMessage_TMessageBank.getBackupUploaded(option: choosenOption, fileid: fileIdBackup, filesize: String(fileSize), recordSize: String(recordSize)))
  828. }
  829. let date = Date()
  830. let calendar = Calendar.current
  831. if (calendar.isDateInToday(date)) {
  832. dayLastBackup = "Today".localized()
  833. } else {
  834. let startOfNow = calendar.startOfDay(for: Date())
  835. let startOfTimeStamp = calendar.startOfDay(for: date)
  836. let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
  837. let day = -(components.day!)
  838. if day == 1{
  839. dayLastBackup = "Yesterday".localized()
  840. } else {
  841. let formatter = DateFormatter()
  842. formatter.dateFormat = "dd MMMM yyyy"
  843. let lang: String = SecureUserDefaults.shared.value(forKey: "i18n_language") ?? "en"
  844. if lang == "id" {
  845. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  846. }
  847. let stringFormat = formatter.string(from: date as Date)
  848. dayLastBackup = stringFormat
  849. }
  850. }
  851. let formatter = DateFormatter()
  852. formatter.dateFormat = "HH:mm"
  853. formatter.locale = NSLocale(localeIdentifier: "id") as Locale?
  854. timeLastBackup = formatter.string(from: date as Date)
  855. valueLastBackup = dayLastBackup.localized() + ", " + timeLastBackup
  856. valuesizeBackup = Units(bytes: fileSize).getReadableUnit()
  857. labelPreparing.text = "Successfully Backup Data".localized()
  858. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { [self] in
  859. isBackupStart = false
  860. tableView.beginUpdates()
  861. tableView.reloadRows(at: [indexPath, IndexPath(row: 0, section: 0)], with: .none)
  862. tableView.reloadSections(IndexSet(integer: 2), with: .none)
  863. tableView.endUpdates()
  864. })
  865. } catch {}
  866. }
  867. }
  868. }
  869. })
  870. } catch {
  871. //print(error)
  872. }
  873. } catch {
  874. rollback.pointee = true
  875. print("Access database error: \(error.localizedDescription)")
  876. }
  877. })
  878. }
  879. }
  880. extension String {
  881. func appendLineToURL(fileURL: URL) throws {
  882. try (self + "\n").appendToURL(fileURL: fileURL)
  883. }
  884. func appendToURL(fileURL: URL) throws {
  885. let data = self.data(using: String.Encoding.utf8)!
  886. try data.append(fileURL: fileURL)
  887. }
  888. }
  889. extension Data {
  890. func append(fileURL: URL) throws {
  891. if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
  892. defer {
  893. fileHandle.closeFile()
  894. }
  895. fileHandle.seekToEndOfFile()
  896. fileHandle.write(self)
  897. }
  898. else {
  899. try write(to: fileURL, options: .atomic)
  900. }
  901. }
  902. }