From d95742dd9f80506a0d773cbba7bc6a4508de1964 Mon Sep 17 00:00:00 2001 From: Iván Ávalos Date: Thu, 31 Mar 2022 22:00:12 -0600 Subject: Added support for sharing and saving reports --- iosApp/iosApp.xcodeproj/project.pbxproj | 23 ++++++++- iosApp/iosApp/AppDelegate.swift | 2 + .../iosApp/Details/Reports/UnitReportsView.swift | 39 ++++++++++---- .../Details/Reports/UnitReportsViewModel.swift | 58 ++++++++++++++++++--- iosApp/iosApp/Shared/ShareViewController.swift | 26 ++++++++++ iosApp/iosApp/Shared/Utils.swift | 52 +++++++++++++++++++ iosApp/iosApp/Shared/XlsxFile.swift | 60 ++++++++++++++++++++++ .../trackermap/TrackerMap/utils/NSDataByteArray.kt | 40 +++++++++++++++ 8 files changed, 280 insertions(+), 20 deletions(-) create mode 100644 iosApp/iosApp/Shared/ShareViewController.swift create mode 100644 iosApp/iosApp/Shared/XlsxFile.swift create mode 100644 shared/src/iosMain/kotlin/mx/trackermap/TrackerMap/utils/NSDataByteArray.kt diff --git a/iosApp/iosApp.xcodeproj/project.pbxproj b/iosApp/iosApp.xcodeproj/project.pbxproj index dc4bdc2..6706004 100644 --- a/iosApp/iosApp.xcodeproj/project.pbxproj +++ b/iosApp/iosApp.xcodeproj/project.pbxproj @@ -46,6 +46,8 @@ E39ABC4327A4E88C00965D05 /* UnitsViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = E39ABC4227A4E88C00965D05 /* UnitsViewModel.swift */; }; E39ABC4627A4EBD500965D05 /* DevicesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E39ABC4527A4EBD500965D05 /* DevicesView.swift */; }; E39ABC4827A4EDEC00965D05 /* DeviceRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = E39ABC4727A4EDEC00965D05 /* DeviceRow.swift */; }; + E3B5740827F68F5F0018AFCF /* XlsxFile.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3B5740727F68F5F0018AFCF /* XlsxFile.swift */; }; + E3B5740A27F69F750018AFCF /* ShareViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3B5740927F69F750018AFCF /* ShareViewController.swift */; }; E3C651E727CB5426002F6F4C /* Tabler in Frameworks */ = {isa = PBXBuildFile; productRef = E3C651E627CB5426002F6F4C /* Tabler */; }; E3C651EA27CB61EE002F6F4C /* GEOSwift in Frameworks */ = {isa = PBXBuildFile; productRef = E3C651E927CB61EE002F6F4C /* GEOSwift */; }; E3E77EE6279E6CE400150070 /* FlowCollector.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3E77EE5279E6CE400150070 /* FlowCollector.swift */; }; @@ -63,6 +65,16 @@ name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; }; + E3B5741D27F6A3C70018AFCF /* Embed App Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + ); + name = "Embed App Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ @@ -106,6 +118,8 @@ E39ABC4227A4E88C00965D05 /* UnitsViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnitsViewModel.swift; sourceTree = ""; }; E39ABC4527A4EBD500965D05 /* DevicesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DevicesView.swift; sourceTree = ""; }; E39ABC4727A4EDEC00965D05 /* DeviceRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceRow.swift; sourceTree = ""; }; + E3B5740727F68F5F0018AFCF /* XlsxFile.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = XlsxFile.swift; sourceTree = ""; }; + E3B5740927F69F750018AFCF /* ShareViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareViewController.swift; sourceTree = ""; }; E3E77EE5279E6CE400150070 /* FlowCollector.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FlowCollector.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -271,6 +285,8 @@ E33A237227A7581A00DD647F /* Utils.swift */, E34A2F4727A7878200AD8AEB /* HyperlinkText.swift */, E31D721427CF159900CDA320 /* SidewaysScroller.swift */, + E3B5740727F68F5F0018AFCF /* XlsxFile.swift */, + E3B5740927F69F750018AFCF /* ShareViewController.swift */, ); path = Shared; sourceTree = ""; @@ -287,6 +303,7 @@ 7555FF78242A565900829871 /* Frameworks */, 7555FF79242A565900829871 /* Resources */, E33A236F27A7545500DD647F /* Embed Frameworks */, + E3B5741D27F6A3C70018AFCF /* Embed App Extensions */, ); buildRules = ( ); @@ -309,7 +326,7 @@ 7555FF73242A565900829871 /* Project object */ = { isa = PBXProject; attributes = { - LastSwiftUpdateCheck = 1130; + LastSwiftUpdateCheck = 1320; LastUpgradeCheck = 1130; ORGANIZATIONNAME = orgName; TargetAttributes = { @@ -396,6 +413,7 @@ E312E74F27B366060018C5DE /* DevicesViewModel.swift in Sources */, E33A236727A64E4500DD647F /* MarkerTransformations.swift in Sources */, E38F241527A242870069FC45 /* Inject.swift in Sources */, + E3B5740A27F69F750018AFCF /* ShareViewController.swift in Sources */, E39ABC4827A4EDEC00965D05 /* DeviceRow.swift in Sources */, E396282827AFBD72005D070E /* UnitCommandsView.swift in Sources */, E38F241C27A26DD70069FC45 /* RootViewModel.swift in Sources */, @@ -408,6 +426,7 @@ E39ABC4327A4E88C00965D05 /* UnitsViewModel.swift in Sources */, E360251B27BCA8A600958B21 /* AccountViewModel.swift in Sources */, E34A2F4827A7878200AD8AEB /* HyperlinkText.swift in Sources */, + E3B5740827F68F5F0018AFCF /* XlsxFile.swift in Sources */, 2152FB042600AC8F00CF470E /* iOSApp.swift in Sources */, E39ABC4627A4EBD500965D05 /* DevicesView.swift in Sources */, E3141B8B27B9E91F00CE777C /* UnitReportsViewModel.swift in Sources */, @@ -552,6 +571,7 @@ 7555FFA6242A565B00829871 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = iosApp/iosApp.entitlements; @@ -589,6 +609,7 @@ 7555FFA7242A565B00829871 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = iosApp/iosApp.entitlements; diff --git a/iosApp/iosApp/AppDelegate.swift b/iosApp/iosApp/AppDelegate.swift index 72e3e92..22d4f75 100644 --- a/iosApp/iosApp/AppDelegate.swift +++ b/iosApp/iosApp/AppDelegate.swift @@ -32,6 +32,8 @@ class AppDelegate: NSObject, UIApplicationDelegate { application.registerForRemoteNotifications() + Utils.createReportTmpDirectory() + Utils.clearReportTmpDirectory() return true } diff --git a/iosApp/iosApp/Details/Reports/UnitReportsView.swift b/iosApp/iosApp/Details/Reports/UnitReportsView.swift index 2143b3b..e189835 100644 --- a/iosApp/iosApp/Details/Reports/UnitReportsView.swift +++ b/iosApp/iosApp/Details/Reports/UnitReportsView.swift @@ -152,17 +152,34 @@ struct UnitReportsView: View { EmptyView() }.pickerStyle(SegmentedPickerStyle()) - //HStack { - // Group { - // Button {} label: { - // Text("report-save") - // } - // - // Button {} label: { - // Text("report-share") - // } - // }.frame(maxWidth: .infinity) - //}.padding() + HStack { + Group { + Button { + unitReportsViewModel.saveXlsxReport() + } label: { + Text("report-save") + } + + Button { + unitReportsViewModel.shareXlsxReport() + } label: { + Text("report-share") + } + }.frame(maxWidth: .infinity) + }.padding() + .sheet(isPresented: $unitReportsViewModel.showShareDialog) { + ShareView(activityItems: $unitReportsViewModel.activityItems) + } + .fileExporter(isPresented: $unitReportsViewModel.showExportDialog, + documents: [unitReportsViewModel.saveDocument], + contentType: .xlsx) { result in + switch result { + case .success (let url): + print ("Saved to \(url)") + case .failure (let error): + print (error.localizedDescription) + } + } }.padding() }.onAppear { unitReportsViewModel.fetchReport() diff --git a/iosApp/iosApp/Details/Reports/UnitReportsViewModel.swift b/iosApp/iosApp/Details/Reports/UnitReportsViewModel.swift index 4731a57..e5b3e4b 100644 --- a/iosApp/iosApp/Details/Reports/UnitReportsViewModel.swift +++ b/iosApp/iosApp/Details/Reports/UnitReportsViewModel.swift @@ -1,11 +1,20 @@ -// -// UnitReportsViewModel.swift -// iosApp -// -// Created by Iván on 13/02/22. -// Copyright © 2022 orgName. All rights reserved. -// - +/** + * TrackerMap + * Copyright (C) 2021-2022 Iván Ávalos , Henoch Ojeda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ import Foundation import Combine import shared @@ -14,6 +23,11 @@ class UnitReportsViewModel: ObservableObject { @Inject var reportController: ReportController @Inject var geofencesController: GeofencesController + enum XlsxAction { + case save + case share + } + @Published var deviceId: Int32? = nil @Published var reportType: ReportController.ReportType = .positions { didSet { @@ -34,6 +48,16 @@ class UnitReportsViewModel: ObservableObject { markers = [] case let report as ReportController.ReportStopsReport: markers = report.stops.compactMap { s in Marker.companion.fromStop(stop: s) } + case let report as ReportController.ReportXlsxReport: + print ("Got XLSX report!") + saveDocument = XlsxFile(bytes: report.data) + if xlsxAction == .save { + showExportDialog = true + } else { + let url = saveDocument.data.dataToFile(fileName: "report.xlsx") + activityItems = [url!] + showShareDialog = true + } default: break } @@ -43,6 +67,7 @@ class UnitReportsViewModel: ObservableObject { @Published var markers = [Marker]() @Published var selectedMarker: Marker? = nil + // Geofences @Published var geofences: [Int: Geofence] = [:] { didSet { flatGeofences = Array(geofences.values) @@ -50,6 +75,13 @@ class UnitReportsViewModel: ObservableObject { } @Published var flatGeofences: [Geofence] = [] + // Save and share + var xlsxAction: XlsxAction = .save + var saveDocument = XlsxFile() + @Published var showExportDialog: Bool = false + @Published var showShareDialog: Bool = false + @Published var activityItems: [Any] = [] + init(deviceId id: Int32?) { deviceId = id let collector = Collector(callback: setReport) @@ -91,4 +123,14 @@ class UnitReportsViewModel: ObservableObject { ]) { _, _ in } } } + + func saveXlsxReport () { + xlsxAction = .save + fetchReport(xlsx: true) + } + + func shareXlsxReport () { + xlsxAction = .share + fetchReport(xlsx: true) + } } diff --git a/iosApp/iosApp/Shared/ShareViewController.swift b/iosApp/iosApp/Shared/ShareViewController.swift new file mode 100644 index 0000000..ed26ab8 --- /dev/null +++ b/iosApp/iosApp/Shared/ShareViewController.swift @@ -0,0 +1,26 @@ +// +// ShareViewController.swift +// iosApp +// +// Created by Iván on 31/03/22. +// Copyright © 2022 orgName. All rights reserved. +// + +import Foundation +import SwiftUI +import UIKit + +struct ShareView: UIViewControllerRepresentable { + + @Binding var activityItems: [Any] + var excludedActivityTypes: [UIActivity.ActivityType]? = nil + + func makeUIViewController(context: UIViewControllerRepresentableContext) -> UIActivityViewController { + let controller = UIActivityViewController(activityItems: activityItems, + applicationActivities: nil) + controller.excludedActivityTypes = excludedActivityTypes + return controller + } + + func updateUIViewController(_ uiViewController: UIActivityViewController, context: UIViewControllerRepresentableContext) {} +} diff --git a/iosApp/iosApp/Shared/Utils.swift b/iosApp/iosApp/Shared/Utils.swift index 61a8f90..4e04d1b 100644 --- a/iosApp/iosApp/Shared/Utils.swift +++ b/iosApp/iosApp/Shared/Utils.swift @@ -20,6 +20,25 @@ import CryptoKit import WhirlyGlobe import shared +// Source: https://stackoverflow.com/a/55092044 +extension Data { + func dataToFile(fileName: String) -> NSURL? { + let fileManager = FileManager.default + let data = self + let filePath = Utils.getReportTmpDirectory().appendingPathComponent(fileName) + do { + if(fileManager.fileExists(atPath: filePath)) { + try fileManager.removeItem(atPath: filePath) + } + fileManager.createFile(atPath: filePath, contents: data, attributes: nil) + return NSURL(fileURLWithPath: filePath) + } catch { + print("Error writing the file: \(error.localizedDescription)") + } + return nil + } +} + class Utils { static func MD5(string: String) -> String { let digest = Insecure.MD5.hash(data: string.data(using: .utf8) ?? Data()) @@ -45,4 +64,37 @@ class Utils { .replacingOccurrences(of: "{x}", with: "\(latitude)") .replacingOccurrences(of: "{y}", with: "\(longitude)")) } + + static func createReportTmpDirectory() { + let fileManager = FileManager.default + let tmpDir = getReportTmpDirectory() as String + do { + if (!fileManager.fileExists(atPath: tmpDir)) { + try fileManager.createDirectory(atPath: tmpDir, + withIntermediateDirectories: false, + attributes: nil) + } + } catch { + print("Could not create temp folder: \(error)") + } + } + + static func getReportTmpDirectory() -> NSString { + let tmpDir = NSTemporaryDirectory() + return (tmpDir as NSString).appendingPathComponent("reports") as NSString + } + + // Source: https://stackoverflow.com/a/33937110 + static func clearReportTmpDirectory() { + let fileManager = FileManager.default + let reportTmpDir = getReportTmpDirectory() + do { + let filePaths = try fileManager.contentsOfDirectory(atPath: reportTmpDir as String) + for filePath in filePaths { + try fileManager.removeItem(atPath: reportTmpDir.appendingPathComponent(filePath)) + } + } catch { + print("Could not clear temp folder: \(error)") + } + } } diff --git a/iosApp/iosApp/Shared/XlsxFile.swift b/iosApp/iosApp/Shared/XlsxFile.swift new file mode 100644 index 0000000..8015422 --- /dev/null +++ b/iosApp/iosApp/Shared/XlsxFile.swift @@ -0,0 +1,60 @@ +/** + * TrackerMap + * Copyright (C) 2021-2022 Iván Ávalos , Henoch Ojeda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +import shared +import Foundation +import UniformTypeIdentifiers +import SwiftUI + +// Source: https://www.hackingwithswift.com/quick-start/swiftui/how-to-export-files-using-fileexporter + +extension UTType { + static var doc: Self { .init(filenameExtension: "doc")! } + static var docx: Self { .init(filenameExtension: "docx")! } + + static var xls: Self { .init(filenameExtension: "xls")! } + static var xlsx: Self { .init(filenameExtension: "xlsx")! } + + static var ppt: Self { .init(filenameExtension: "ppt")! } + static var pptx: Self { .init(filenameExtension: "pptx")! } +} + +struct XlsxFile: FileDocument { + static var readableContentTypes = [UTType.xlsx] + + var data: Data + + init() { + data = Data() + } + + init(bytes: KotlinByteArray) { + data = bytes.toData() + } + + init(configuration: ReadConfiguration) throws { + if let data = configuration.file.regularFileContents { + self.data = data + return + } + self.data = Data() + } + + func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { + return FileWrapper(regularFileWithContents: data) + } +} diff --git a/shared/src/iosMain/kotlin/mx/trackermap/TrackerMap/utils/NSDataByteArray.kt b/shared/src/iosMain/kotlin/mx/trackermap/TrackerMap/utils/NSDataByteArray.kt new file mode 100644 index 0000000..807c63f --- /dev/null +++ b/shared/src/iosMain/kotlin/mx/trackermap/TrackerMap/utils/NSDataByteArray.kt @@ -0,0 +1,40 @@ +/** + * TrackerMap + * Copyright (C) 2021-2022 Iván Ávalos , Henoch Ojeda + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package mx.trackermap.TrackerMap.utils + +import kotlinx.cinterop.addressOf +import kotlinx.cinterop.allocArrayOf +import kotlinx.cinterop.memScoped +import kotlinx.cinterop.usePinned +import platform.Foundation.NSData +import platform.Foundation.create +import platform.posix.memcpy + +// Source: https://gist.github.com/noahsark769/61cfb7a8b7231e2069a9dab94cf74a62 + +fun ByteArray.toData(): NSData = memScoped { + NSData.create( + bytes = allocArrayOf(this@toData), + length = this@toData.size.toULong()) +} + +fun NSData.toByteArray(): ByteArray = ByteArray(this@toByteArray.length.toInt()).apply { + usePinned { + memcpy(it.addressOf(0), this@toByteArray.bytes, this@toByteArray.length) + } +} \ No newline at end of file -- cgit v1.2.3