Search in sources :

Example 1 with DropboxFile

use of com.goxr3plus.xr3player.controllers.dropbox.DropboxFile in project XR3Player by goxr3plus.

the class DropboxService method createTask.

@Override
protected Task<Boolean> createTask() {
    return new Task<Boolean>() {

        @Override
        protected Boolean call() throws Exception {
            try {
                // REFRESH?
                if (operation == DropBoxOperation.REFRESH) {
                    // Create the Client
                    if (client == null || previousAccessToken == null || !previousAccessToken.equals(dropBoxViewer.getAccessToken())) {
                        previousAccessToken = dropBoxViewer.getAccessToken();
                        client = new DbxClientV2(config, dropBoxViewer.getAccessToken());
                    }
                    // Get current account info
                    final FullAccount account = client.users().getCurrentAccount();
                    Platform.runLater(() -> dropBoxViewer.getTopMenuButton().setText(" " + account.getName().getDisplayName()));
                    // List all the files brooooo!
                    final ObservableList<DropboxFile> observableList = FXCollections.observableArrayList();
                    listAllFiles(currentPath, observableList, false, true);
                    // Check if folder is empty
                    Platform.runLater(() -> {
                        dropBoxViewer.getSearchResultsLabel().setVisible(false);
                        dropBoxViewer.getEmptyFolderLabel().setVisible(observableList.isEmpty());
                        // Set the items to TableView
                        dropBoxViewer.getDropboxFilesTableViewer().getTableView().getItems().clear();
                        dropBoxViewer.getDropboxFilesTableViewer().getTableView().getItems().addAll(observableList);
                        dropBoxViewer.getDropboxFilesTableViewer().updateLabel();
                        // Sort the Table
                        dropBoxViewer.getDropboxFilesTableViewer().sortTable();
                        // Make the CacheService Available to the bro user
                        if (searchCacheService.getCachedList().isEmpty() && !searchCacheService.isRunning())
                            searchCacheService.prepareCachedSearch(client);
                    });
                } else if (operation == DropBoxOperation.DELETE) {
                    // Delete all the selected files and folders
                    final List<DropboxFile> list = dropBoxViewer.getDropboxFilesTableViewer().getSelectionModel().getSelectedItems().stream().collect(Collectors.toList());
                    // Remove from the TreeView one by one
                    list.forEach(item -> {
                        if (delete(item.getMetadata().getPathLower()))
                            Platform.runLater(() -> dropBoxViewer.getDropboxFilesTableViewer().getTableView().getItems().remove(item));
                    });
                    // Update the bottom label
                    Platform.runLater(() -> {
                        // Update the Label
                        dropBoxViewer.getDropboxFilesTableViewer().updateLabel();
                        // Sort the Table
                        dropBoxViewer.getDropboxFilesTableViewer().sortTable();
                    });
                } else if (operation == DropBoxOperation.CREATE_FOLDER) {
                    // Create Folder
                    createFolder(folderName);
                    // Refresh
                    Platform.runLater(() -> refresh(currentPath));
                } else if (operation == DropBoxOperation.RENAME) {
                    // Try to rename
                    rename(dropboxFile.getMetadata().getPathLower(), newPath);
                } else if (operation == DropBoxOperation.SEARCH) {
                    ObservableList<DropboxFile> observableList;
                    // CountDown Latch
                    final CountDownLatch countDown = new CountDownLatch(1);
                    final boolean[] searchCacheServiceIsRunning = { false };
                    Platform.runLater(() -> {
                        searchCacheServiceIsRunning[0] = searchCacheService.isRunning();
                        countDown.countDown();
                    });
                    // Wait
                    countDown.await();
                    // Check if cached search is available
                    if (!searchCacheService.getCachedList().isEmpty() && !searchCacheServiceIsRunning[0]) {
                        System.out.println("Doing ++CACHED SEARCH++");
                        // Search based on cachedList
                        observableList = cachedSearch(searchCacheService.getCachedList());
                    } else // Do normal global search
                    {
                        System.out.println("Doing --NORMAL SEARCH--");
                        searchMatchingFilesCounter = 0;
                        // Prepare an observableList
                        observableList = FXCollections.observableArrayList();
                        // Clear Cached Search
                        searchCacheService.getCachedList().clear();
                        // Start a normal Search
                        search("", observableList);
                    }
                    // Run of JavaFX Thread
                    Platform.runLater(() -> {
                        // Set Label Visible
                        dropBoxViewer.getSearchResultsLabel().setVisible(true);
                        // Set the items to TableView
                        dropBoxViewer.getDropboxFilesTableViewer().getTableView().getItems().clear();
                        dropBoxViewer.getDropboxFilesTableViewer().getTableView().getItems().addAll(observableList);
                        // Set Label Visible
                        dropBoxViewer.getSearchResultsLabel().setText("Total Found -> " + InfoTool.getNumberWithDots(observableList.size()));
                        dropBoxViewer.getDropboxFilesTableViewer().updateLabel();
                        // Sort the Table
                        dropBoxViewer.getDropboxFilesTableViewer().sortTable();
                    });
                }
            } catch (final ListFolderErrorException ex) {
                ex.printStackTrace();
                // Show to user about the error
                Platform.runLater(() -> AlertTool.showNotification("Missing Folder", "Folder : [ " + currentPath + " ] doesn't exist.", Duration.seconds(2), NotificationType.ERROR));
                // Check the Internet Connection
                checkConnection();
            } catch (final Exception ex) {
                ex.printStackTrace();
                // Check the Internet Connection
                checkConnection();
                // Change the Operation so CachedSearch works correctly
                operation = DropBoxOperation.STOPPED;
                return false;
            }
            // Change the Operation so CachedSearch works correctly
            operation = DropBoxOperation.STOPPED;
            return true;
        }

        /**
         * Check if there is Internet Connection
         */
        private boolean checkConnection() {
            // Check if there is Internet Connection
            if (!NetworkingTool.isReachableByPing("www.google.com")) {
                Platform.runLater(() -> dropBoxViewer.getErrorVBox().setVisible(true));
                return false;
            }
            return true;
        }

        /**
         * List all the Files inside DropboxAccount
         * @param path
         * @param children
         * @param recursive
         * @param appendToMap
         * @throws DbxException
         * @throws ListFolderErrorException
         */
        public void listAllFiles(final String path, final ObservableList<DropboxFile> children, final boolean recursive, final boolean appendToMap) throws DbxException {
            ListFolderResult result = client.files().listFolder(path);
            while (true) {
                for (final Metadata metadata : result.getEntries()) {
                    if (metadata instanceof DeletedMetadata) {
                    // Deleted
                    // children.remove(metadata.getPathLower())
                    } else if (metadata instanceof FolderMetadata) {
                        // Folder
                        final String folder = metadata.getPathLower();
                        // "/")
                        if (appendToMap)
                            children.add(new DropboxFile(metadata));
                        if (recursive)
                            listAllFiles(folder, children, true, appendToMap);
                    } else if (metadata instanceof FileMetadata) {
                        // "/")
                        if (appendToMap)
                            children.add(new DropboxFile(metadata));
                    // boolean subFileOfCurrentFolder = path.equals(parent)
                    // System.out.println( ( subFileOfCurrentFolder ? "" : "\n" ) + "File->" + file
                    // + " Media Info: " + InfoTool.isAudioSupported(file))
                    }
                }
                if (!result.getHasMore())
                    break;
                try {
                    result = client.files().listFolderContinue(result.getCursor());
                // System.out.println("Entered result next")
                } catch (final ListFolderContinueErrorException ex) {
                    ex.printStackTrace();
                }
            }
        }

        /**
         * List all the Files inside DropboxAccount
         * @param path
         * @param children
         * @throws DbxException
         */
        public void search(final String path, final ObservableList<DropboxFile> children) throws DbxException {
            ListFolderResult result = client.files().listFolder(path);
            while (true) {
                for (final Metadata metadata : result.getEntries()) {
                    if (metadata instanceof DeletedMetadata) {
                    // Deleted
                    // children.remove(metadata.getPathLower())
                    } else if (metadata instanceof FolderMetadata) {
                        // Folder
                        final String folder = metadata.getPathLower();
                        if (metadata.getName().toLowerCase().contains(searchWord))
                            children.add(new DropboxFile(metadata));
                        // Run again
                        search(folder, children);
                    } else if (metadata instanceof FileMetadata) {
                        // File
                        if (metadata.getName().toLowerCase().contains(searchWord)) {
                            children.add(new DropboxFile(metadata));
                            ++searchMatchingFilesCounter;
                            // Refresh the Search Label
                            Platform.runLater(() -> dropBoxViewer.getRefreshLabel().setText("Searching , found [ " + InfoTool.getNumberWithDots(searchMatchingFilesCounter) + " ] matching files"));
                        // System.out.println(searchMatchingFilesCounter)
                        }
                        // Add each and every item to the cached search list
                        searchCacheService.getCachedList().add(metadata);
                    // System.out.println(searchCacheService.getCachedList().size());
                    }
                }
                if (!result.getHasMore())
                    break;
                try {
                    result = client.files().listFolderContinue(result.getCursor());
                // System.out.println("Entered result next")
                } catch (final ListFolderContinueErrorException ex) {
                    ex.printStackTrace();
                }
            }
        }

        /**
         * List all the Files inside DropboxAccount
         *
         * @return
         */
        public ObservableList<DropboxFile> cachedSearch(final List<Metadata> cachedList) {
            // Find matching patterns
            return cachedList.stream().filter(metadata -> metadata.getName().toLowerCase().contains(searchWord)).map(DropboxFile::new).collect(Collectors.toCollection(FXCollections::observableArrayList));
        }

        /**
         * Deletes the given file or folder from Dropbox Account
         *
         * @param path The path of the Dropbox File or Folder
         */
        public boolean delete(final String path) {
            try {
                if (operation == DropBoxOperation.DELETE)
                    client.files().deleteV2(path);
                else
                    // SUPPORTED ONLY ON BUSINESS PLAN
                    client.files().permanentlyDelete(path);
                // Show message to the User
                Platform.runLater(() -> AlertTool.showNotification("Delete was successful", "Successfully deleted selected files/folders", Duration.millis(2000), NotificationType.SIMPLE, JavaFXTool.getFontIcon("fa-dropbox", dropBoxViewer.FONT_ICON_COLOR, 64)));
                return true;
            } catch (final DbxException dbxe) {
                dbxe.printStackTrace();
                // Show message to the User
                Platform.runLater(() -> AlertTool.showNotification("Failed deleting files", "Failed to delete selected files/folders", Duration.millis(2000), NotificationType.ERROR));
                return false;
            }
        }

        /**
         * Renames the given file or folder from Dropbox Account
         *
         * @param oldPath
         * @param newPath
         */
        public boolean rename(final String oldPath, final String newPath) {
            try {
                final RelocationResult result = client.files().moveV2(oldPath, newPath);
                // Run on JavaFX Thread
                Platform.runLater(() -> {
                    // Show message
                    AlertTool.showNotification("Rename Successful", "Succesfully renamed file :\n [ " + dropboxFile.getMetadata().getName() + " ] to -> [ " + result.getMetadata().getName() + " ]", Duration.millis(2500), NotificationType.SIMPLE, JavaFXTool.getFontIcon("fa-dropbox", DropboxViewer.FONT_ICON_COLOR, 64));
                    // Return the previous name
                    dropboxFile.setMetadata(result.getMetadata());
                    // Sort the Table
                    dropBoxViewer.getDropboxFilesTableViewer().sortTable();
                });
                return true;
            } catch (final DbxException dbxe) {
                dbxe.printStackTrace();
                // Run on JavaFX Thread
                Platform.runLater(() -> {
                    // Show message
                    AlertTool.showNotification("Error Message", "Failed to rename the File:\n [ " + dropboxFile.getMetadata().getName() + " ] to -> [ " + newPath + " ]", Duration.millis(2500), NotificationType.ERROR);
                    // Return the previous name
                    dropboxFile.titleProperty().set(dropboxFile.getMetadata().getName());
                });
                return false;
            }
        }

        /**
         * Create a folder from Dropbox Account
         *
         * @param path Folder name
         */
        public boolean createFolder(final String path) {
            try {
                // Create new folder
                final CreateFolderResult result = client.files().createFolderV2(path, true);
                // Show message to the User
                Platform.runLater(() -> AlertTool.showNotification("New folder created", "Folder created with name :\n [ " + result.getMetadata().getName() + " ]", Duration.millis(2000), NotificationType.SIMPLE, JavaFXTool.getFontIcon("fa-dropbox", DropboxViewer.FONT_ICON_COLOR, 64)));
                return true;
            } catch (final DbxException dbxe) {
                dbxe.printStackTrace();
                // Show message to the User
                Platform.runLater(() -> AlertTool.showNotification("Failed creating folder", "Folder was not created", Duration.millis(2000), NotificationType.ERROR));
                return false;
            }
        }
    };
}
Also used : JavaFXTool(com.goxr3plus.xr3player.utils.javafx.JavaFXTool) DbxClientV2(com.dropbox.core.v2.DbxClientV2) DropboxViewer(com.goxr3plus.xr3player.controllers.dropbox.DropboxViewer) FXCollections(javafx.collections.FXCollections) ListFolderResult(com.dropbox.core.v2.files.ListFolderResult) DropboxFile(com.goxr3plus.xr3player.controllers.dropbox.DropboxFile) DropBoxOperation(com.goxr3plus.xr3player.enums.DropBoxOperation) CreateFolderResult(com.dropbox.core.v2.files.CreateFolderResult) Task(javafx.concurrent.Task) NetworkingTool(com.goxr3plus.xr3player.utils.general.NetworkingTool) DbxRequestConfig(com.dropbox.core.DbxRequestConfig) FolderMetadata(com.dropbox.core.v2.files.FolderMetadata) DeletedMetadata(com.dropbox.core.v2.files.DeletedMetadata) RelocationResult(com.dropbox.core.v2.files.RelocationResult) InfoTool(com.goxr3plus.xr3player.utils.general.InfoTool) FullAccount(com.dropbox.core.v2.users.FullAccount) NotificationType(com.goxr3plus.xr3player.enums.NotificationType) Service(javafx.concurrent.Service) ListFolderContinueErrorException(com.dropbox.core.v2.files.ListFolderContinueErrorException) Collectors(java.util.stream.Collectors) Platform(javafx.application.Platform) CountDownLatch(java.util.concurrent.CountDownLatch) FileMetadata(com.dropbox.core.v2.files.FileMetadata) List(java.util.List) AlertTool(com.goxr3plus.xr3player.utils.javafx.AlertTool) Duration(javafx.util.Duration) DbxException(com.dropbox.core.DbxException) ListFolderErrorException(com.dropbox.core.v2.files.ListFolderErrorException) ObservableList(javafx.collections.ObservableList) Metadata(com.dropbox.core.v2.files.Metadata) ListFolderContinueErrorException(com.dropbox.core.v2.files.ListFolderContinueErrorException) Task(javafx.concurrent.Task) RelocationResult(com.dropbox.core.v2.files.RelocationResult) ListFolderErrorException(com.dropbox.core.v2.files.ListFolderErrorException) FolderMetadata(com.dropbox.core.v2.files.FolderMetadata) DeletedMetadata(com.dropbox.core.v2.files.DeletedMetadata) FileMetadata(com.dropbox.core.v2.files.FileMetadata) Metadata(com.dropbox.core.v2.files.Metadata) FileMetadata(com.dropbox.core.v2.files.FileMetadata) FolderMetadata(com.dropbox.core.v2.files.FolderMetadata) DeletedMetadata(com.dropbox.core.v2.files.DeletedMetadata) CountDownLatch(java.util.concurrent.CountDownLatch) ListFolderContinueErrorException(com.dropbox.core.v2.files.ListFolderContinueErrorException) DbxException(com.dropbox.core.DbxException) ListFolderErrorException(com.dropbox.core.v2.files.ListFolderErrorException) CreateFolderResult(com.dropbox.core.v2.files.CreateFolderResult) DbxClientV2(com.dropbox.core.v2.DbxClientV2) DropboxFile(com.goxr3plus.xr3player.controllers.dropbox.DropboxFile) ObservableList(javafx.collections.ObservableList) ListFolderResult(com.dropbox.core.v2.files.ListFolderResult) List(java.util.List) ObservableList(javafx.collections.ObservableList) FullAccount(com.dropbox.core.v2.users.FullAccount) DbxException(com.dropbox.core.DbxException)

