From 2e00316c3830ea4a1696ae4d6dd1f682707d1f72 Mon Sep 17 00:00:00 2001 From: bharathkalyans Date: Sun, 1 Jan 2023 13:31:28 +0530 Subject: [PATCH 1/9] Reformatted the Drifty_CLI file and extracted the utility methods to separate package and extracted the Hardcoded String values to Constants into the DriftyConstants. --- .idea/checkstyle-idea.xml | 15 ++ .idea/sonarlint/issuestore/index.pb | 0 Website/script.js | 10 +- src/Drifty_CLI.java | 266 +++++++++------------------ src/FileDownloader.java | 193 +++++++++---------- src/constants/DriftyConstants.java | 45 +++++ src/{ => singleton}/CreateLogs.java | 46 ++--- src/utility/DriftyUtility.java | 80 ++++++++ src/validation/DriftyValidation.java | 47 +++++ 9 files changed, 399 insertions(+), 303 deletions(-) create mode 100644 .idea/checkstyle-idea.xml create mode 100644 .idea/sonarlint/issuestore/index.pb create mode 100644 src/constants/DriftyConstants.java rename src/{ => singleton}/CreateLogs.java (73%) create mode 100644 src/utility/DriftyUtility.java create mode 100644 src/validation/DriftyValidation.java diff --git a/.idea/checkstyle-idea.xml b/.idea/checkstyle-idea.xml new file mode 100644 index 000000000..dcf1d4d17 --- /dev/null +++ b/.idea/checkstyle-idea.xml @@ -0,0 +1,15 @@ + + + + 10.5.0 + JavaOnly + + + \ No newline at end of file diff --git a/.idea/sonarlint/issuestore/index.pb b/.idea/sonarlint/issuestore/index.pb new file mode 100644 index 000000000..e69de29bb diff --git a/Website/script.js b/Website/script.js index 1ae6d8ce7..ad1230026 100644 --- a/Website/script.js +++ b/Website/script.js @@ -13,8 +13,8 @@ fetch( }); function download_alert_window() { - var w = confirm("Do you want to download Drifty?"); - if (w == true) { + let w = confirm("Do you want to download Drifty?"); + if (w === true) { alert("Thanks for Downloading"); window.open( "https://github.com/SaptarshiSarkar12/Drifty/releases/latest/download/Drifty_CLI.exe" @@ -25,8 +25,8 @@ function download_alert_window() { } function download_alert_apple() { - var a = confirm("Do you want to download Drifty?"); - if (a == true) { + let a = confirm("Do you want to download Drifty?"); + if (a === true) { alert("Thanks for Downloading"); window.open( "https://github.com/SaptarshiSarkar12/Drifty/releases/latest/download/Drifty.jar" @@ -248,7 +248,7 @@ function toggleMore(btn, id) { function renderAssets(assets) { return assets.reduce((all, asset) => { //check if it is for windows - let is_windows = asset.name.split(".").pop().toLocaleLowerCase() == "exe"; + let is_windows = asset.name.split(".").pop().toLocaleLowerCase() === "exe"; if (is_windows) { return `${all} Download `; diff --git a/src/Drifty_CLI.java b/src/Drifty_CLI.java index 56ad2a97c..1c3a932c7 100644 --- a/src/Drifty_CLI.java +++ b/src/Drifty_CLI.java @@ -1,291 +1,191 @@ -import java.io.IOException; -import java.net.URL; +import singleton.CreateLogs; +import utility.DriftyUtility; +import validation.DriftyValidation; + import java.util.Objects; import java.util.Scanner; +import static constants.DriftyConstants.*; + + /** * This is the main class for the CLI version of Drifty. + * * @author Saptarshi Sarkar, Akshat Jain, Anurag Bharati, Naachiket Pant, Fonta22 * @version 1.2.2 */ public class Drifty_CLI { - private static String downloadsFolder; + public static final CreateLogs logger = new CreateLogs("Drift_CLI_LOG.log"); + public static final String VERSION_NUMBER = "v1.2.2"; protected static final Scanner SC = new Scanner(System.in); - public static CreateLogs logger = new CreateLogs("Drifty_CLI_LOG.log"); - public static final String ANSI_RESET = "\u001B[0m"; - public static final String ANSI_CYAN = "\u001B[36m"; - public static final String ANSI_PURPLE = "\u001B[35m"; - private static String fName = null; protected static boolean isYoutubeURL; - public static String versionNumber = "v1.2.2"; + private static String downloadsFolder; + private static String fileName = null; /** * This function is the main method of the whole application. + * * @param args Command Line Arguments as a String array. */ public static void main(String[] args) { - logger.log("INFO", "Application Started !"); - initialPrintBanner(); - if (args.length > 0){ + logger.log(LOGGER_INFO, APPLICATION_STARTED); + DriftyUtility.initialPrintBanner(); + if (args.length > 0) { String URL = args[0]; String name = null; String location = null; - for (int i = 0; i < args.length; i++){ - if (Objects.equals(args[i], "-help") || Objects.equals(args[i], "-h")){ - help(); + for (int i = 0; i < args.length; i++) { + if (Objects.equals(args[i], HELP_FLAG) || Objects.equals(args[i], HELP_FLAG_SHORT)) { + DriftyUtility.help(); System.exit(0); - } else if (Objects.equals(args[i], "-name") || (Objects.equals(args[i], "-n"))){ - name = args[i+1]; - } else if (Objects.equals(args[i], "-location") || (Objects.equals(args[i], "-l"))){ - location = args[i+1]; - } else if (Objects.equals(args[i], "-version") || (Objects.equals(args[i], "-v"))) { - System.out.println("Drifty " + versionNumber); + } else if (Objects.equals(args[i], NAME_FLAG) || (Objects.equals(args[i], NAME_FLAG_SHORT))) { + name = args[i + 1]; + } else if (Objects.equals(args[i], LOCATION_FLAG) || (Objects.equals(args[i], LOCATION_FLAG_SHORT))) { + location = args[i + 1]; + } else if (Objects.equals(args[i], VERSION_FLAG) || (Objects.equals(args[i], VERSION_FLAG_SHORT))) { + System.out.println(APPLICATION_NAME + " " + VERSION_NUMBER); System.exit(0); } } - if (!isURLValid(URL)) { - System.out.println("URL is invalid!"); - logger.log("ERROR", "URL is invalid!"); + if (!DriftyUtility.isURLValid(URL)) { + System.out.println(INVALID_URL); + logger.log(LOGGER_ERROR, INVALID_URL); System.exit(0); } - isYoutubeURL = isYoutubeLink(URL); - fName = (name==null) ? fName : name; - if ((fName==null || !containsFilename(URL)) && (!isYoutubeURL)) { - System.out.print("Enter the filename (with file extension) : "); - fName = SC.nextLine(); + isYoutubeURL = DriftyUtility.isYoutubeLink(URL); + fileName = (name == null) ? fileName : name; + if ((fileName == null || !containsFilename(URL)) && (!isYoutubeURL)) { + System.out.print(FILE_NAME_WITH_EXTENSION); + fileName = SC.nextLine(); } downloadsFolder = location; - if (downloadsFolder == null){ + if (downloadsFolder == null) { saveToDefault(); - } - else { - if (System.getProperty("os.name").contains("Windows")) { + } else { + if (System.getProperty(OS_NAME).contains(WINDOWS_OS_NAME)) { downloadsFolder = SC.nextLine().replace('/', '\\'); if (!(downloadsFolder.endsWith("\\"))) { downloadsFolder = downloadsFolder + System.getProperty("file.separator"); } } } - new FileDownloader(URL, fName, downloadsFolder).run(); + new FileDownloader(URL, fileName, downloadsFolder).run(); System.exit(0); } - while(true) { - fName = null; + while (true) { + fileName = null; String link; while (true) { - System.out.print("Enter the link to the file : "); + System.out.print(FILE_LINK); link = SC.nextLine(); - isYoutubeURL = isYoutubeLink(link); - if (isYoutubeURL){ + isYoutubeURL = DriftyUtility.isYoutubeLink(link); + if (isYoutubeURL) { break; } - if (!isURLValid(link)) { - System.out.println("Invalid URL. Please enter again"); + if (!DriftyUtility.isURLValid(link)) { + System.out.println(INVALID_URL_ENTER_AGAIN); } else if (!containsFilename(link)) { - System.out.println("Automatic file name detection failed!"); - logger.log("ERROR", "Automatic file name detection failed!"); + System.out.println(AUTOMATIC_FILE_DETECTION); + logger.log(LOGGER_ERROR, AUTOMATIC_FILE_DETECTION); break; } else { break; } } - System.out.print("Do you want to download the file in your default downloads folder? (Enter Y for yes and N for no) : "); - String default_folder = SC.nextLine().toLowerCase(); - boolean yesOrNo = yesNoValidation(default_folder, "Do you want to download the file in your default downloads folder? (Enter Y for yes and N for no) : "); + System.out.print(DOWNLOAD_DEFAULT_LOCATION); + String defaultFolder = SC.nextLine().toLowerCase(); + boolean yesOrNo = DriftyValidation.yesNoValidation(defaultFolder, DOWNLOAD_DEFAULT_LOCATION); if (yesOrNo) { saveToDefault(); } else { enterDownloadsFolder(); } if (!isYoutubeURL) { - if (fName != null) { - System.out.print("Would you like to rename this file? (Enter Y for yes and N for no) : "); + if (fileName != null) { + System.out.print(RENAME_FILE); String renameFile = SC.nextLine().toLowerCase(); - yesOrNo = yesNoValidation(renameFile, "Would you like to rename this file? (Enter Y for yes and N for no) : "); + yesOrNo = DriftyValidation.yesNoValidation(renameFile, RENAME_FILE); if (yesOrNo) { - System.out.print("Enter the filename (with file extension) : "); - fName = SC.nextLine(); + System.out.print(FILE_NAME_WITH_EXTENSION); + fileName = SC.nextLine(); } } else { - System.out.print("Enter the filename (with file extension) : "); - fName = SC.nextLine(); + System.out.print(FILE_NAME_WITH_EXTENSION); + fileName = SC.nextLine(); } } - new FileDownloader(link, fName, downloadsFolder).run(); - System.out.println("Press Q to Quit Or Press any Key to Continue"); + new FileDownloader(link, fileName, downloadsFolder).run(); + System.out.println(QUIT_OR_CONTINUE); String quit = SC.nextLine().toLowerCase(); - if(quit.equals("q")){ - logger.log("INFO", "Application Terminated!"); + if (quit.equals("q")) { + logger.log(LOGGER_INFO, APPLICATION_TERMINATED); break; } - printBanner(); + DriftyUtility.printBanner(); } } /** * This function takes a folder path as input from the user, where the file will be saved. */ - private static void enterDownloadsFolder(){ - System.out.print("Enter the directory in which you want to download the file : "); + private static void enterDownloadsFolder() { + System.out.print(DIRECTORY_TO_DOWNLOAD_FILE); downloadsFolder = SC.nextLine(); - if (System.getProperty("os.name").contains("Windows")) { + if (System.getProperty(OS_NAME).contains(WINDOWS_OS_NAME)) { downloadsFolder = SC.nextLine().replace('/', '\\'); if (!(downloadsFolder.endsWith("\\"))) { downloadsFolder = downloadsFolder + System.getProperty("file.separator"); } } - logger.log("INFO", "Custom Directory Entered : " + downloadsFolder); + logger.log(LOGGER_INFO, "Custom Directory Entered : " + downloadsFolder); } /** * This function tries to detect the default downloads folder and save the file in that folder */ - private static void saveToDefault(){ - System.out.println("Trying to auto-detect default Downloads folder..."); - logger.log("INFO", "Trying to auto-detect default Downloads folder..."); - if (!System.getProperty("os.name").contains("Windows")) { - String home = System.getProperty("user.home"); - downloadsFolder = home + "/Downloads/"; - } - else { + private static void saveToDefault() { + System.out.println(TRYING_TO_AUTOMATICALLY_DETECT_FILE); + logger.log(LOGGER_ERROR, TRYING_TO_AUTOMATICALLY_DETECT_FILE); + if (!System.getProperty(OS_NAME).contains(WINDOWS_OS_NAME)) { + String home = System.getProperty(USER_HOME_PROPERTY); + downloadsFolder = home + DOWNLOADS_FILE_PATH; + } else { downloadsFolder = DefaultDownloadFolderLocationFinder.findPath() + System.getProperty("file.separator"); } if (downloadsFolder.equals(System.getProperty("file.separator")) || downloadsFolder == null) { - System.out.println("Failed to retrieve default download folder!"); - logger.log("ERROR", "Failed to retrieve default download folder!"); + System.out.println(FAILED_TO_RETRIEVE_DEFAULT_DOWNLOAD_FOLDER); + logger.log(LOGGER_ERROR, FAILED_TO_RETRIEVE_DEFAULT_DOWNLOAD_FOLDER); enterDownloadsFolder(); } else { - System.out.println("Default download folder detected : " + downloadsFolder); - logger.log("INFO", "Default download folder detected : " + downloadsFolder); - } - } - - /** - * @param link Link to the file that the user wants to download - * @return true if link is valid and false if link is invalid - */ - private static boolean isURLValid(String link){ - try{ - new URL(link).toURI(); - return true; - } - catch (Exception e){ - return false; + System.out.println(DEFAULT_DOWNLOAD_FOLDER + downloadsFolder); + logger.log(LOGGER_INFO, DEFAULT_DOWNLOAD_FOLDER + downloadsFolder); } } - /** - * This method checks whether the link provided is of YouTube or not and returns the resultant boolean value accordingly. - * @param url link to the file to be downloaded. - * @return true if the url is of YouTube and false if it is not. - */ - public static boolean isYoutubeLink(String url) { - String pattern = "^(http(s)?:\\/\\/)?((w){3}.)?youtu(be|.be)?(\\.com)?\\/.+"; - return url.matches(pattern); - } /** * @param link Link to the file that the user wants to download * @return true if the filename is detected and false if the filename is not detected */ - private static boolean containsFilename(String link){ + private static boolean containsFilename(String link) { // Check and inform user if the url contains filename. // Example : "example.com/file.txt" prints "Filename detected: file.txt" // example.com/file.json -> file.json - String file = link.substring(link.lastIndexOf("/")+1); + String file = link.substring(link.lastIndexOf("/") + 1); int index = file.lastIndexOf("."); - if (index < 0 || index > file.length()){ + if (index < 0) { return false; } String extension = file.substring(index); // edge case 1 : "example.com/." - if (extension.length()==1){ + if (extension.length() == 1) { return false; } // file.png?width=200 -> file.png - fName = file.split("([?])")[0]; - System.out.println("Filename detected : " + fName); - logger.log("INFO", "Filename detected : " + fName); + fileName = file.split("([?])")[0]; + System.out.println(FILENAME_DETECTED + fileName); + logger.log(LOGGER_INFO, FILENAME_DETECTED + fileName); return true; } - /** - * This method performs Yes-No validation and returns the boolean value accordingly. - * @param input Input String to validate. - * @param printMsg The message to print to re-input the confirmation. - * @return true if the user enters Y [Yes] and false if not. - */ - public static boolean yesNoValidation(String input, String printMsg){ - while (true) { - if (input.length() == 0) { - System.out.println("Please enter Y for yes and N for no!"); - logger.log("ERROR", "Please enter Y for yes and N for no!"); - } else { - break; - } - System.out.print(printMsg); - input = SC.nextLine().toLowerCase(); - } - char choice = input.charAt(0); - if (choice == 'y') { - return true; - } else if (choice =='n'){ - return false; - } - else { - System.out.println("Invalid input!"); - logger.log("ERROR", "Invalid input"); - System.out.print(printMsg); - input = SC.nextLine().toLowerCase(); - yesNoValidation(input, printMsg); - } - return false; - } - - /** - * This function provides help about how to use the application through command line arguments. - */ - private static void help(){ - System.out.println(ANSI_RESET+"\n\033[38;31;48;40;1m----==| DRIFTY CLI HELP |==----"+ANSI_RESET); - System.out.println("\033[38;31;48;40;0m v1.2.2"+ANSI_RESET); - System.out.println("For more information visit: https://github.com/SaptarshiSarkar12/Drifty/"); - System.out.println("\033[31;1mRequired parameter: File URL"+ANSI_RESET+" \033[3m(This must be the first argument you are passing)"+ANSI_RESET); - System.out.println("\033[33;1mOptional parameters:"); - System.out.println("\033[97;1mName ShortForm Default Description"+ANSI_RESET); - System.out.println("-location -l Downloads The location on your computer where content downloaded from Drifty are placed."); - System.out.println("-name -n Source Renames file."); - System.out.println("-help -h N/A Provides concise information for Drifty CLI.\n"); - System.out.println("-version -v Current Version Number Displays version number of Drifty."); - System.out.println("\033[97;1mExample:" + ANSI_RESET + " \n> \033[37;1mjava Drifty_CLI https://example.com/object.png -n obj.png -l C:/Users/example"+ ANSI_RESET ); - System.out.println("\033[37;3m* Requires java 18 or higher. \n"+ANSI_RESET); - } - - /** - * This function prints the banner of the application in the console. - */ - private static void printBanner(){ - System.out.print("\033[H\033[2J"); - System.out.println(ANSI_PURPLE+"===================================================================="+ANSI_RESET); - System.out.println(ANSI_CYAN+" _____ _____ _____ ______ _______ __ __"+ANSI_RESET); - System.out.println(ANSI_CYAN+" | __ \\ | __ \\ |_ _|| ____||__ __|\\ \\ / /"+ANSI_RESET); - System.out.println(ANSI_CYAN+" | | | || |__) | | | | |__ | | \\ \\_/ /"+ANSI_RESET); - System.out.println(ANSI_CYAN+" | | | || _ / | | | __| | | \\ / "+ANSI_RESET); - System.out.println(ANSI_CYAN+" | |__| || | \\ \\ _| |_ | | | | | | "+ANSI_RESET); - System.out.println(ANSI_CYAN+" |_____/ |_| \\_\\|_____||_| |_| |_| "+ANSI_RESET); - System.out.println(ANSI_PURPLE+"===================================================================="+ANSI_RESET); - } - - /** - * This method prints the banner without any colour of text except white. - */ - private static void initialPrintBanner(){ - System.out.println("===================================================================="); - System.out.println(" _____ _____ _____ ______ _______ __ __"); - System.out.println(" | __ \\ | __ \\ |_ _|| ____||__ __|\\ \\ / /"); - System.out.println(" | | | || |__) | | | | |__ | | \\ \\_/ /"); - System.out.println(" | | | || _ / | | | __| | | \\ / "); - System.out.println(" | |__| || | \\ \\ _| |_ | | | | | | "); - System.out.println(" |_____/ |_| \\_\\|_____||_| |_| |_| "); - System.out.println("===================================================================="); - } } diff --git a/src/FileDownloader.java b/src/FileDownloader.java index 33ac641ab..960458d98 100644 --- a/src/FileDownloader.java +++ b/src/FileDownloader.java @@ -1,3 +1,6 @@ +import utility.DriftyUtility; +import validation.DriftyValidation; + import java.io.*; import java.net.*; import java.nio.channels.Channels; @@ -9,16 +12,16 @@ * This class deals with downloading the file. */ class FileDownloader implements Runnable { + // default number of threads to download with + private final static int numberOfThreads = 3; + // default threading threshold in bytes 50MB + private final static long threadingThreshold = 1024 * 1024 * 50; private static String dir; private static String fileName; private static String link; private static long totalSize; private static URL url; private static boolean supportsMultithreading; - // default number of threads to download with - private final static int numberOfThreads = 3; - // default threading threshold in bytes 50MB - private final static long threadingThreshold = 1024 * 1024 * 50; /** * This is a constructor to initialise values of link, fileName and dir variables. @@ -43,92 +46,6 @@ public static String getDir() { return dir; } - /** - * This is the overridden run method of the Runnable interface and deals with the main part of opening connections and downloading the file. - */ - @Override - public void run() { - link = link.replace('\\', '/'); - if (!(link.startsWith("http://") || link.startsWith("https://"))) { - link = "http://" + link; - } - if (link.startsWith("https://github.com/") || (link.startsWith("http://github.com/"))) { - if (!(link.endsWith("?raw=true"))) { - link = link + "?raw=true"; - } - } - try { - // If link is of an YouTube video, then the following block of code will execute. - if (Drifty_CLI.isYoutubeLink(link)) { - try { - downloadFromYouTube(""); - } catch (IOException e) { - try { - System.out.println("Getting ready to download the file..."); - Drifty_CLI.logger.log("INFO", "Getting ready to download the file..."); - copyYt_dlp cy = new copyYt_dlp(); - cy.copyToTemp(); - try { - downloadFromYouTube(copyYt_dlp.tempDir); - } catch (InterruptedException ie) { - System.out.println("User interrupted while downloading the file!"); - Drifty_CLI.logger.log("ERROR", "User interrupted while downloading the file! " + ie.getMessage()); - } catch (IOException io1) { - System.out.println("Failed to download YouTube video!"); - Drifty_CLI.logger.log("ERROR", "Failed to download YouTube video! " + io1.getMessage()); - } - } catch (IOException io) { - System.out.println("Failed to initialise YouTube video downloader!"); - Drifty_CLI.logger.log("ERROR", "Failed to initialise YouTube video downloader! " + io.getMessage()); - } - } catch (InterruptedException e) { - System.out.println("User interrupted while downloading the file!"); - Drifty_CLI.logger.log("ERROR", "User interrupted while downloading the file! " + e.getMessage()); - } - } else { - url = new URL(link); - URLConnection openConnection = url.openConnection(); - openConnection.connect(); - totalSize = openConnection.getHeaderFieldLong("Content-Length", -1); - - String acceptRange = openConnection.getHeaderField("Accept-Ranges"); - FileDownloader.supportsMultithreading = totalSize > threadingThreshold && acceptRange != null && acceptRange.equalsIgnoreCase("bytes"); - - if (fileName.length() == 0) { - String[] webPaths = url.getFile().trim().split("/"); - fileName = webPaths[webPaths.length - 1]; - } - dir = dir.replace('/', '\\'); - if (dir.length() != 0) { - if (dir.equals(".\\\\") || dir.equals(".\\")) { - dir = ""; - } - } else { - System.out.println("Invalid Directory Entered !"); - Drifty_CLI.logger.log("ERROR", "Invalid Directory Entered !"); - } - try { - new CheckDirectory(dir); - } catch (IOException e) { - System.out.println("Failed to create the directory : " + dir + " ! " + e.getMessage()); - Drifty_CLI.logger.log("ERROR", "Failed to create the directory : " + dir + " ! " + e.getMessage()); - } - System.out.println("Trying to download the file..."); - Drifty_CLI.logger.log("INFO", "Trying to download the file..."); - downloadFile(); - } - } catch (MalformedURLException e) { - System.out.println("Invalid Link!"); - Drifty_CLI.logger.log("ERROR", "Invalid Link! " + e.getMessage()); - } catch (SocketTimeoutException e) { - System.out.println("Timed out while connecting to " + url + " !"); - Drifty_CLI.logger.log("ERROR", "Timed out while connecting to " + url + " ! " + e.getMessage()); - } catch (IOException e) { - System.out.println("Failed to connect to " + url + " !"); - Drifty_CLI.logger.log("ERROR", "Failed to connect to " + url + " ! " + e.getMessage()); - } - } - /** * This method deals with downloading the file. */ @@ -170,7 +87,8 @@ private static void downloadFile() { // keep main thread from closing the IO for short amt. of time so UI thread can finish and output try { Thread.sleep(1000); - } catch (InterruptedException ignored) {} + } catch (InterruptedException ignored) { + } } catch (InterruptedException ignored) { } } else { @@ -228,19 +146,19 @@ private static void downloadFromYouTube(String dirOfYt_dlp) throws InterruptedEx Process yt_dlp = processBuilder.start(); yt_dlp.waitFor(); int exitValueOfYt_Dlp = yt_dlp.exitValue(); - if (exitValueOfYt_Dlp != 0){ + if (exitValueOfYt_Dlp != 0) { return; } System.out.print("Would you like to rename this file? (Enter Y for yes and N for no) : "); String renameFile = Drifty_CLI.SC.nextLine().toLowerCase(); - boolean yesOrNo = Drifty_CLI.yesNoValidation(renameFile, "Would you like to rename this file? (Enter Y for yes and N for no) : "); + boolean yesOrNo = DriftyValidation.yesNoValidation(renameFile, "Would you like to rename this file? (Enter Y for yes and N for no) : "); if (yesOrNo) { System.out.print("Enter the filename (with file extension) : "); fName = Drifty_CLI.SC.nextLine(); } System.out.println("Trying to download the file ..."); Drifty_CLI.logger.log("INFO", "Trying to download the file ..."); - if (fName.equals("")){ + if (fName.equals("")) { processBuilder = new ProcessBuilder(dirOfYt_dlp + "yt-dlp", "--quiet", "--progress", "-P", dir, link, "-o", "%(title)s.mp4"); } else { processBuilder = new ProcessBuilder(dirOfYt_dlp + "yt-dlp", "--quiet", "--progress", "-P", dir, link, "-o", fName); @@ -260,6 +178,7 @@ private static void downloadFromYouTube(String dirOfYt_dlp) throws InterruptedEx /** * This method check if all the downloader threads are completed correctly and merges the downloaded parts. + * * @param fileOutputStreams FileOutputStream of all the parts * @param partSizes Size each of the parts * @param downloaderThreads DownloaderThreads of all the parts @@ -301,4 +220,90 @@ public static boolean merge(List fileOutputStreams, List } return false; } + + /** + * This is the overridden run method of the Runnable interface and deals with the main part of opening connections and downloading the file. + */ + @Override + public void run() { + link = link.replace('\\', '/'); + if (!(link.startsWith("http://") || link.startsWith("https://"))) { + link = "http://" + link; + } + if (link.startsWith("https://github.com/") || (link.startsWith("http://github.com/"))) { + if (!(link.endsWith("?raw=true"))) { + link = link + "?raw=true"; + } + } + try { + // If link is of an YouTube video, then the following block of code will execute. + if (DriftyUtility.isYoutubeLink(link)) { + try { + downloadFromYouTube(""); + } catch (IOException e) { + try { + System.out.println("Getting ready to download the file..."); + Drifty_CLI.logger.log("INFO", "Getting ready to download the file..."); + copyYt_dlp cy = new copyYt_dlp(); + cy.copyToTemp(); + try { + downloadFromYouTube(copyYt_dlp.tempDir); + } catch (InterruptedException ie) { + System.out.println("User interrupted while downloading the file!"); + Drifty_CLI.logger.log("ERROR", "User interrupted while downloading the file! " + ie.getMessage()); + } catch (IOException io1) { + System.out.println("Failed to download YouTube video!"); + Drifty_CLI.logger.log("ERROR", "Failed to download YouTube video! " + io1.getMessage()); + } + } catch (IOException io) { + System.out.println("Failed to initialise YouTube video downloader!"); + Drifty_CLI.logger.log("ERROR", "Failed to initialise YouTube video downloader! " + io.getMessage()); + } + } catch (InterruptedException e) { + System.out.println("User interrupted while downloading the file!"); + Drifty_CLI.logger.log("ERROR", "User interrupted while downloading the file! " + e.getMessage()); + } + } else { + url = new URL(link); + URLConnection openConnection = url.openConnection(); + openConnection.connect(); + totalSize = openConnection.getHeaderFieldLong("Content-Length", -1); + + String acceptRange = openConnection.getHeaderField("Accept-Ranges"); + FileDownloader.supportsMultithreading = totalSize > threadingThreshold && acceptRange != null && acceptRange.equalsIgnoreCase("bytes"); + + if (fileName.length() == 0) { + String[] webPaths = url.getFile().trim().split("/"); + fileName = webPaths[webPaths.length - 1]; + } + dir = dir.replace('/', '\\'); + if (dir.length() != 0) { + if (dir.equals(".\\\\") || dir.equals(".\\")) { + dir = ""; + } + } else { + System.out.println("Invalid Directory Entered !"); + Drifty_CLI.logger.log("ERROR", "Invalid Directory Entered !"); + } + try { + new CheckDirectory(dir); + } catch (IOException e) { + System.out.println("Failed to create the directory : " + dir + " ! " + e.getMessage()); + Drifty_CLI.logger.log("ERROR", "Failed to create the directory : " + dir + " ! " + e.getMessage()); + } + System.out.println("Trying to download the file..."); + Drifty_CLI.logger.log("INFO", "Trying to download the file..."); + downloadFile(); + } + } catch (MalformedURLException e) { + System.out.println("Invalid Link!"); + Drifty_CLI.logger.log("ERROR", "Invalid Link! " + e.getMessage()); + } catch (SocketTimeoutException e) { + System.out.println("Timed out while connecting to " + url + " !"); + Drifty_CLI.logger.log("ERROR", "Timed out while connecting to " + url + " ! " + e.getMessage()); + } catch (IOException e) { + System.out.println("Failed to connect to " + url + " !"); + Drifty_CLI.logger.log("ERROR", "Failed to connect to " + url + " ! " + e.getMessage()); + } + } } diff --git a/src/constants/DriftyConstants.java b/src/constants/DriftyConstants.java new file mode 100644 index 000000000..6ead0554f --- /dev/null +++ b/src/constants/DriftyConstants.java @@ -0,0 +1,45 @@ +package constants; + +public final class DriftyConstants { + + public static final String APPLICATION_NAME = "Drifty"; + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_CYAN = "\u001B[36m"; + public static final String ANSI_PURPLE = "\u001B[35m"; + public static final String DOWNLOADS_FILE_PATH = "/Downloads/"; + public static final String LOGGER_INFO = "INFO"; + public static final String LOGGER_ERROR = "ERROR"; + public static final String APPLICATION_STARTED = "Application Started !"; + public static final String APPLICATION_TERMINATED = "Application Terminated!"; + public static final String INVALID_URL = "URL is invalid!"; + public static final String INVALID_URL_ENTER_AGAIN = "Invalid URL. Please enter again"; + public static final String AUTOMATIC_FILE_DETECTION = "Automatic file name detection failed!"; + public static final String TRYING_TO_AUTOMATICALLY_DETECT_FILE = "Trying to auto-detect default Downloads folder..."; + public static final String HELP_FLAG = "-help"; + public static final String NAME_FLAG = "-name"; + public static final String VERSION_FLAG = "-version"; + public static final String LOCATION_FLAG = "-location"; + public static final String HELP_FLAG_SHORT = "-h"; + public static final String NAME_FLAG_SHORT = "-n"; + public static final String VERSION_FLAG_SHORT = "-v"; + public static final String LOCATION_FLAG_SHORT = "-l"; + public static final String FILE_NAME_WITH_EXTENSION = "Enter the filename (with file extension) : "; + public static final String FILE_LINK = "Enter the link to the file : "; + public static final String OS_NAME = "os.name"; + public static final String WINDOWS_OS_NAME = "Windows"; + public static final String USER_HOME_PROPERTY = "user.home"; + public static final String DOWNLOAD_DEFAULT_LOCATION = "Do you want to download the file in your default downloads folder? (Enter Y for yes and N for no) : "; + public static final String RENAME_FILE = "Would you like to rename this file? (Enter Y for yes and N for no) : "; + public static final String QUIT_OR_CONTINUE = "Press Q to Quit Or Press any Key to Continue"; + public static final String DIRECTORY_TO_DOWNLOAD_FILE = "Enter the directory in which you want to download the file : "; + public static final String FAILED_TO_RETRIEVE_DEFAULT_DOWNLOAD_FOLDER = "Failed to retrieve default download folder!"; + public static final String DEFAULT_DOWNLOAD_FOLDER = "Default download folder detected : "; + public static final String FILENAME_DETECTED = "Filename detected : "; + + public static final String BANNER_BORDER = "===================================================================="; + + private DriftyConstants() { + } + + +} diff --git a/src/CreateLogs.java b/src/singleton/CreateLogs.java similarity index 73% rename from src/CreateLogs.java rename to src/singleton/CreateLogs.java index 22ce5ceaf..4c6f55507 100644 --- a/src/CreateLogs.java +++ b/src/singleton/CreateLogs.java @@ -1,3 +1,5 @@ +package singleton; + import java.io.*; import java.nio.file.FileSystems; import java.nio.file.Path; @@ -9,48 +11,50 @@ * This class deals with creating Log files for Drifty. */ public class CreateLogs { - static DateFormat df; + static DateFormat dateFormat; static boolean isLogEmpty; static Path filePath; - static Calendar calObj = Calendar.getInstance(); + static Calendar calendarObject = Calendar.getInstance(); /** * This is the constructor used to initialise the variables in this class. + * * @param logFileName Filename of the Log file. */ - public CreateLogs(String logFileName){ + public CreateLogs(String logFileName) { filePath = FileSystems.getDefault().getPath(logFileName); - df = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); + dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); } /** - * This function actually writes the entries to the log file. - * @param type Type of the Log (acceptable values - INFO, WARN, ERROR). - * @param msg Log message. + * This function clears the contents of the previous log file. */ - public void log(String type, String msg){ - String dateAndTime = df.format(calObj.getTime()); - if (!isLogEmpty){ - clearLog(); - } - try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Drifty_CLI_LOG.log", true))))) { + private static void clearLog() { + try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Drifty_CLI_LOG.log", false))))) { isLogEmpty = true; - out.println(dateAndTime + " " + type.toUpperCase() + " - " + msg); + out.write(""); } catch (IOException e) { - System.out.println("Failed to create log : " + msg); + System.out.println("Failed to clear Log contents !"); +// Drifty_CLI.logger.log("ERROR", "Failed to clear Log contents !"); } } /** - * This function clears the contents of the previous log file. + * This function actually writes the entries to the log file. + * + * @param type Type of the Log (acceptable values - INFO, WARN, ERROR). + * @param msg Log message. */ - private static void clearLog(){ - try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Drifty_CLI_LOG.log", false))))) { + public void log(String type, String msg) { + String dateAndTime = dateFormat.format(calendarObject.getTime()); + if (!isLogEmpty) { + clearLog(); + } + try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Drifty_CLI_LOG.log", true))))) { isLogEmpty = true; - out.write(""); + out.println(dateAndTime + " " + type.toUpperCase() + " - " + msg); } catch (IOException e) { - System.out.println("Failed to clear Log contents !"); - Drifty_CLI.logger.log("ERROR", "Failed to clear Log contents !"); + System.out.println("Failed to create log : " + msg); } } } diff --git a/src/utility/DriftyUtility.java b/src/utility/DriftyUtility.java new file mode 100644 index 000000000..1491a406c --- /dev/null +++ b/src/utility/DriftyUtility.java @@ -0,0 +1,80 @@ +package utility; + +import java.net.URL; + +import static constants.DriftyConstants.*; + +public final class DriftyUtility { + + private DriftyUtility() { + } + + /** + * This method checks whether the link provided is of YouTube or not and returns the resultant boolean value accordingly. + * + * @param url link to the file to be downloaded. + * @return true if the url is of YouTube and false if it is not. + */ + public static boolean isYoutubeLink(String url) { + String pattern = "^(http(s)?:\\/\\/)?((w){3}.)?youtu(be|.be)?(\\.com)?\\/.+"; + return url.matches(pattern); + } + + /** + * @param link Link to the file that the user wants to download + * @return true if link is valid and false if link is invalid + */ + public static boolean isURLValid(String link) { + try { + new URL(link).toURI(); + return true; + } catch (Exception e) { + return false; + } + } + + public static void help() { + System.out.println(ANSI_RESET + "\n\033[38;31;48;40;1m----==| DRIFTY CLI HELP |==----" + ANSI_RESET); + System.out.println("\033[38;31;48;40;0m v1.2.2" + ANSI_RESET); + System.out.println("For more information visit: https://github.com/SaptarshiSarkar12/Drifty/"); + System.out.println("\033[31;1mRequired parameter: File URL" + ANSI_RESET + " \033[3m(This must be the first argument you are passing)" + ANSI_RESET); + System.out.println("\033[33;1mOptional parameters:"); + System.out.println("\033[97;1mName ShortForm Default Description" + ANSI_RESET); + System.out.println("-location -l Downloads The location on your computer where content downloaded from Drifty are placed."); + System.out.println("-name -n Source Renames file."); + System.out.println("-help -h N/A Provides concise information for Drifty CLI.\n"); + System.out.println("-version -v Current Version Number Displays version number of Drifty."); + System.out.println("\033[97;1mExample:" + ANSI_RESET + " \n> \033[37;1mjava Drifty_CLI https://example.com/object.png -n obj.png -l C:/Users/example" + ANSI_RESET); + System.out.println("\033[37;3m* Requires java 18 or higher. \n" + ANSI_RESET); + } + + /** + * This function prints the banner of the application in the console. + */ + public static void printBanner() { + System.out.print("\033[H\033[2J"); + System.out.println(ANSI_PURPLE + BANNER_BORDER + ANSI_RESET); + System.out.println(ANSI_CYAN + " _____ _____ _____ ______ _______ __ __" + ANSI_RESET); + System.out.println(ANSI_CYAN + " | __ \\ | __ \\ |_ _|| ____||__ __|\\ \\ / /" + ANSI_RESET); + System.out.println(ANSI_CYAN + " | | | || |__) | | | | |__ | | \\ \\_/ /" + ANSI_RESET); + System.out.println(ANSI_CYAN + " | | | || _ / | | | __| | | \\ / " + ANSI_RESET); + System.out.println(ANSI_CYAN + " | |__| || | \\ \\ _| |_ | | | | | | " + ANSI_RESET); + System.out.println(ANSI_CYAN + " |_____/ |_| \\_\\|_____||_| |_| |_| " + ANSI_RESET); + System.out.println(ANSI_PURPLE + BANNER_BORDER + ANSI_RESET); + } + + /** + * This method prints the banner without any colour of text except white. + */ + public static void initialPrintBanner() { + System.out.println(BANNER_BORDER); + System.out.println(" _____ _____ _____ ______ _______ __ __"); + System.out.println(" | __ \\ | __ \\ |_ _|| ____||__ __|\\ \\ / /"); + System.out.println(" | | | || |__) | | | | |__ | | \\ \\_/ /"); + System.out.println(" | | | || _ / | | | __| | | \\ / "); + System.out.println(" | |__| || | \\ \\ _| |_ | | | | | | "); + System.out.println(" |_____/ |_| \\_\\|_____||_| |_| |_| "); + System.out.println(BANNER_BORDER); + } + +} diff --git a/src/validation/DriftyValidation.java b/src/validation/DriftyValidation.java new file mode 100644 index 000000000..179cf5069 --- /dev/null +++ b/src/validation/DriftyValidation.java @@ -0,0 +1,47 @@ +package validation; + + +import singleton.CreateLogs; + +import java.util.Scanner; + + +public final class DriftyValidation { + + public static final CreateLogs logger = new CreateLogs("Drift_CLI_LOG.log"); + private static Scanner SC = new Scanner(System.in); + + /** + * This method performs Yes-No validation and returns the boolean value accordingly. + * + * @param input Input String to validate. + * @param printMessage The message to print to re-input the confirmation. + * @return true if the user enters Y [Yes] and false if not. + */ + public static boolean yesNoValidation(String input, String printMessage) { + + while (true) { + if (input.length() == 0) { + System.out.println("Please enter Y for yes and N for no!"); + logger.log("ERROR", "Please enter Y for yes and N for no!"); + } else { + break; + } + System.out.print(printMessage); + input = SC.nextLine().toLowerCase(); + } + char choice = input.charAt(0); + if (choice == 'y') { + return true; + } else if (choice == 'n') { + return false; + } else { + System.out.println("Invalid input!"); + logger.log("ERROR", "Invalid input"); + System.out.print(printMessage); + input = SC.nextLine().toLowerCase(); + yesNoValidation(input, printMessage); + } + return false; + } +} From 00b2352addebcdb92a0cecd38296e5245167b952 Mon Sep 17 00:00:00 2001 From: bharathkalyans Date: Sun, 1 Jan 2023 14:03:00 +0530 Subject: [PATCH 2/9] Made CreateLogs a singleton class --- src/DownloaderThread.java | 14 ++++---- src/Drifty_CLI.java | 27 +++++++------- src/FileDownloader.java | 4 +-- src/ProgressBarThread.java | 53 +++++++++++++++------------- src/constants/DriftyConstants.java | 11 +++++- src/singleton/CreateLogs.java | 30 +++++++++------- src/singleton/ScannerFactory.java | 16 +++++++++ src/validation/DriftyValidation.java | 5 +-- 8 files changed, 98 insertions(+), 62 deletions(-) create mode 100644 src/singleton/ScannerFactory.java diff --git a/src/DownloaderThread.java b/src/DownloaderThread.java index c0006457a..3ed7ac646 100644 --- a/src/DownloaderThread.java +++ b/src/DownloaderThread.java @@ -5,15 +5,15 @@ import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; -public class DownloaderThread extends Thread{ +public class DownloaderThread extends Thread { - private URL url; - private FileOutputStream file; - private long start; - private long end; + private final URL url; + private final long start; + private final long end; + private final FileOutputStream file; public DownloaderThread(URL url, FileOutputStream file, long start, long end) { - this.url=url; + this.url = url; this.file = file; this.start = start; this.end = end; @@ -24,7 +24,7 @@ public void run() { ReadableByteChannel readableByteChannel; try { URLConnection con = url.openConnection(); - con.setRequestProperty("Range", "bytes="+start+"-"+end); + con.setRequestProperty("Range", "bytes=" + start + "-" + end); con.connect(); readableByteChannel = Channels.newChannel(con.getInputStream()); file.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE); diff --git a/src/Drifty_CLI.java b/src/Drifty_CLI.java index 1c3a932c7..6ff41e476 100644 --- a/src/Drifty_CLI.java +++ b/src/Drifty_CLI.java @@ -1,4 +1,5 @@ import singleton.CreateLogs; +import singleton.ScannerFactory; import utility.DriftyUtility; import validation.DriftyValidation; @@ -15,9 +16,9 @@ * @version 1.2.2 */ public class Drifty_CLI { - public static final CreateLogs logger = new CreateLogs("Drift_CLI_LOG.log"); - public static final String VERSION_NUMBER = "v1.2.2"; - protected static final Scanner SC = new Scanner(System.in); + public static final CreateLogs logger = CreateLogs.getInstance(); + + protected static final Scanner SCANNER = ScannerFactory.getInstance(); protected static boolean isYoutubeURL; private static String downloadsFolder; private static String fileName = null; @@ -56,14 +57,14 @@ public static void main(String[] args) { fileName = (name == null) ? fileName : name; if ((fileName == null || !containsFilename(URL)) && (!isYoutubeURL)) { System.out.print(FILE_NAME_WITH_EXTENSION); - fileName = SC.nextLine(); + fileName = SCANNER.nextLine(); } downloadsFolder = location; if (downloadsFolder == null) { saveToDefault(); } else { if (System.getProperty(OS_NAME).contains(WINDOWS_OS_NAME)) { - downloadsFolder = SC.nextLine().replace('/', '\\'); + downloadsFolder = SCANNER.nextLine().replace('/', '\\'); if (!(downloadsFolder.endsWith("\\"))) { downloadsFolder = downloadsFolder + System.getProperty("file.separator"); } @@ -77,7 +78,7 @@ public static void main(String[] args) { String link; while (true) { System.out.print(FILE_LINK); - link = SC.nextLine(); + link = SCANNER.nextLine(); isYoutubeURL = DriftyUtility.isYoutubeLink(link); if (isYoutubeURL) { break; @@ -93,7 +94,7 @@ public static void main(String[] args) { } } System.out.print(DOWNLOAD_DEFAULT_LOCATION); - String defaultFolder = SC.nextLine().toLowerCase(); + String defaultFolder = SCANNER.nextLine().toLowerCase(); boolean yesOrNo = DriftyValidation.yesNoValidation(defaultFolder, DOWNLOAD_DEFAULT_LOCATION); if (yesOrNo) { saveToDefault(); @@ -103,20 +104,20 @@ public static void main(String[] args) { if (!isYoutubeURL) { if (fileName != null) { System.out.print(RENAME_FILE); - String renameFile = SC.nextLine().toLowerCase(); + String renameFile = SCANNER.nextLine().toLowerCase(); yesOrNo = DriftyValidation.yesNoValidation(renameFile, RENAME_FILE); if (yesOrNo) { System.out.print(FILE_NAME_WITH_EXTENSION); - fileName = SC.nextLine(); + fileName = SCANNER.nextLine(); } } else { System.out.print(FILE_NAME_WITH_EXTENSION); - fileName = SC.nextLine(); + fileName = SCANNER.nextLine(); } } new FileDownloader(link, fileName, downloadsFolder).run(); System.out.println(QUIT_OR_CONTINUE); - String quit = SC.nextLine().toLowerCase(); + String quit = SCANNER.nextLine().toLowerCase(); if (quit.equals("q")) { logger.log(LOGGER_INFO, APPLICATION_TERMINATED); break; @@ -130,9 +131,9 @@ public static void main(String[] args) { */ private static void enterDownloadsFolder() { System.out.print(DIRECTORY_TO_DOWNLOAD_FILE); - downloadsFolder = SC.nextLine(); + downloadsFolder = SCANNER.nextLine(); if (System.getProperty(OS_NAME).contains(WINDOWS_OS_NAME)) { - downloadsFolder = SC.nextLine().replace('/', '\\'); + downloadsFolder = SCANNER.nextLine().replace('/', '\\'); if (!(downloadsFolder.endsWith("\\"))) { downloadsFolder = downloadsFolder + System.getProperty("file.separator"); } diff --git a/src/FileDownloader.java b/src/FileDownloader.java index 960458d98..cbdb16aa3 100644 --- a/src/FileDownloader.java +++ b/src/FileDownloader.java @@ -150,11 +150,11 @@ private static void downloadFromYouTube(String dirOfYt_dlp) throws InterruptedEx return; } System.out.print("Would you like to rename this file? (Enter Y for yes and N for no) : "); - String renameFile = Drifty_CLI.SC.nextLine().toLowerCase(); + String renameFile = Drifty_CLI.SCANNER.nextLine().toLowerCase(); boolean yesOrNo = DriftyValidation.yesNoValidation(renameFile, "Would you like to rename this file? (Enter Y for yes and N for no) : "); if (yesOrNo) { System.out.print("Enter the filename (with file extension) : "); - fName = Drifty_CLI.SC.nextLine(); + fName = Drifty_CLI.SCANNER.nextLine(); } System.out.println("Trying to download the file ..."); Drifty_CLI.logger.log("INFO", "Trying to download the file ..."); diff --git a/src/ProgressBarThread.java b/src/ProgressBarThread.java index 54452d0c6..5a2298519 100644 --- a/src/ProgressBarThread.java +++ b/src/ProgressBarThread.java @@ -3,24 +3,26 @@ import java.util.ArrayList; import java.util.List; +import static constants.DriftyConstants.*; + /** * This is the class responsible for showing the progress bar in the console. */ public class ProgressBarThread extends Thread { private final float charPercent; - private long downloadedBytes; - private List downloadedBytesPerPart; - private boolean downloading; - private long downloadSpeed; - private List downloadSpeeds; private final List partSizes; private final String fileName; private final FileOutputStream fos; - private long totalDownloadBytes; private final int charAmt; private final List charPercents; private final List fileOutputStreams; private final boolean isThreadedDownloading; + private long downloadedBytes; + private List downloadedBytesPerPart; + private boolean downloading; + private long downloadSpeed; + private List downloadSpeeds; + private long totalDownloadBytes; public ProgressBarThread(List fileOutputStreams, List partSizes, String fileName) { this.partSizes = partSizes; @@ -29,7 +31,7 @@ public ProgressBarThread(List fileOutputStreams, List pa charPercent = 0; fos = null; totalDownloadBytes = 0; - charAmt = 80/fileOutputStreams.size(); + charAmt = 80 / fileOutputStreams.size(); isThreadedDownloading = true; downloading = true; charPercents = new ArrayList<>(fileOutputStreams.size()); @@ -69,7 +71,7 @@ public ProgressBarThread(FileOutputStream fos, long totalDownloadBytes, String f public void setDownloading(boolean downloading) { this.downloading = downloading; if (downloading) { - System.out.println("Downloading " + fileName + " ..."); + System.out.println(DOWNLOADING + fileName + " ..."); } } @@ -88,9 +90,9 @@ private String generateProgressBar(String spinner) { bar = bar.substring(0, charAmt / 2 - 2) + String.format("%02d", (int) (downloadedBytes * 100 / totalDownloadBytes)) + "%" + bar.substring(charAmt / 2 + 1); return "[" + spinner + "] " + fileName + " (0KB)[" + bar + "](" + convertBytes(totalDownloadBytes) + ") " + (float) downloadSpeed / 1000000 + " MB/s "; } else { - String result = "[" + spinner + "] "+ convertBytes(totalDownloadBytes) ; + StringBuilder result = new StringBuilder("[" + spinner + "] " + convertBytes(totalDownloadBytes)); float filled; - totalDownloadBytes=0; + totalDownloadBytes = 0; for (int i = 0; i < fileOutputStreams.size(); i++) { filled = downloadedBytesPerPart.get(i) / ((float) charPercents.get(i)); totalDownloadBytes += downloadedBytesPerPart.get(i); @@ -98,9 +100,9 @@ private String generateProgressBar(String spinner) { String b = new String(new char[charAmt - (int) filled]).replace("\0", "."); String bar = a + b; bar = bar.substring(0, charAmt / 2 - 2) + String.format("%02d", (int) (downloadedBytesPerPart.get(i) * 100 / partSizes.get(i))) + "%" + bar.substring(charAmt / 2 + 1); - result += " [" + bar + "] " + String.format("%.2f",(float) downloadSpeeds.get(i) / 1000000) + " MB/s"; + result.append(" [").append(bar).append("] ").append(String.format("%.2f", (float) downloadSpeeds.get(i) / 1000000)).append(" MB/s"); } - return result; + return result.toString(); } } @@ -113,13 +115,13 @@ private String convertBytes(long bytes) { double bytesWithDecimals; if (bytes > 1024) { bytesWithDecimals = bytes / 1024.0; - sizeWithUnit = String.format("%.2f", bytesWithDecimals) + " KB"; + sizeWithUnit = String.format("%.2f", bytesWithDecimals) + " KB"; if (bytesWithDecimals > 1024) { bytesWithDecimals = bytesWithDecimals / 1024; - sizeWithUnit = String.format("%.2f",bytesWithDecimals) + " MB"; + sizeWithUnit = String.format("%.2f", bytesWithDecimals) + " MB"; if (bytesWithDecimals > 1024) { bytesWithDecimals = bytesWithDecimals / 1024; - sizeWithUnit = String.format("%.2f",bytesWithDecimals) + "GB"; + sizeWithUnit = String.format("%.2f", bytesWithDecimals) + "GB"; } } return sizeWithUnit; @@ -133,17 +135,17 @@ private String convertBytes(long bytes) { */ private void cleanup() { System.out.println("\r" + generateProgressBar("/")); - if(isThreadedDownloading){ + if (isThreadedDownloading) { String sizeWithUnit = convertBytes(totalDownloadBytes); - System.out.println("Downloaded " + fileName + " of size " + sizeWithUnit + " at " + FileDownloader.getDir() + fileName + " successfully !"); - Drifty_CLI.logger.log("INFO", "Downloaded " + fileName + " of size " + sizeWithUnit + " at " + FileDownloader.getDir() + fileName + " successfully !"); - }else if (downloadedBytes == totalDownloadBytes) { + System.out.println(DOWNLOADED + fileName + OFF_SIZE + sizeWithUnit + " at " + FileDownloader.getDir() + fileName + SUCCESSFULLY); + Drifty_CLI.logger.log(LOGGER_INFO, DOWNLOADED + fileName + OFF_SIZE + sizeWithUnit + " at " + FileDownloader.getDir() + fileName + SUCCESSFULLY); + } else if (downloadedBytes == totalDownloadBytes) { String sizeWithUnit = convertBytes(downloadedBytes); - System.out.println("Downloaded " + fileName + " of size " + sizeWithUnit + " at " + FileDownloader.getDir() + fileName + " successfully !"); - Drifty_CLI.logger.log("INFO", "Downloaded " + fileName + " of size " + sizeWithUnit + " at " + FileDownloader.getDir() + fileName + " successfully !"); + System.out.println(DOWNLOADED + fileName + OFF_SIZE + sizeWithUnit + " at " + FileDownloader.getDir() + fileName + SUCCESSFULLY); + Drifty_CLI.logger.log(LOGGER_INFO, DOWNLOADED + fileName + OFF_SIZE + sizeWithUnit + " at " + FileDownloader.getDir() + fileName + SUCCESSFULLY); } else { - System.out.println("Download failed!"); - Drifty_CLI.logger.log("ERROR", "Download failed!"); + System.out.println(DOWNLOAD_FAILED); + Drifty_CLI.logger.log(LOGGER_ERROR, DOWNLOAD_FAILED); } } @@ -168,19 +170,20 @@ public void run() { } else { for (int i = 0; i <= 3; i++) { for (int j = 0; j < fileOutputStreams.size(); j++) { - initialMeasurements.add(j,fileOutputStreams.get(j).getChannel().size()); + initialMeasurements.add(j, fileOutputStreams.get(j).getChannel().size()); } Thread.sleep(300); long downloadedPartBytes; for (int j = 0; j < fileOutputStreams.size(); j++) { downloadedPartBytes = fileOutputStreams.get(j).getChannel().size(); - downloadedBytesPerPart.add(j,downloadedPartBytes); + downloadedBytesPerPart.add(j, downloadedPartBytes); downloadSpeeds.add(j, (downloadedPartBytes - initialMeasurements.get(j)) * 4); } System.out.print("\r" + generateProgressBar(spinner[i])); } } } catch (InterruptedException | IOException ignored) { + } } cleanup(); diff --git a/src/constants/DriftyConstants.java b/src/constants/DriftyConstants.java index 6ead0554f..d5cbc71b8 100644 --- a/src/constants/DriftyConstants.java +++ b/src/constants/DriftyConstants.java @@ -2,7 +2,9 @@ public final class DriftyConstants { + public static final String VERSION_NUMBER = "v1.2.2"; public static final String APPLICATION_NAME = "Drifty"; + public static final String DRIFTY_CLI_LOG = "Drift_CLI_LOG.log"; public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_CYAN = "\u001B[36m"; public static final String ANSI_PURPLE = "\u001B[35m"; @@ -35,8 +37,15 @@ public final class DriftyConstants { public static final String FAILED_TO_RETRIEVE_DEFAULT_DOWNLOAD_FOLDER = "Failed to retrieve default download folder!"; public static final String DEFAULT_DOWNLOAD_FOLDER = "Default download folder detected : "; public static final String FILENAME_DETECTED = "Filename detected : "; - public static final String BANNER_BORDER = "===================================================================="; + public static final String FAILED_TO_CREATE_LOG = "Failed to create log : "; + public static final String FAILED_TO_CLEAR_LOG = "Failed to clear Log contents !"; + + public static final String DOWNLOADED = "Downloaded "; + public static final String DOWNLOADING = "Downloading "; + public static final String DOWNLOAD_FAILED = "Download failed!"; + public static final String SUCCESSFULLY = " successfully !"; + public static final String OFF_SIZE = " of size "; private DriftyConstants() { } diff --git a/src/singleton/CreateLogs.java b/src/singleton/CreateLogs.java index 4c6f55507..0ec5fbfd0 100644 --- a/src/singleton/CreateLogs.java +++ b/src/singleton/CreateLogs.java @@ -7,35 +7,41 @@ import java.text.SimpleDateFormat; import java.util.Calendar; +import static constants.DriftyConstants.*; + /** * This class deals with creating Log files for Drifty. */ public class CreateLogs { - static DateFormat dateFormat; - static boolean isLogEmpty; - static Path filePath; - static Calendar calendarObject = Calendar.getInstance(); + private static CreateLogs createLogsInstance; + Path filePath; + DateFormat dateFormat; + boolean isLogEmpty; + Calendar calendarObject = Calendar.getInstance(); /** * This is the constructor used to initialise the variables in this class. - * - * @param logFileName Filename of the Log file. */ - public CreateLogs(String logFileName) { - filePath = FileSystems.getDefault().getPath(logFileName); + private CreateLogs() { + filePath = FileSystems.getDefault().getPath(DRIFTY_CLI_LOG); dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); } + public static CreateLogs getInstance() { + if (createLogsInstance != null) return createLogsInstance; + createLogsInstance = new CreateLogs(); + return createLogsInstance; + } + /** * This function clears the contents of the previous log file. */ - private static void clearLog() { + private void clearLog() { try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Drifty_CLI_LOG.log", false))))) { isLogEmpty = true; out.write(""); } catch (IOException e) { - System.out.println("Failed to clear Log contents !"); -// Drifty_CLI.logger.log("ERROR", "Failed to clear Log contents !"); + System.out.println(FAILED_TO_CLEAR_LOG); } } @@ -54,7 +60,7 @@ public void log(String type, String msg) { isLogEmpty = true; out.println(dateAndTime + " " + type.toUpperCase() + " - " + msg); } catch (IOException e) { - System.out.println("Failed to create log : " + msg); + System.out.println(FAILED_TO_CREATE_LOG + msg); } } } diff --git a/src/singleton/ScannerFactory.java b/src/singleton/ScannerFactory.java new file mode 100644 index 000000000..895ad05d8 --- /dev/null +++ b/src/singleton/ScannerFactory.java @@ -0,0 +1,16 @@ +package singleton; + +import java.util.Scanner; + +public class ScannerFactory { + private static Scanner scanner; + + private ScannerFactory() { + } + + public static Scanner getInstance() { + if (scanner != null) return scanner; + scanner = new Scanner(System.in); + return scanner; + } +} diff --git a/src/validation/DriftyValidation.java b/src/validation/DriftyValidation.java index 179cf5069..e7e20593f 100644 --- a/src/validation/DriftyValidation.java +++ b/src/validation/DriftyValidation.java @@ -1,14 +1,15 @@ package validation; - import singleton.CreateLogs; +import static constants.DriftyConstants.*; + import java.util.Scanner; public final class DriftyValidation { - public static final CreateLogs logger = new CreateLogs("Drift_CLI_LOG.log"); + public static final CreateLogs logger = CreateLogs.getInstance(); private static Scanner SC = new Scanner(System.in); /** From f39966909ecaa7cd17c588e8d148003df05faaa4 Mon Sep 17 00:00:00 2001 From: bharathkalyans Date: Sun, 1 Jan 2023 14:32:37 +0530 Subject: [PATCH 3/9] Extracted Hard Coded String values in FileDownloader.java and renamed variables to proper naming. --- .idea/inspectionProfiles/Project_Default.xml | 31 +++++++ src/CheckDirectory.java | 12 ++- src/FileDownloader.java | 86 ++++++++++---------- src/constants/DriftyConstants.java | 19 +++++ 4 files changed, 101 insertions(+), 47 deletions(-) diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml index 2490c6527..c043e93a4 100644 --- a/.idea/inspectionProfiles/Project_Default.xml +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -4,5 +4,36 @@ + + + \ No newline at end of file diff --git a/src/CheckDirectory.java b/src/CheckDirectory.java index 35f794437..29caa648b 100644 --- a/src/CheckDirectory.java +++ b/src/CheckDirectory.java @@ -4,25 +4,29 @@ import java.nio.file.Files; import java.nio.file.Path; +import static constants.DriftyConstants.*; + /** * This class checks if a directory exists or not. if it doesn't, the directory is created. */ class CheckDirectory { /** * This constructor creates the directory if it does not exist. + * * @param dir Name of the folder where the user wants to download the file. * @throws IOException when creating the directory fails. */ CheckDirectory(String dir) throws IOException { - if (!(checkIfFolderExists(dir))){ + if (!(checkIfFolderExists(dir))) { Path directory = FileSystems.getDefault().getPath(dir); Files.createDirectory(directory); - Drifty_CLI.logger.log("INFO", "Directory Created"); + Drifty_CLI.logger.log(LOGGER_INFO, DIRECTORY_CREATED); } } /** * This function checks if a folder exists or not. + * * @param folderName Name of the folder where the user wants to download the file. * @return true if the folder exists and false if the folder is missing. */ @@ -34,8 +38,8 @@ private static boolean checkIfFolderExists(String folderName) { found = true; } } catch (Exception e) { - System.out.println("Error while checking for directory !"); - Drifty_CLI.logger.log("ERROR", "Error while checking for directory !"); + System.out.println(ERROR_WHILE_CHECKING_FOR_DIRECTORY); + Drifty_CLI.logger.log(LOGGER_ERROR, ERROR_WHILE_CHECKING_FOR_DIRECTORY); } return found; } diff --git a/src/FileDownloader.java b/src/FileDownloader.java index cbdb16aa3..e56157c2f 100644 --- a/src/FileDownloader.java +++ b/src/FileDownloader.java @@ -8,14 +8,16 @@ import java.util.ArrayList; import java.util.List; +import static constants.DriftyConstants.*; + /** * This class deals with downloading the file. */ class FileDownloader implements Runnable { // default number of threads to download with - private final static int numberOfThreads = 3; + private static final int numberOfThreads = 3; // default threading threshold in bytes 50MB - private final static long threadingThreshold = 1024 * 1024 * 50; + private static final long threadingThreshold = 1024 * 1024 * 50; private static String dir; private static String fileName; private static String link; @@ -100,7 +102,7 @@ private static void downloadFile() { FileOutputStream fos = new FileOutputStream(dir + fileName); ProgressBarThread progressBarThread = new ProgressBarThread(fos, totalSize, fileName); progressBarThread.start(); - Drifty_CLI.logger.log("INFO", "Downloading " + fileName + " ..."); + Drifty_CLI.logger.log(LOGGER_INFO, DOWNLOADING + fileName + " ..."); fos.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE); progressBarThread.setDownloading(false); // keep main thread from closing the IO for short amt. of time so UI thread can finish and output @@ -112,14 +114,14 @@ private static void downloadFile() { } catch (SecurityException e) { System.out.println("Write access to " + dir + fileName + " denied !"); - Drifty_CLI.logger.log("ERROR", "Write access to " + dir + fileName + " denied ! " + e.getMessage()); + Drifty_CLI.logger.log(LOGGER_ERROR, "Write access to " + dir + fileName + " denied ! " + e.getMessage()); } catch (IOException e) { - System.out.println("Failed to download the contents ! "); - Drifty_CLI.logger.log("ERROR", "Failed to download the contents ! " + e.getMessage()); + System.out.println(FAILED_TO_DOWNLOAD_CONTENTS); + Drifty_CLI.logger.log(LOGGER_ERROR, FAILED_TO_DOWNLOAD_CONTENTS + e.getMessage()); } } catch (NullPointerException e) { - System.out.println("Failed to get I/O operations channel to read from the data stream !"); - Drifty_CLI.logger.log("ERROR", "Failed to get I/O operations channel to read from the data stream !" + e.getMessage()); + System.out.println(FAILED_TO_READ_DATA_STREAM); + Drifty_CLI.logger.log(LOGGER_ERROR, FAILED_TO_READ_DATA_STREAM + e.getMessage()); } if (dir.length() == 0) { dir = System.getProperty("user.dir"); @@ -139,7 +141,7 @@ private static void downloadFile() { */ private static void downloadFromYouTube(String dirOfYt_dlp) throws InterruptedException, IOException { String fName = ""; - System.out.println("Trying to auto-detect filename..."); + System.out.println(TRYING_TO_AUTOMATICALLY_DETECT_FILE); ProcessBuilder processBuilder = new ProcessBuilder(dirOfYt_dlp + "yt-dlp", link, "--print", "title"); processBuilder.inheritIO(); System.out.print("Filename : "); @@ -149,15 +151,15 @@ private static void downloadFromYouTube(String dirOfYt_dlp) throws InterruptedEx if (exitValueOfYt_Dlp != 0) { return; } - System.out.print("Would you like to rename this file? (Enter Y for yes and N for no) : "); + System.out.print(RENAME_FILE); String renameFile = Drifty_CLI.SCANNER.nextLine().toLowerCase(); boolean yesOrNo = DriftyValidation.yesNoValidation(renameFile, "Would you like to rename this file? (Enter Y for yes and N for no) : "); if (yesOrNo) { - System.out.print("Enter the filename (with file extension) : "); + System.out.print(FILE_NAME_WITH_EXTENSION); fName = Drifty_CLI.SCANNER.nextLine(); } - System.out.println("Trying to download the file ..."); - Drifty_CLI.logger.log("INFO", "Trying to download the file ..."); + System.out.println(TRYING_TO_DOWNLOAD_FILE); + Drifty_CLI.logger.log(LOGGER_INFO, TRYING_TO_DOWNLOAD_FILE); if (fName.equals("")) { processBuilder = new ProcessBuilder(dirOfYt_dlp + "yt-dlp", "--quiet", "--progress", "-P", dir, link, "-o", "%(title)s.mp4"); } else { @@ -168,11 +170,11 @@ private static void downloadFromYouTube(String dirOfYt_dlp) throws InterruptedEx yt_dlp.waitFor(); exitValueOfYt_Dlp = yt_dlp.exitValue(); if (exitValueOfYt_Dlp == 0) { - System.out.println("Successfully downloaded the file!"); - Drifty_CLI.logger.log("INFO", "Successfully downloaded the file!"); + System.out.println(SUCCESSFULLY_DOWNLOADED_FILE); + Drifty_CLI.logger.log(LOGGER_INFO, SUCCESSFULLY_DOWNLOADED_FILE); } else if (exitValueOfYt_Dlp == 1) { - System.out.println("Failed to download the file!"); - Drifty_CLI.logger.log("INFO", "Failed to download the file!"); + System.out.println(FAILED_TO_DOWNLOAD_FILES); + Drifty_CLI.logger.log(LOGGER_INFO, FAILED_TO_DOWNLOAD_FILES); } } @@ -198,10 +200,8 @@ public static boolean merge(List fileOutputStreams, List downloaderThread = downloaderThreads.get(i); if (fout.getChannel().size() < partSize) { - if (!downloaderThread.isAlive()) - throw new IOException("Error: thread encountered an error"); - } else if (!downloaderThread.isAlive()) - completed++; + if (!downloaderThread.isAlive()) throw new IOException(THREAD_ERROR_ENCOUNTERED); + } else if (!downloaderThread.isAlive()) completed++; } //check if it is merge-able @@ -242,26 +242,26 @@ public void run() { downloadFromYouTube(""); } catch (IOException e) { try { - System.out.println("Getting ready to download the file..."); - Drifty_CLI.logger.log("INFO", "Getting ready to download the file..."); + System.out.println(GETTING_READY_TO_DOWNLOAD_FILE); + Drifty_CLI.logger.log(LOGGER_INFO, GETTING_READY_TO_DOWNLOAD_FILE); copyYt_dlp cy = new copyYt_dlp(); cy.copyToTemp(); try { downloadFromYouTube(copyYt_dlp.tempDir); } catch (InterruptedException ie) { - System.out.println("User interrupted while downloading the file!"); - Drifty_CLI.logger.log("ERROR", "User interrupted while downloading the file! " + ie.getMessage()); + System.out.println(USER_INTERRUPTION); + Drifty_CLI.logger.log(LOGGER_ERROR, USER_INTERRUPTION + ie.getMessage()); } catch (IOException io1) { - System.out.println("Failed to download YouTube video!"); - Drifty_CLI.logger.log("ERROR", "Failed to download YouTube video! " + io1.getMessage()); + System.out.println(FAILED_TO_DOWNLOAD_YOUTUBE_VIDEO); + Drifty_CLI.logger.log(LOGGER_ERROR, FAILED_TO_DOWNLOAD_YOUTUBE_VIDEO + io1.getMessage()); } } catch (IOException io) { - System.out.println("Failed to initialise YouTube video downloader!"); - Drifty_CLI.logger.log("ERROR", "Failed to initialise YouTube video downloader! " + io.getMessage()); + System.out.println(FAILED_TO_INITIALISE_YOUTUBE_VIDEO); + Drifty_CLI.logger.log(LOGGER_ERROR, FAILED_TO_INITIALISE_YOUTUBE_VIDEO + io.getMessage()); } } catch (InterruptedException e) { - System.out.println("User interrupted while downloading the file!"); - Drifty_CLI.logger.log("ERROR", "User interrupted while downloading the file! " + e.getMessage()); + System.out.println(USER_INTERRUPTION); + Drifty_CLI.logger.log(LOGGER_ERROR, USER_INTERRUPTION + e.getMessage()); } } else { url = new URL(link); @@ -282,28 +282,28 @@ public void run() { dir = ""; } } else { - System.out.println("Invalid Directory Entered !"); - Drifty_CLI.logger.log("ERROR", "Invalid Directory Entered !"); + System.out.println(INVALID_DIRECTORY); + Drifty_CLI.logger.log(LOGGER_ERROR, INVALID_DIRECTORY); } try { new CheckDirectory(dir); } catch (IOException e) { - System.out.println("Failed to create the directory : " + dir + " ! " + e.getMessage()); - Drifty_CLI.logger.log("ERROR", "Failed to create the directory : " + dir + " ! " + e.getMessage()); + System.out.println(FAILED_TO_CREATE_DIRECTORY + dir + " ! " + e.getMessage()); + Drifty_CLI.logger.log(LOGGER_ERROR, FAILED_TO_CREATE_DIRECTORY + dir + " ! " + e.getMessage()); } - System.out.println("Trying to download the file..."); - Drifty_CLI.logger.log("INFO", "Trying to download the file..."); + System.out.println(TRYING_TO_DOWNLOAD_FILE); + Drifty_CLI.logger.log(LOGGER_ERROR, TRYING_TO_DOWNLOAD_FILE); downloadFile(); } } catch (MalformedURLException e) { - System.out.println("Invalid Link!"); - Drifty_CLI.logger.log("ERROR", "Invalid Link! " + e.getMessage()); + System.out.println(INVALID_LINK); + Drifty_CLI.logger.log(LOGGER_ERROR, INVALID_LINK + e.getMessage()); } catch (SocketTimeoutException e) { - System.out.println("Timed out while connecting to " + url + " !"); - Drifty_CLI.logger.log("ERROR", "Timed out while connecting to " + url + " ! " + e.getMessage()); + System.out.println(FAILED_TO_CONNECT_TO_URL + url + " !"); + Drifty_CLI.logger.log(LOGGER_ERROR, FAILED_TO_CONNECT_TO_URL + url + " ! " + e.getMessage()); } catch (IOException e) { - System.out.println("Failed to connect to " + url + " !"); - Drifty_CLI.logger.log("ERROR", "Failed to connect to " + url + " ! " + e.getMessage()); + System.out.println(FAILED_TO_CONNECT_TO_URL + url + " !"); + Drifty_CLI.logger.log(LOGGER_ERROR, FAILED_TO_CONNECT_TO_URL + url + " ! " + e.getMessage()); } } } diff --git a/src/constants/DriftyConstants.java b/src/constants/DriftyConstants.java index d5cbc71b8..350df8abe 100644 --- a/src/constants/DriftyConstants.java +++ b/src/constants/DriftyConstants.java @@ -14,9 +14,12 @@ public final class DriftyConstants { public static final String APPLICATION_STARTED = "Application Started !"; public static final String APPLICATION_TERMINATED = "Application Terminated!"; public static final String INVALID_URL = "URL is invalid!"; + public static final String INVALID_LINK = "Invalid Link!"; public static final String INVALID_URL_ENTER_AGAIN = "Invalid URL. Please enter again"; + public static final String INVALID_DIRECTORY = "Invalid Directory Entered !"; public static final String AUTOMATIC_FILE_DETECTION = "Automatic file name detection failed!"; public static final String TRYING_TO_AUTOMATICALLY_DETECT_FILE = "Trying to auto-detect default Downloads folder..."; + public static final String TRYING_TO_DOWNLOAD_FILE = "Trying to download the file ..."; public static final String HELP_FLAG = "-help"; public static final String NAME_FLAG = "-name"; public static final String VERSION_FLAG = "-version"; @@ -35,17 +38,33 @@ public final class DriftyConstants { public static final String QUIT_OR_CONTINUE = "Press Q to Quit Or Press any Key to Continue"; public static final String DIRECTORY_TO_DOWNLOAD_FILE = "Enter the directory in which you want to download the file : "; public static final String FAILED_TO_RETRIEVE_DEFAULT_DOWNLOAD_FOLDER = "Failed to retrieve default download folder!"; + public static final String FAILED_TO_CONNECT_TO_URL = "Failed to connect to "; public static final String DEFAULT_DOWNLOAD_FOLDER = "Default download folder detected : "; public static final String FILENAME_DETECTED = "Filename detected : "; public static final String BANNER_BORDER = "===================================================================="; public static final String FAILED_TO_CREATE_LOG = "Failed to create log : "; public static final String FAILED_TO_CLEAR_LOG = "Failed to clear Log contents !"; + public static final String FAILED_TO_CREATE_DIRECTORY = "Failed to create the directory : "; public static final String DOWNLOADED = "Downloaded "; public static final String DOWNLOADING = "Downloading "; public static final String DOWNLOAD_FAILED = "Download failed!"; public static final String SUCCESSFULLY = " successfully !"; + public static final String SUCCESSFULLY_DOWNLOADED_FILE = "Successfully downloaded the file!"; public static final String OFF_SIZE = " of size "; + public static final String DIRECTORY_CREATED = "Directory Created"; + public static final String ERROR_WHILE_CHECKING_FOR_DIRECTORY = "Error while checking for directory !"; + + public static final String FAILED_TO_DOWNLOAD_FILES = "Failed to download the file!"; + public static final String FAILED_TO_DOWNLOAD_CONTENTS = "Failed to download the contents ! "; + public static final String FAILED_TO_READ_DATA_STREAM = "Failed to get I/O operations channel to read from the data stream !"; + + public static final String FAILED_TO_DOWNLOAD_YOUTUBE_VIDEO = "Failed to download YouTube video!"; + public static final String FAILED_TO_INITIALISE_YOUTUBE_VIDEO = "Failed to initialise YouTube video downloader!"; + public static final String THREAD_ERROR_ENCOUNTERED = "Error: thread encountered an error"; + + public static final String GETTING_READY_TO_DOWNLOAD_FILE = "Getting ready to download the file..."; + public static final String USER_INTERRUPTION = "User interrupted while downloading the file!"; private DriftyConstants() { } From a7681c5bc39570db5174e300c800fceb3c4766c5 Mon Sep 17 00:00:00 2001 From: bharathkalyans Date: Mon, 2 Jan 2023 11:42:25 +0530 Subject: [PATCH 4/9] Resolved the Issues assigned! --- .idea/sonarlint/issuestore/index.pb | 31 ++++++++++++++++++++++++++++ src/Drifty_CLI.java | 4 ++-- src/FileDownloader.java | 4 ++-- src/constants/DriftyConstants.java | 4 +++- src/validation/DriftyValidation.java | 4 ++-- 5 files changed, 40 insertions(+), 7 deletions(-) diff --git a/.idea/sonarlint/issuestore/index.pb b/.idea/sonarlint/issuestore/index.pb index e69de29bb..ee8ced521 100644 --- a/.idea/sonarlint/issuestore/index.pb +++ b/.idea/sonarlint/issuestore/index.pb @@ -0,0 +1,31 @@ + +9 + README.md,8/e/8ec9a00bfd09b3190ac6b22251dbb1aa95a0579d +B +Website/Dockerfile,7/c/7c3898b8b683ab26f301f4653896877e2a5dbc19 +A +Website/style.css,a/5/a553767b752db0898ab95377236160f2a2183e9a +C +Website/thanks.html,6/6/66a8016dee556b2bb557e749366cc8321b388a7c +A +Website/README.md,7/d/7d521d70820c8292be22ed30005d3c1fda202576 +A +Website/script.js,f/4/f473dfb4c9712d68bb288e158641ba5d452a71d3 +M +src/singleton/CreateLogs.java,5/f/5fef46a3d0fcc709d30d5e27a03bda2763dd65f3 +J +src/ProgressBarThread.java,5/e/5ed186658cad4df860bb19ebf2f264078c4169b1 +Q +!src/singleton/ScannerFactory.java,0/9/094d50e568616c63bc7aced69fb8d43001c34dfd +C +src/copyYt_dlp.java,b/6/b64a0907c5ecaa270ac59328330f8e5edce82272 +I +src/DownloaderThread.java,7/4/74f37b08ce7172b57efa75158126bb38a15e8e72 +\ +,.idea/inspectionProfiles/Project_Default.xml,4/9/496a238a6afa168dbaf6efd37bb459331589579c +G +src/CheckDirectory.java,4/0/406740eb482bc2d22e16969b1a7a1cdada625b09 +\ +,src/DefaultDownloadFolderLocationFinder.java,5/f/5fac91aed83b5ac4616bd08013f740603f0c198d +N +src/utility/DriftyUtility.java,9/5/95b1b5c55b5284695b355c0e83deac11f7a2937c \ No newline at end of file diff --git a/src/Drifty_CLI.java b/src/Drifty_CLI.java index 6ff41e476..e77f6376a 100644 --- a/src/Drifty_CLI.java +++ b/src/Drifty_CLI.java @@ -145,8 +145,8 @@ private static void enterDownloadsFolder() { * This function tries to detect the default downloads folder and save the file in that folder */ private static void saveToDefault() { - System.out.println(TRYING_TO_AUTOMATICALLY_DETECT_FILE); - logger.log(LOGGER_ERROR, TRYING_TO_AUTOMATICALLY_DETECT_FILE); + System.out.println(TRYING_TO_AUTO_DETECT_FILE); + logger.log(LOGGER_ERROR, TRYING_TO_AUTO_DETECT_FILE); if (!System.getProperty(OS_NAME).contains(WINDOWS_OS_NAME)) { String home = System.getProperty(USER_HOME_PROPERTY); downloadsFolder = home + DOWNLOADS_FILE_PATH; diff --git a/src/FileDownloader.java b/src/FileDownloader.java index e56157c2f..5257caa43 100644 --- a/src/FileDownloader.java +++ b/src/FileDownloader.java @@ -102,7 +102,7 @@ private static void downloadFile() { FileOutputStream fos = new FileOutputStream(dir + fileName); ProgressBarThread progressBarThread = new ProgressBarThread(fos, totalSize, fileName); progressBarThread.start(); - Drifty_CLI.logger.log(LOGGER_INFO, DOWNLOADING + fileName + " ..."); + Drifty_CLI.logger.log(LOGGER_INFO, "Downloading " + fileName + " ..."); fos.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE); progressBarThread.setDownloading(false); // keep main thread from closing the IO for short amt. of time so UI thread can finish and output @@ -141,7 +141,7 @@ private static void downloadFile() { */ private static void downloadFromYouTube(String dirOfYt_dlp) throws InterruptedException, IOException { String fName = ""; - System.out.println(TRYING_TO_AUTOMATICALLY_DETECT_FILE); + System.out.println(TRYING_TO_AUTO_DETECT_FILE); ProcessBuilder processBuilder = new ProcessBuilder(dirOfYt_dlp + "yt-dlp", link, "--print", "title"); processBuilder.inheritIO(); System.out.print("Filename : "); diff --git a/src/constants/DriftyConstants.java b/src/constants/DriftyConstants.java index 350df8abe..f709a7f61 100644 --- a/src/constants/DriftyConstants.java +++ b/src/constants/DriftyConstants.java @@ -18,7 +18,7 @@ public final class DriftyConstants { public static final String INVALID_URL_ENTER_AGAIN = "Invalid URL. Please enter again"; public static final String INVALID_DIRECTORY = "Invalid Directory Entered !"; public static final String AUTOMATIC_FILE_DETECTION = "Automatic file name detection failed!"; - public static final String TRYING_TO_AUTOMATICALLY_DETECT_FILE = "Trying to auto-detect default Downloads folder..."; + public static final String TRYING_TO_AUTO_DETECT_FILE = "Trying to auto-detect default Downloads folder..."; public static final String TRYING_TO_DOWNLOAD_FILE = "Trying to download the file ..."; public static final String HELP_FLAG = "-help"; public static final String NAME_FLAG = "-name"; @@ -66,6 +66,8 @@ public final class DriftyConstants { public static final String GETTING_READY_TO_DOWNLOAD_FILE = "Getting ready to download the file..."; public static final String USER_INTERRUPTION = "User interrupted while downloading the file!"; + public static final String ENTER_Y_OR_N = "Please enter Y for yes and N for no!"; + private DriftyConstants() { } diff --git a/src/validation/DriftyValidation.java b/src/validation/DriftyValidation.java index e7e20593f..6aa5d88e0 100644 --- a/src/validation/DriftyValidation.java +++ b/src/validation/DriftyValidation.java @@ -23,8 +23,8 @@ public static boolean yesNoValidation(String input, String printMessage) { while (true) { if (input.length() == 0) { - System.out.println("Please enter Y for yes and N for no!"); - logger.log("ERROR", "Please enter Y for yes and N for no!"); + System.out.println(ENTER_Y_OR_N); + logger.log(LOGGER_ERROR, ENTER_Y_OR_N); } else { break; } From 7edc95fd31d459e7312a2f231050bf4c2c87a933 Mon Sep 17 00:00:00 2001 From: Bharath Kalyan S Date: Tue, 3 Jan 2023 20:02:05 +0530 Subject: [PATCH 5/9] Update src/CheckDirectory.java Co-authored-by: Saptarshi Sarkar --- src/CheckDirectory.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/CheckDirectory.java b/src/CheckDirectory.java index 29caa648b..d800f5144 100644 --- a/src/CheckDirectory.java +++ b/src/CheckDirectory.java @@ -26,7 +26,6 @@ class CheckDirectory { /** * This function checks if a folder exists or not. - * * @param folderName Name of the folder where the user wants to download the file. * @return true if the folder exists and false if the folder is missing. */ From c251cf03b018baf9f58363ce6ad909c196256317 Mon Sep 17 00:00:00 2001 From: Bharath Kalyan S Date: Tue, 3 Jan 2023 20:02:13 +0530 Subject: [PATCH 6/9] Update src/Drifty_CLI.java Co-authored-by: Saptarshi Sarkar --- src/Drifty_CLI.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Drifty_CLI.java b/src/Drifty_CLI.java index e77f6376a..66a251c0e 100644 --- a/src/Drifty_CLI.java +++ b/src/Drifty_CLI.java @@ -25,7 +25,6 @@ public class Drifty_CLI { /** * This function is the main method of the whole application. - * * @param args Command Line Arguments as a String array. */ public static void main(String[] args) { From 8f34af0178e33eaddc21af02e62fd01c28ebe744 Mon Sep 17 00:00:00 2001 From: Bharath Kalyan S Date: Tue, 3 Jan 2023 20:02:21 +0530 Subject: [PATCH 7/9] Update src/CheckDirectory.java Co-authored-by: Saptarshi Sarkar --- src/CheckDirectory.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/CheckDirectory.java b/src/CheckDirectory.java index d800f5144..32ee7cbc9 100644 --- a/src/CheckDirectory.java +++ b/src/CheckDirectory.java @@ -12,7 +12,6 @@ class CheckDirectory { /** * This constructor creates the directory if it does not exist. - * * @param dir Name of the folder where the user wants to download the file. * @throws IOException when creating the directory fails. */ From fbd2884490f9d7ebbebbfcb8c3a705cce599f658 Mon Sep 17 00:00:00 2001 From: Bharath Kalyan S Date: Tue, 3 Jan 2023 20:02:36 +0530 Subject: [PATCH 8/9] Update src/Drifty_CLI.java Co-authored-by: Saptarshi Sarkar --- src/Drifty_CLI.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Drifty_CLI.java b/src/Drifty_CLI.java index 66a251c0e..36cfb1119 100644 --- a/src/Drifty_CLI.java +++ b/src/Drifty_CLI.java @@ -11,7 +11,6 @@ /** * This is the main class for the CLI version of Drifty. - * * @author Saptarshi Sarkar, Akshat Jain, Anurag Bharati, Naachiket Pant, Fonta22 * @version 1.2.2 */ From a75759b66674ac507e8cf8e75c470652f47f4192 Mon Sep 17 00:00:00 2001 From: Bharath Kalyan S Date: Tue, 3 Jan 2023 20:03:20 +0530 Subject: [PATCH 9/9] Updated src/Drifty_CLI.java Co-authored-by: Saptarshi Sarkar --- src/Drifty_CLI.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Drifty_CLI.java b/src/Drifty_CLI.java index 36cfb1119..aee92f270 100644 --- a/src/Drifty_CLI.java +++ b/src/Drifty_CLI.java @@ -16,7 +16,6 @@ */ public class Drifty_CLI { public static final CreateLogs logger = CreateLogs.getInstance(); - protected static final Scanner SCANNER = ScannerFactory.getInstance(); protected static boolean isYoutubeURL; private static String downloadsFolder;