IEnumerator ShowLoadDialogCoroutine()
    {
        // Show a load file dialog and wait for a response from user
        // Load file/folder: both, Allow multiple selection: true
        // Initial path: default (Documents), Initial filename: empty
        // Title: "Load File", Submit button text: "Load"
        yield return(FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.FilesAndFolders, true, null, null, "Load Files and Folders", "Load"));

        // Dialog is closed
        // Print whether the user has selected some files/folders or cancelled the operation (FileBrowser.Success)
        Debug.Log(FileBrowser.Success);

        if (FileBrowser.Success)
        {
            // Print paths of the selected files (FileBrowser.Result) (null, if FileBrowser.Success is false)
            for (int i = 0; i < FileBrowser.Result.Length; i++)
            {
                Debug.Log(FileBrowser.Result[i]);
            }

            // Read the bytes of the first file via FileBrowserHelpers
            // Contrary to File.ReadAllBytes, this function works on Android 10+, as well
            byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result[0]);

            // Or, copy the first file to persistentDataPath
            string destinationPath = Path.Combine(Application.persistentDataPath, FileBrowserHelpers.GetFilename(FileBrowser.Result[0]));
            FileBrowserHelpers.CopyFile(FileBrowser.Result[0], destinationPath);
            previewImage.sprite = LoadSprite(destinationPath);
        }
    }