Example 2 with DropboxFile

use of com.goxr3plus.xr3player.controllers.dropbox.DropboxFile in project XR3Player by goxr3plus.

the class DownloadService method createTask.

@Override
protected Task<Boolean> createTask() {
    return new Task<Boolean>() {

        @Override
        protected Boolean call() throws Exception {
            try {
                // Create the Client
                client = new DbxClientV2(config, dropBoxViewer.getAccessToken());
                // Try to download the File
                downloadFile(client, dropboxFile, localFileAbsolutePath);
                // Show message to the User
                Platform.runLater(() -> AlertTool.showNotification("Download completed", "Completed downloading " + (!dropboxFile.isDirectory() ? "File" : FOLDER) + " :\n[ " + dropboxFile.getMetadata().getName() + " ]", Duration.millis(3000), NotificationType.SIMPLE, JavaFXTool.getFontIcon("fa-dropbox", DropboxViewer.FONT_ICON_COLOR, 64)));
                // Update the progress
                updateProgress(1, 1);
                return true;
            } catch (final Exception ex) {
                ex.printStackTrace();
                // Show message to the User
                Platform.runLater(() -> AlertTool.showNotification("Download Failed", "Failed to download " + (!dropboxFile.isDirectory() ? "File" : FOLDER) + ":\n[ " + dropboxFile.getMetadata().getName() + " ]", Duration.millis(3000), NotificationType.ERROR));
                return false;
            }
        }

        /**
         * Download Dropbox File to Local Computer
         *
         * @param client                Current connected client
         * @param dropboxFile           The file path on the Dropbox cloud server ->
         *                              [/foldername/something.txt] or a Folder [/fuck]
         * @param localFileAbsolutePath The absolute file path of the File on the Local
         *                              File System
         * @throws DbxException
         * @throws DownloadErrorException
         * @throws IOException
         */
        public void downloadFile(final DbxClientV2 client, final DropboxFile dropboxFile, final String localFileAbsolutePath) throws DownloadErrorException, DbxException, IOException {
            final String dropBoxFilePath = dropboxFile.getMetadata().getPathLower();
            // Simple File
            if (!dropboxFile.isDirectory()) {
                // Create DbxDownloader
                downloadFile = client.files().download(dropBoxFilePath);
                try (// FileOutputStream
                FileOutputStream fOut = new FileOutputStream(localFileAbsolutePath);
                    // ProgressOutPutStream
                    ProgressOutputStream output = new ProgressOutputStream(fOut, downloadFile.getResult().getSize(), (long completed, long totalSize) -> {
                        // System.out.println( ( completed * 100 ) / totalSize + " %")
                        updateProgress((completed * 100), totalSize);
                    })) {
                    // FileOutputStream
                    System.out.println("Downloading .... " + dropBoxFilePath);
                    // Add a progress Listener
                    downloadFile.download(output);
                // Fast way...
                // client.files().downloadBuilder(file).download(new
                // FileOutputStream("downloads/" + md.getName()))
                // DbxRawClientV2 rawClient = new
                // DbxRawClientV2(config,dropBoxViewer.getAccessToken())
                // DbxUserFilesRequests r = new DbxUserFilesRequests(client)
                } catch (final Exception ex) {
                    ex.printStackTrace();
                }
            // Directory
            } else {
                // Create DbxDownloader
                downloadFolder = client.files().downloadZip(dropBoxFilePath);
                try (// FileOutputStream
                FileOutputStream fOut = new FileOutputStream(localFileAbsolutePath)) {
                    // FileOutputStream
                    System.out.println("Downloading .... " + dropBoxFilePath);
                    // Add a progress Listener
                    downloadFolder.download(fOut);
                } catch (final Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    };
}
Also used : DbxClientV2(com.dropbox.core.v2.DbxClientV2) Task(javafx.concurrent.Task) DropboxFile(com.goxr3plus.xr3player.controllers.dropbox.DropboxFile) FileOutputStream(java.io.FileOutputStream) ProgressOutputStream(com.goxr3plus.xr3player.controllers.dropbox.ProgressOutputStream) IOException(java.io.IOException) DownloadErrorException(com.dropbox.core.v2.files.DownloadErrorException) DbxException(com.dropbox.core.DbxException)

Aggregations

DbxException (com.dropbox.core.DbxException)2 DbxClientV2 (com.dropbox.core.v2.DbxClientV2)2 DropboxFile (com.goxr3plus.xr3player.controllers.dropbox.DropboxFile)2 Task (javafx.concurrent.Task)2 DbxRequestConfig (com.dropbox.core.DbxRequestConfig)1 CreateFolderResult (com.dropbox.core.v2.files.CreateFolderResult)1 DeletedMetadata (com.dropbox.core.v2.files.DeletedMetadata)1 DownloadErrorException (com.dropbox.core.v2.files.DownloadErrorException)1 FileMetadata (com.dropbox.core.v2.files.FileMetadata)1 FolderMetadata (com.dropbox.core.v2.files.FolderMetadata)1 ListFolderContinueErrorException (com.dropbox.core.v2.files.ListFolderContinueErrorException)1 ListFolderErrorException (com.dropbox.core.v2.files.ListFolderErrorException)1 ListFolderResult (com.dropbox.core.v2.files.ListFolderResult)1 Metadata (com.dropbox.core.v2.files.Metadata)1 RelocationResult (com.dropbox.core.v2.files.RelocationResult)1 FullAccount (com.dropbox.core.v2.users.FullAccount)1 DropboxViewer (com.goxr3plus.xr3player.controllers.dropbox.DropboxViewer)1 ProgressOutputStream (com.goxr3plus.xr3player.controllers.dropbox.ProgressOutputStream)1 DropBoxOperation (com.goxr3plus.xr3player.enums.DropBoxOperation)1 NotificationType (com.goxr3plus.xr3player.enums.NotificationType)1