Esempio n. 2
0
    IEnumerator ShowLoadDialogCoroutine()
    {
        // Show a load file dialog and wait for a response from user
        // Load file/folder: file, Initial path: default (Documents), Title: "Load File", submit button text: "Load"
        yield return(FileBrowser.WaitForLoadDialog(false, @"Assets\Resources\Animations\", "Load Animation", "Load"));

        // Dialog is closed
        // Print whether a file is chosen (FileBrowser.Success)
        // and the path to the selected file (FileBrowser.Result) (null, if FileBrowser.Success is false)
        Debug.Log(FileBrowser.Success + " " + FileBrowser.Result);

        if (FileBrowser.Success)
        {
            // If a file was chosen, read its bytes via FileBrowserHelpers
            // Contrary to File.ReadAllBytes, this function works on Android 10+, as well
            //byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result)
            string code       = FileBrowserHelpers.ReadTextFromFile(FileBrowser.Result);
            Anim   loadedAnim = new Anim(FileBrowserHelpers.GetFilename(FileBrowser.Result).Replace(".txt", ""), code);
            //loadedAnim.Code = GetCleanCode(loadedAnim.Code);
            AnimationData.Instance.AddAnim(loadedAnim);
            AnimationData.Instance.selectedAnim = loadedAnim;
            MenuManager.Instance.UpdateAnimations();
            MenuManager.Instance.SetSelectedAnimation(loadedAnim.AnimationName);
        }
    }
Esempio n. 3
0
    /// <summary>
    /// Displays File Browser to select a file Location to save the exported glTF file
    /// </summary>
    /// <returns>IEnumerator Object</returns>
    public IEnumerator DisplaySaveCoroutine()
    {
        FileBrowser.SingleClickMode = true;

        yield return(FileBrowser.WaitForSaveDialog(FileBrowser.PickMode.FilesAndFolders, false, null, null, "Select Folder", "Save"));

        if (FileBrowser.Success)
        {
            string returnedPath = FileBrowser.Result[0];
            Debug.Log("Export Path : " + returnedPath);

            var exporter = new GLTFSceneExporter(new[] { _viewerObject.transform }, RetrieveTexturePath);
            if (FileBrowserHelpers.DirectoryExists(returnedPath))
            {
                string folderName      = _loadFileName ?? "ExportedObject";
                string finalExportPath = FileBrowserHelpers.CreateFolderInDirectory(returnedPath, folderName);
                Debug.Log("Final Export Path for empty filename : " + finalExportPath);
                exporter.SaveGLTFandBin(finalExportPath, folderName);
            }
            else
            {
                string saveFileName    = FileBrowserHelpers.GetFilename(returnedPath);
                string folderPath      = returnedPath.Substring(0, returnedPath.LastIndexOf(saveFileName));
                string finalExportPath = FileBrowserHelpers.CreateFolderInDirectory(folderPath, saveFileName);
                Debug.Log("Final Export Path with given filename : " + finalExportPath);
                exporter.SaveGLTFandBin(finalExportPath, saveFileName);
            }
        }
    }
Esempio n. 4
0
        private async void ReadFB2File(string path)
        {
            string fileName = FileBrowserHelpers.GetFilename(path);
            string text     = FileBrowserHelpers.ReadTextFromFile(path);

            FB2File file  = await new FB2Reader().ReadAsync(text);
            var     lines = await _fB2SampleConverter.ConvertAsync(file);

            string finalText = _fB2SampleConverter.GetLinesAsText();

            byte[] imageData = _fB2SampleConverter.GetCoverImageData();

            string imagePath = Application.persistentDataPath + _targetFolder + fileName + ".jpg";;

            try
            {
                File.WriteAllBytes(imagePath, imageData);

                Debug.Log("Image is saved. Path: " + imagePath);
            }
            catch
            {
                Debug.LogError("Loading image is error!");
            }

            imagePath = imagePath.Replace("/", "\\");

            string filePath = (Application.persistentDataPath + _targetFolder + fileName).Replace("/", "\\");

            FileData newBook = new FileData(fileName, filePath, imagePath, FileData.FileType.Book);

            SaveFile(newBook, finalText);
        }
Esempio n. 5
0
    /// <summary>
    /// Uploads the files present in the folder selected by the user
    /// </summary>
    /// <param name="folderPath">Path of folder</param>
    /// <returns></returns>
    IEnumerator UploadFolderToAmazonS3(string folderPath)
    {
        bool          errorOccured   = false;
        string        errorMsg       = null;
        string        rootName       = FileBrowserHelpers.GetFilename(folderPath);
        List <string> uploadFileList = GetUploadFileList(folderPath, out long uploadSize);

        if (uploadSize > MaxUploadFileSize)
        {
            DisplayUploadErrorMessage("File size is too large. It must be less than 50MB.");
            yield break;
        }
        if (uploadFileList.Count > 1)
        {
            int           numberOfFiles = uploadFileList.Count;
            float         index         = 0;
            float         uploadPercentage;
            string        key, progress;
            MessageFields uploadMsgFields = DisplayUploadProgressMessage();
            foreach (string file in uploadFileList)
            {
                uploadPercentage = (index / numberOfFiles) * 100;
                progress         = "Progress : " + Mathf.Round(uploadPercentage).ToString() + "%";
                uploadMsgFields.MessageDetails("Upload Progress ...", progress);
                key = file.Substring(file.LastIndexOf(rootName));
                key = key.Replace("\\", "/");
                yield return(GetPreSignedRequest(key, file, false, (e, m) => { errorOccured = e; errorMsg = m; }));

                if (errorOccured)
                {
                    break;
                }
                index++;
            }

            DestroyUploadProgressMessage(uploadMsgFields);

            if (errorOccured)
            {
                DisplayUploadErrorMessage(errorMsg);
                yield break;
            }
            if (gltfUrl != null)
            {
                yield return(PushUrlToDatabase(gltfUrl));
            }
        }
        else if (uploadFileList.Count == 1)
        {
            string filePath = uploadFileList[0];
            string key      = filePath.Substring(filePath.LastIndexOf(rootName));
            key = key.Replace("\\", "/");
            yield return(GetPreSignedRequest(key, filePath, true, (e, m) => { }));
        }
        else
        {
            DisplayUploadErrorMessage("Folder is Empty.");
        }
    }
    // Warning: paths returned by FileBrowser dialogs do not contain a trailing '\' character
    // Warning: FileBrowser can only show 1 dialog at a time

    public void OpenDialog()
    {
        // Set filters (optional)
        // It is sufficient to set the filters just once (instead of each time before showing the file browser dialog),
        // if all the dialogs will be using the same filters
        FileBrowser.SetFilters(true, new FileBrowser.Filter("RFP File", ".rfp"));

        // Set default filter that is selected when the dialog is shown (optional)
        // Returns true if the default filter is set successfully
        // In this case, set Images filter as the default filter
        FileBrowser.SetDefaultFilter(".rfp");

        // Set excluded file extensions (optional) (by default, .lnk and .tmp extensions are excluded)
        // Note that when you use this function, .lnk and .tmp extensions will no longer be
        // excluded unless you explicitly add them as parameters to the function
        FileBrowser.SetExcludedExtensions(".lnk", ".tmp", ".zip", ".rar", ".exe");

        // Add a new quick link to the browser (optional) (returns true if quick link is added successfully)
        // It is sufficient to add a quick link just once
        // Name: Users
        // Path: C:\Users
        // Icon: default (folder icon)
        FileBrowser.AddQuickLink("Users", "C:\\Users", null);

        // Show a save file dialog
        // onSuccess event: not registered (which means this dialog is pretty useless)
        // onCancel event: not registered
        // Save file/folder: file, Allow multiple selection: false
        // Initial path: "C:\", Initial filename: "Screenshot.png"
        // Title: "Save As", Submit button text: "Save"
        // FileBrowser.ShowSaveDialog( null, null, FileBrowser.PickMode.Files, false, "C:\\", "Screenshot.png", "Save As", "Save" );

        // Show a select folder dialog
        // onSuccess event: print the selected folder's path
        // onCancel event: print "Canceled"
        // Load file/folder: folder, Allow multiple selection: false
        // Initial path: default (Documents), Initial filename: empty
        // Title: "Select Folder", Submit button text: "Select"
        string initialPath = null;
        string initialFile = null;

        if (FileBrowserHelpers.FileExists(fileInput.text))
        {
            initialPath = FileBrowserHelpers.GetDirectoryName(fileInput.text);
            initialFile = FileBrowserHelpers.GetFilename(fileInput.text);
        }
        if (FileBrowserHelpers.DirectoryExists(fileInput.text))
        {
            initialPath = fileInput.text;
        }
        FileBrowser.ShowLoadDialog((paths) => { Debug.Log("Selected: " + paths[0]); fileInput.text = paths[0]; },
                                   () => { Debug.Log("Canceled file open"); },
                                   FileBrowser.PickMode.Files, false, initialPath, initialFile);

        // Coroutine example
        //StartCoroutine(ShowLoadDialogCoroutine());
    }
Esempio n. 7
0
    IEnumerator ShowLoadFieldDialogCoroutine()
    {
        yield return(FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.FilesAndFolders, false, Application.dataPath + "/CustomFields/", null, "Load field", "Load"));

        if (FileBrowser.Success)
        {
            string destinationPath = FileBrowser.Result[0];
            fileImage = FileBrowserHelpers.GetFilename(FileBrowser.Result[0]);
            LoadFieldToPath(destinationPath);
        }
    }
Esempio n. 8
0
    public void ImportClicked()
    {
        SimpleFileBrowser.FileBrowser.SetFilters(false, new SimpleFileBrowser.FileBrowser.Filter(
                                                     "Databases", ".DB", ".DBS", ".SQL", ".SQLITE3", ".SQLITE3", ".FILE"));

        SimpleFileBrowser.FileBrowser.ShowLoadDialog((paths) =>
        {
            string destinationPath = Path.Combine(Application.persistentDataPath, FileBrowserHelpers.GetFilename(FileBrowser.Result[0]));
            FileBrowserHelpers.CopyFile(FileBrowser.Result[0], destinationPath);
        }, null, SimpleFileBrowser.FileBrowser.PickMode.Files);
    }
Esempio n. 9
0
 /// <summary>
 /// Uploads the File/Folder to AmazonS3
 /// Determines if the user selected path is a file or Folder and calls appropriate Coroutines
 /// </summary>
 /// <param name="dataPath">User Selected path for upload</param>
 public void UploadToAmazonS3(string dataPath)
 {
     if (FileBrowserHelpers.DirectoryExists(dataPath))
     {
         StartCoroutine(UploadFolderToAmazonS3(dataPath));
     }
     else
     {
         string key = FileBrowserHelpers.GetFilename(dataPath);
         StartCoroutine(GetPreSignedRequest(key, dataPath, true, (e, m) => { }));
     }
 }
Esempio n. 10
0
    IEnumerator SaveJsonCoroutine(string data)
    {
        FileBrowser.Filter[] filters = new FileBrowser.Filter[1];
        filters[0] = new FileBrowser.Filter("JSON files", ".json");
        FileBrowser.SetFilters(true, filters);
        FileBrowser.SetDefaultFilter(".json");
        yield return(FileBrowser.WaitForSaveDialog(false, @"Assets\Resources\", "Uloz ulohu", "Uloz"));

        if (FileBrowser.Success)
        {
            string path     = FileBrowser.Result;
            string fileName = FileBrowserHelpers.GetFilename(FileBrowser.Result);
            File.WriteAllText(path, data);
        }
    }
Esempio n. 11
0
    IEnumerator ShowLoadDialogCoroutine()
    {
        // Show a load file dialog and wait for a response from user
        // Load file/folder: file, Initial path: default (Documents), Title: "Load File", submit button text: "Load"
        yield return(FileBrowser.WaitForLoadDialog(false, @"Assets\", "Load Object", "Load"));

        // Dialog is closed
        // Print whether a file is chosen (FileBrowser.Success)
        // and the path to the selected file (FileBrowser.Result) (null, if FileBrowser.Success is false)
        Debug.Log(FileBrowser.Success + " " + FileBrowser.Result);

        if (FileBrowser.Success)
        {
            IndexedFace.Instance.UpdateModel(FileBrowser.Result, FileBrowserHelpers.GetFilename(FileBrowser.Result).Replace(".obj", ""));
        }
    }
Esempio n. 12
0
    IEnumerator SaveAnimationCoroutine(Anim newAnim)
    {
        yield return(FileBrowser.WaitForSaveDialog(false, @"Assets\Resources\Animations\", "Save Animation", "Save"));

        if (FileBrowser.Success)
        {
            string path     = FileBrowser.Result;
            string fileName = FileBrowserHelpers.GetFilename(FileBrowser.Result);
            newAnim.AnimationName = fileName.Replace(".txt", "");
            //FileBrowserHelpers.CreateFileInDirectory(@"Assets\Resources\Animations\",fileName);
            HandleTextFile.WriteString(path, newAnim.Code /*GetCleanCode(newAnim.Code)*/);
            AnimationData.Instance.AddAnim(newAnim);
            AnimationData.Instance.selectedAnim = newAnim;
            MenuManager.Instance.UpdateAnimations();
            MenuManager.Instance.SetSelectedAnimation(newAnim.AnimationName);
        }
    }
Esempio n. 13
0
    /// <summary>
    /// Uploads a single file to the server. Not used in case of upload to AmazonS3
    /// Note - As the backend server supports only upload to AmazonS3 this is never called
    /// </summary>
    /// <param name="uploadFilePath">Path of file to be uploaded</param>
    /// <param name="deleteTempFile">Path of temporary Zip file</param>
    /// <returns></returns>
    private IEnumerator UploadFileToServer(string uploadFilePath, bool deleteTempFile)
    {
        List <IMultipartFormSection> formData = new List <IMultipartFormSection>();
        string fileName = FileBrowserHelpers.GetFilename(uploadFilePath);

        byte[] fileData = FileBrowserHelpers.ReadBytesFromFile(uploadFilePath);
        formData.Add(new MultipartFormFileSection("Object", fileData, fileName, "application/octet-stream"));

        using (UnityWebRequest uwr = UnityWebRequest.Post(amazonS3ServerBackend + "/fileupload", formData))
        {
            uwr.SendWebRequest();

            MessageFields uploadMsgFields = DisplayUploadProgressMessage();
            StartCoroutine(CheckUploadConnection(uwr));
            while (!uwr.isDone)
            {
                string progress = "Progress : " + Mathf.Round(uwr.uploadProgress * 100).ToString() + "%";
                uploadMsgFields.MessageDetails("Upload Progress ...", progress);
                if (uwr.isNetworkError || uwr.isHttpError)
                {
                    yield break;
                }
                yield return(null);
            }

            if (uwr.result != UnityWebRequest.Result.Success)
            {
                DestroyUploadProgressMessage(uploadMsgFields);
                if (deleteTempFile && FileBrowserHelpers.FileExists(uploadFilePath))
                {
                    FileBrowserHelpers.DeleteFile(uploadFilePath);
                    Debug.Log("Temp File deleted after Error");
                }
                DisplayUploadErrorMessage(uwr.error);
            }
            else
            {
                DestroyUploadProgressMessage(uploadMsgFields);
                if (deleteTempFile && FileBrowserHelpers.FileExists(uploadFilePath))
                {
                    FileBrowserHelpers.DeleteFile(uploadFilePath);
                    Debug.Log("Temp File deleted");
                }
            }
        }
    }
Esempio n. 14
0
    IEnumerator ShowLoadDialogCoroutine(string path, string tooltip, string type)
    {
        // Show a load file dialog and wait for a response from user
        // Load file/folder: file, Initial path: default (Documents), Title: "Load File", submit button text: "Load"
        if (type.Equals("Diagram"))
        {
            FileBrowser.SetDefaultFilter(".xml");
        }
        else
        {
            FileBrowser.SetDefaultFilter(".json");
        }
        yield return(FileBrowser.WaitForLoadDialog(false, path, tooltip, "Load"));

        // Dialog is closed
        // Print whether a file is chosen (FileBrowser.Success)
        // and the path to the selected file (FileBrowser.Result) (null, if FileBrowser.Success is false)
        Debug.Log(FileBrowser.Success + " " + FileBrowser.Result);

        if (FileBrowser.Success)
        {
            // If a file was chosen, read its bytes via FileBrowserHelpers
            // Contrary to File.ReadAllBytes, this function works on Android 10+, as well
            //byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result)
            if (type.Equals("Animation"))
            {
                //string code = FileBrowserHelpers.ReadTextFromFile(FileBrowser.Result);
                Anim loadedAnim = new Anim(FileBrowserHelpers.GetFilename(FileBrowser.Result).Replace(".json", ""), "");
                loadedAnim.LoadCode(FileBrowser.Result);
                //loadedAnim.Code = GetCleanCode(loadedAnim.Code);
                AnimationData.Instance.AddAnim(loadedAnim);
                AnimationData.Instance.selectedAnim = loadedAnim;
                MenuManager.Instance.UpdateAnimations();
                MenuManager.Instance.SetSelectedAnimation(loadedAnim.AnimationName);
            }
            else if (type.Equals("Diagram"))
            {
                string fileName = FileBrowserHelpers.GetFilename(FileBrowser.Result);
                Debug.Log(FileBrowser.Result);
                Debug.Log(fileName);
                AnimationData.Instance.SetDiagramPath(FileBrowser.Result);
                ClassDiagram.Instance.LoadDiagram();
            }
        }
    }
Esempio n. 15
0
        private IEnumerator ShowLoadDialogCoroutine()
        {
            // Show a load file dialog and wait for a response from user
            // Load file/folder: file, Initial path: default (Documents), Title: "Load File", submit button text: "Load"
            yield return(FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.Files, false, null, "Load Book", "Load"));

            if (FileBrowser.Success)
            {
                foreach (string path in FileBrowser.Result)
                {
                    string fileName   = FileBrowserHelpers.GetFilename(path);
                    string targetPath = Application.persistentDataPath + _sourceFolder + fileName;
                    FileBrowserHelpers.MoveFile(path, targetPath);

                    ImportFiles();
                }
            }

            onFB2Loaded?.Invoke();
        }
Esempio n. 16
0
    IEnumerator MobileFileBrowserLoadCoroutinePalette(PEERbotPalette palette)
    {
        SimpleFileBrowser.FileBrowser.SetDefaultFilter(".csv");
        yield return(SimpleFileBrowser.FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.Files, false, getPalettePathFolder(), null, "Load CSV Palette File", "Load"));

        androidSaveLoadBackground.SetActive(false);
        if (FileBrowser.Success)  //Try to load if successful
        //Because F%^$ing Android refuses to keep file IO simple, with their F!@# stupid SAF system
        {
            string filepath = FileBrowserHelpers.GetDirectoryName(FileBrowser.Result[0]);
            string filename = FileBrowserHelpers.GetFilename(FileBrowser.Result[0]);
            string realpath = Path.Combine(filepath, filename);
            Debug.Log("Realpath: " + realpath);
            LoadCSVPalette(palette, realpath);
        }
        else
        {
            pc.deletePalette(palette);
        }
    }
Esempio n. 17
0
    /// <summary>
    /// Tells whether the user selected folder/file is valid i.e contains supported file format and checks file size.
    /// </summary>
    /// <param name="selectedPath">Path of file/folder user wants to upload</param>
    /// <param name="errorMessage">If any error pass error message</param>
    /// <returns>True if file/folder is valid else False</returns>
    public bool IsValidUpload(string selectedPath, out string errorMessage)
    {
        if (FileBrowserHelpers.DirectoryExists(selectedPath))
        {
            FileSystemEntry[] allFiles = FileBrowserHelpers.GetEntriesInDirectory(selectedPath);
            foreach (FileSystemEntry entry in allFiles)
            {
                if (!entry.IsDirectory)
                {
                    string uploadFileExtension = entry.Extension.ToLower();
                    if (uploadFileExtension == TypeGLTF || uploadFileExtension == TypeGLB)
                    {
                        errorMessage = null;
                        return(true);
                    }
                }
            }
            errorMessage = "glTF/glb type file not found in selected folder.";
            return(false);
        }
        else
        {
            string uploadFileName = FileBrowserHelpers.GetFilename(selectedPath).ToLower();
            if (uploadFileName.EndsWith(TypeGLTF) || uploadFileName.EndsWith(TypeGLB))
            {
                if (FileBrowserHelpers.GetFilesize(selectedPath) < MaxUploadFileSize)
                {
                    errorMessage = null;
                    return(true);
                }
                else
                {
                    errorMessage = "File size is too large. It must be less than 50MB.";
                    return(false);
                }
            }

            errorMessage = "File selected is not glTF or glb.";
            return(false);
        }
    }
Esempio n. 18
0
    IEnumerator ShowLoadDialogCoroutine()
    {
        yield return(FileBrowser.WaitForLoadDialog(false, null, "Load MP3", "Select"));

        path = FileBrowser.Result;

        if (FileBrowser.Success)
        {
            byte[] audioFile = FileBrowserHelpers.ReadBytesFromFile(path);
            musicFileName    = FileBrowserHelpers.GetFilename(path);
            audioSource.clip = NAudioPlayer.FromMp3Data(audioFile);
            fullLength       = (int)audioSource.clip.length;

            canJump          = true;
            audioSource.time = 0;
            AudioProfile(audioProfileVal);
        }

        varUI.GetComponent <UIControl>().enabled           = true;
        varMainCam.GetComponent <ExtendedFlycam>().enabled = true;
    }
Esempio n. 19
0
    /// <summary>
    /// Determines the type of file selected by user and imports the selected object
    /// </summary>
    /// <param name="sourcePath">Path of object file to be imported</param>
    void LoadObjfromFile(string sourcePath)
    {
        bool   isInvalidFileType = false;
        string fileName          = FileBrowserHelpers.GetFilename(sourcePath).ToLower();

        if (fileName.EndsWith(TypeOBJ))
        {
            _viewerObject = new OBJLoader().Load(sourcePath);
            _loadFileName = fileName.Substring(0, fileName.LastIndexOf(TypeOBJ));
        }
        else if (fileName.EndsWith(TypeGLTF))
        {
            gltfImporter.GLTFUri = sourcePath;
            GLTFLoaderTask();
            _loadFileName = fileName.Substring(0, fileName.LastIndexOf(TypeGLTF));
        }
        else if (fileName.EndsWith(TypeGLB))
        {
            gltfImporter.GLTFUri = sourcePath;
            GLTFLoaderTask();
            _loadFileName = fileName.Substring(0, fileName.LastIndexOf(TypeGLB));
        }
        else
        {
            isInvalidFileType = true;
            DestroyLoadingMessage();
            DisplayFileErrorMessage();
        }

        if (!isInvalidFileType)
        {
            StartCoroutine(LoadedObjectToViewer());
        }
        //if (_viewerObject != null)
        //{
        //    _viewerObject.SetActive(false);
        //    Debug.Log("object loaded successfully");
        //    StartCoroutine(LoadedObjectToViewer());
        //}
    }
Esempio n. 20
0
    static public IEnumerator ResourceFromArchive()
    {
        FileBrowser.SetFilters(true, new FileBrowser.Filter("ZipArchive", ".zip"));
        FileBrowser.SetDefaultFilter(".zip");
        FileBrowser.SetExcludedExtensions(".exe", ".lnk", ".tmp");

        yield return(FileBrowser.WaitForLoadDialog(false, null, "Load File", "Load"));

        Debug.Log(FileBrowser.Success + " " + FileBrowser.Result);

        if (FileBrowser.Success)
        {
            byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result);
            try
            {
                MemoryStream ms = new MemoryStream(bytes);

                using (ZipArchive zip = new ZipArchive(ms))
                {
                    if (FileBrowserHelpers.GetFilename(FileBrowser.Result) != nameArchive)
                    {
                        ResourceAllocation(zip.GetEntry("DataFile.xml"));
                        nameArchive = FileBrowserHelpers.GetFilename(FileBrowser.Result);
                    }
                    foreach (ZipArchiveEntry entry in zip.Entries)
                    {
                        if (entry.FullName != "DataFile.xml")
                        {
                            ResourceAllocation(entry);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Error: " + e.Message);
                nameArchive = null;
            }
        }
    }
Esempio n. 21
0
    IEnumerator ShowLoadDialogCoroutine(string path, string tooltip, string type)
    {
        // Show a load file dialog and wait for a response from user
        // Load file/folder: file, Initial path: default (Documents), Title: "Load File", submit button text: "Load"
        FileBrowser.Filter[] filters = new FileBrowser.Filter[1];
        filters[0] = new FileBrowser.Filter("JSON files", ".json");
        FileBrowser.SetFilters(true, filters);
        FileBrowser.SetDefaultFilter(".json");
        yield return(FileBrowser.WaitForLoadDialog(false, path, tooltip, "Otvor"));

        // Dialog is closed
        // Print whether a file is chosen (FileBrowser.Success)
        // and the path to the selected file (FileBrowser.Result) (null, if FileBrowser.Success is false)
        Debug.Log(FileBrowser.Success + " " + FileBrowser.Result);

        if (FileBrowser.Success)
        {
            // If a file was chosen, read its bytes via FileBrowserHelpers
            // Contrary to File.ReadAllBytes, this function works on Android 10+, as well
            //byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result)
            string fileName = FileBrowserHelpers.GetFilename(FileBrowser.Result);
            ImageSerializer.Instance.LoadData(FileBrowser.Result);
        }
    }
Esempio n. 22
0
        private async void ImportFiles()
        {
            string path = Application.persistentDataPath + _sourceFolder;

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch (IOException ex)
            {
                Debug.Log(ex.Message);
                return;
            }

            var files = FileBrowserHelpers.GetEntriesInDirectory(path);

            foreach (var file in files)
            {
                string fileName  = string.Empty;
                string filePath  = string.Empty;
                string imagePath = string.Empty;

                string   text      = string.Empty;
                string   finalText = string.Empty;
                byte[]   imageData = null;
                FileData newBook   = null;

                if (!file.IsDirectory)
                {
                    switch (file.Extension)
                    {
                    case ".fb2":
                        fileName = FileBrowserHelpers.GetFilename(file.Path);
                        text     = FileBrowserHelpers.ReadTextFromFile(file.Path);

                        FB2File fb2File = await new FB2Reader().ReadAsync(text);
                        var     lines   = await _fB2SampleConverter.ConvertAsync(fb2File);

                        finalText = _fB2SampleConverter.GetLinesAsText();

                        imageData = _fB2SampleConverter.GetCoverImageData();

                        if (imageData != null)
                        {
                            imagePath = Application.persistentDataPath + _targetFolder + fileName + ".jpg";;

                            try
                            {
                                File.WriteAllBytes(imagePath, imageData);

                                Debug.Log("Image is saved. Path: " + imagePath);
                            }
                            catch
                            {
                                Debug.LogError("Loading image is error!");
                            }

                            imagePath = imagePath.Replace("/", "\\");
                        }

                        filePath = (Application.persistentDataPath + _targetFolder + fileName).Replace("/", "\\");

                        newBook = new FileData(fileName, filePath, imagePath, FileData.FileType.Book);

                        SaveFile(newBook, finalText);

                        FileBrowserHelpers.DeleteFile(file.Path);
                        break;

                    case ".epub":
                        EpubBook epubFile = EpubReader.ReadBook(file.Path);

                        fileName = epubFile.Title + " (" + epubFile.Author + ")";

                        foreach (EpubTextContentFile textContentFile in epubFile.ReadingOrder)
                        {
                            HtmlDocument htmlDocument = new HtmlDocument();
                            htmlDocument.LoadHtml(textContentFile.Content);

                            StringBuilder sb = new StringBuilder();
                            foreach (HtmlNode node in htmlDocument.DocumentNode.SelectNodes("//text()"))
                            {
                                sb.AppendLine(node.InnerText.Replace("\n", "").Replace("\r", ""));
                            }

                            finalText += sb.ToString();
                        }

                        imageData = epubFile.CoverImage;

                        var imageName = string.Empty;

                        if (imageData == null)
                        {
                            imageData = epubFile.Content.Images.FirstOrDefault().Value.Content;
                            imageName = epubFile.Content.Images.FirstOrDefault().Key;
                        }
                        else
                        {
                            imageName = epubFile.Content.Cover.FileName;
                        }

                        if (imageData != null)
                        {
                            imagePath = Application.persistentDataPath + _targetFolder + imageName;

                            try
                            {
                                File.WriteAllBytes(imagePath, imageData);

                                Debug.Log("Image is saved. Path: " + imagePath);
                            }
                            catch
                            {
                                Debug.LogError("Loading image is error!");
                            }

                            imagePath = imagePath.Replace("/", "\\");
                        }

                        filePath = (Application.persistentDataPath + _targetFolder + fileName).Replace("/", "\\");

                        newBook = new FileData(fileName, filePath, imagePath, FileData.FileType.Book);

                        SaveFile(newBook, finalText);

                        FileBrowserHelpers.DeleteFile(file.Path);
                        break;

                    case ".pdf":
                        var document = PdfiumViewer.PdfDocument.Load(file.Path);
                        var title    = document.GetInformation().Title;

                        if (FilesData.Files.Any(x => x.Name == title))
                        {
                            return;
                        }

                        fileName = FileBrowserHelpers.GetFilename(file.Path);
                        filePath = Application.persistentDataPath + _targetFolder + fileName;

                        imagePath = Application.persistentDataPath + _targetFolder + fileName.Remove(fileName.Length - 4) + ".png";

                        var image = document.Render(0, 72, 72, false);
                        image.Save(imagePath, System.Drawing.Imaging.ImageFormat.Png);

                        imagePath = imagePath.Replace("/", "\\");
                        filePath  = filePath.Replace("/", "\\");

                        document.Dispose();

                        FileBrowserHelpers.MoveFile(file.Path, filePath);

                        newBook = new FileData(title, filePath, imagePath, FileData.FileType.PdfFile);

                        SaveFile(newBook);

                        break;
                    }
                }
                else
                {
                    FileBrowserHelpers.DeleteDirectory(file.Path);
                }
            }
        }
Esempio n. 23
0
        IEnumerator ShowLoadDialogCoroutine()
        {
            // Show a load file dialog and wait for a response from user
            // Load file/folder: both, Allow multiple selection: true
            // Initial path: default (Documents), Initial filename: empty
            // Title: "Load File", Submit button text: "Load"
            yield return(FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.FilesAndFolders, true, null, null, "Load Files and Folders", "Load"));

            if (FileBrowser.Success)
            {
                // Print paths of the selected files (FileBrowser.Result) (null, if FileBrowser.Success is false)
                for (int i = 0; i < FileBrowser.Result.Length; i++)
                {
                    _imageSavePath = _songSavePath = FileBrowser.Result[0];
                }

                // Read the bytes of the first file via FileBrowserHelpers
                // Contrary to File.ReadAllBytes, this function works on Android 10+, as well
                byte[] bytes = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result[0]);

                // Or, copy the first file to persistentDataPath
                string destinationPath = Path.Combine(Application.persistentDataPath, FileBrowserHelpers.GetFilename(FileBrowser.Result[0]));
                FileBrowserHelpers.CopyFile(FileBrowser.Result[0], destinationPath);

                if (_imageSavePath.ToLower().EndsWith(".png") && _imageSavePath.Length > 1 || _imageSavePath.ToLower().EndsWith(".jpg") && _imageSavePath.Length > 1)
                {
                    string[] world = (Application.platform == RuntimePlatform.Android) ? _imageSavePath.Split('/'): _imageSavePath.Split('\\');
                    _imageName = world[world.Length - 1];
                    GetImage();
                }
                if (_songSavePath.ToLower().EndsWith(".mp3") && _songSavePath.Length > 1)
                {
                    string[] world = (Application.platform == RuntimePlatform.Android) ? _imageSavePath.Split('/') : _imageSavePath.Split('\\');
                    _songName = world[world.Length - 1];
                    GetSong();
                }
            }
        }
Esempio n. 24
0
    /// <summary>
    /// Actually uploads the file to AmazonS3 after getting a presigned request for that file
    /// </summary>
    /// <param name="resp">Response of Presigned Request</param>
    /// <param name="filePath">Path of the file to be uploaded</param>
    /// <param name="isSingleFile">False if it is a part of Folder upload, true otherwise</param>
    /// <param name="ErrorCallback">Used only during Folder upload, callback if any error occurs</param>
    /// <returns></returns>
    IEnumerator UploadFileToAmazonS3(PresignResponse resp, string filePath, bool isSingleFile, Action <bool, string> ErrorCallback)
    {
        List <IMultipartFormSection> formData = new List <IMultipartFormSection>();

        byte[] fileData = FileBrowserHelpers.ReadBytesFromFile(filePath);
        string filename = FileBrowserHelpers.GetFilename(filePath);

        formData.Add(new MultipartFormDataSection(nameof(resp.fields.acl), resp.fields.acl));
        formData.Add(new MultipartFormDataSection(nameof(resp.fields.key), resp.fields.key));
        formData.Add(new MultipartFormDataSection("x-amz-algorithm", resp.fields.xamzalgorithm));
        formData.Add(new MultipartFormDataSection("x-amz-credential", resp.fields.xamzcredential));
        formData.Add(new MultipartFormDataSection("x-amz-date", resp.fields.xamzdate));
        formData.Add(new MultipartFormDataSection(nameof(resp.fields.policy), resp.fields.policy));
        formData.Add(new MultipartFormDataSection("x-amz-signature", resp.fields.xamzsignature));
        formData.Add(new MultipartFormFileSection("file", fileData, filename, "application/octet-stream"));
        using (UnityWebRequest uwr = UnityWebRequest.Post(resp.url, formData))
        {
            if (isSingleFile)
            {
                uwr.SendWebRequest();

                MessageFields uploadMsgFields = DisplayUploadProgressMessage();
                StartCoroutine(CheckUploadConnection(uwr));
                while (!uwr.isDone)
                {
                    string progress = "Progress : " + Mathf.Round(uwr.uploadProgress * 100).ToString() + "%";
                    uploadMsgFields.MessageDetails("Upload Progress ...", progress);
                    if (uwr.isNetworkError || uwr.isHttpError)
                    {
                        DestroyUploadProgressMessage(uploadMsgFields);
                        yield break;
                    }
                    yield return(null);
                }
                DestroyUploadProgressMessage(uploadMsgFields);
            }
            else
            {
                yield return(uwr.SendWebRequest());
            }

            if (uwr.result != UnityWebRequest.Result.Success)
            {
                if (isSingleFile)
                {
                    DisplayUploadErrorMessage(uwr.error);
                }
                else
                {
                    ErrorCallback(true, uwr.error + "\n" + resp.fields.key);
                }
            }
            else
            {
                Debug.Log("File Upload Success! : " + filename);
                //Debug.Log(uwr.GetResponseHeader("Location"));
                if (filename.EndsWith(TypeGLTF) || filename.EndsWith(TypeGLB))
                {
                    gltfUrl = uwr.GetResponseHeader("Location");
                    gltfUrl = UnityWebRequest.UnEscapeURL(gltfUrl);
                    if (isSingleFile)
                    {
                        yield return(PushUrlToDatabase(gltfUrl));
                    }
                }
            }
        }
    }
Esempio n. 25
0
    IEnumerator ShowEnvLoadDialogCoroutine()
    {
        yield return(FileBrowser.WaitForLoadDialog(FileBrowser.PickMode.FilesAndFolders, false, Application.dataPath + "/MatsJson/", null, "Load environment", "Load"));

        if (FileBrowser.Success)
        {
            string destinationPath = FileBrowser.Result[0];
            DeserializeField(FileBrowserHelpers.GetDirectoryName(FileBrowser.Result[0]), FileBrowserHelpers.GetFilename(FileBrowser.Result[0]));
        }
    }