Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: wrong YouTube playlist detection #630

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

Tarunkumarkanakam
Copy link

@Tarunkumarkanakam Tarunkumarkanakam commented Sep 9, 2024

Fixes issue

Fixes #601

Changes proposed

  • Standardized the YouTube link format for both youtu.be and youtube.com domains.
  • Extracted and converted youtu.be URLs to the youtube.com/watch?v={videoID} format.
  • Improved error handling for invalid or malformed YouTube playlist links.
  • Added queryParams extraction method to help future development in playlist download feature.

Check List (Check all the applicable boxes)

  • My code follows the code style of this project.
  • My change requires changes to the documentation.
  • I have updated the documentation accordingly.
  • This PR does not contain plagiarized content.
  • The title of my pull request is a short description of the requested changes.

Screenshots

Screenshot 2024-09-09 at 10 29 26 AM

Note to reviewers

This PR ensures that YouTube links with different domain structures (youtu.be and youtube.com) are correctly standardized and handled. It also includes enhanced error handling for cases where the video ID is missing (playlist URLs) or the URL is malformed.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced CLI to support automatic formatting of YouTube links, improving user experience with video URL handling.
    • Introduced a new method for extracting query parameters from URLs, allowing users to easily retrieve specific data from links.
    • Added improved URL normalization to ensure consistent handling of links.
  • Bug Fixes

    • Improved error handling for URL processing, providing users with clearer feedback when issues arise.

Copy link

vercel bot commented Sep 9, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
drifty ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 30, 2024 6:17am

Copy link
Contributor

coderabbitai bot commented Sep 9, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces enhancements to the Drifty_CLI class for improved handling of YouTube links, including better error management and URL normalization. A new method, formatYoutubeLink, is added to the Utility class to validate and reformat YouTube URLs. The changes aim to prevent the application from crashing due to invalid links and enhance the overall URL processing capabilities.

Changes

File Change Summary
CLI/src/main/java/main/Drifty_CLI.java Enhanced YouTube link processing with error handling and added normalizeUrl method for URL normalization.
Core/src/main/java/utils/Utility.java Introduced formatYoutubeLink and extractQueryParams methods for better URL handling and query parameter extraction.

Assessment against linked issues

Objective Addressed Explanation
Drifty must recognize that the URL is of a YouTube video and not of any playlists. (601)
Implement functionality to parse the playlist and download all videos in the playlist. (631) No functionality for playlist handling was added.

Possibly related issues

Poem

🐰 In the meadow of code, where the bunnies reside,
YouTube links now flourish, with joy as our guide!
Error messages vanish, like shadows at dawn,
With each little tweak, our CLI moves on.
Hopping through URLs, so tidy and neat,
A brighter tomorrow, with every heartbeat! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the App 💻 Issues/Pull Requests which update Drifty Application Code label Sep 9, 2024
Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah! You did it 🎉 Now, Relax 😉, Grab a drink ☕, and wait for the maintainers to check your contributions. Meanwhile, you can discuss on other issues and solve them 😀. Thank You 😃!

Meanwhile you can also discuss about the project in our Discord Server 😀

Copy link
Contributor

github-actions bot commented Sep 9, 2024

❌ Linting errors found!

@Tarunkumarkanakam Please fix the following errors:

CLI/src/main/java/main/Drifty_CLI.java:309:29: '}' at column 29 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally). [RightCurly]
Core/src/main/java/utils/Utility.java:917:9: 'if' construct must use '{}'s. [NeedBraces]
CLI/src/main/java/main/Drifty_CLI.java:296:21: '}' at column 21 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally). [RightCurly]

Generated from this workflow run (ID: 10766866379)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5600fa0 and 17a956c.

Files selected for processing (2)
  • CLI/src/main/java/main/Drifty_CLI.java (1 hunks)
  • Core/src/main/java/utils/Utility.java (1 hunks)
Additional comments not posted (1)
Core/src/main/java/utils/Utility.java (1)

909-924: Approve the implementation of contains.

The contains method is implemented correctly and efficiently checks for the presence of a value in an array. It handles null arrays gracefully by returning false immediately, which is a good defensive programming practice.

Comment on lines 297 to 334
else if (isYoutube(link)) {
String videoId = null;
try {
URI uri = URI.create(link);
String domain = uri.getHost();

// checking if the domain is youtu.be
if ("youtu.be".equals(domain)) {
String path = uri.getPath();
if (path != null && path.length() > 1) {
videoId = path.substring(1); // removing the leading "/"
}
}
// checking if the domain is youtube.com
else if ("www.youtube.com".equals(domain) || "youtube.com".equals(domain)) {
Map<String, String> queryParams = extractQueryParams(link, "v");
videoId = queryParams.get("v");
}

if (videoId != null) {
// constructing link in youtube.com/watch?v={videoID}
uri = new URI("https", "www.youtube.com", "/watch", "v=" + videoId, null);
link = uri.toString();
} else {
messageBroker.msgLinkError("YouTube video ID not found in the link.");
messageBroker.msgInputInfo(QUIT_OR_CONTINUE, true);
String choice = SC.next().toLowerCase().strip();
if ("q".equals(choice)) {
LOGGER.log(MessageType.INFO, CLI_APPLICATION_TERMINATED);
break;
}
printBanner();
continue;
}

} catch (IllegalArgumentException | URISyntaxException e) {
messageBroker.msgLinkError("Failed to process the YouTube link: " + e.getMessage());
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor YouTube link handling for clarity and robustness.

The handling of YouTube links in the Drifty_CLI class is functional but could be improved for better clarity and error handling:

  1. Domain Checking: The method uses string comparisons for domain checking, which could be refactored into a more robust method using URL parsing.
  2. Error Handling: The method could provide more specific error messages related to URI creation and parsing issues.

Consider refactoring the code to improve readability and error handling:

-                            if ("youtu.be".equals(domain)) {
+                            if (domain.endsWith("youtu.be")) { // More flexible domain checking

-                            } else if ("www.youtube.com".equals(domain) || "youtube.com".equals(domain)) {
+                            } else if (domain.endsWith("youtube.com")) {

-                            uri = new URI("https", "www.youtube.com", "/watch", "v=" + videoId, null);
+                            try {
+                                uri = new URI("https", "www.youtube.com", "/watch", "v=" + videoId, null);
+                                link = uri.toString();
+                            } catch (URISyntaxException e) {
+                                messageBroker.msgLinkError("Failed to construct YouTube watch URL: " + e.getMessage());
+                                continue; // Skip further processing and allow user to correct input
+                            }

Committable suggestion was skipped due to low confidence.

@SaptarshiSarkar12 SaptarshiSarkar12 changed the title Fix/601 youtube playlist detection cli bug fix Fix: wrong YouTube playlist detection Sep 9, 2024
@SaptarshiSarkar12
Copy link
Owner

@Tarunkumarkanakam After PR #632 has been merged, the code has been refactored a lot to centralize the process of fetching the required data for downloading any type of file, via the DownloadConfiguration class. For this issue, you now need to make changes only in the sanitizeLink() method 👇

public void sanitizeLink() {
link = link.trim();
link = link.replace('\\', '/');
link = link.replaceFirst("^(?!https?:)", "https://");
if (link.startsWith("https://github.com/") || (link.startsWith("http://github.com/"))) {
if (!link.endsWith("?raw=true")) {
link = link + "?raw=true";
}
}
if (this.linkType.equals(LinkType.INSTAGRAM)) {
this.link = Utility.formatInstagramLink(link);
}
}

Please pull the latest changes at first before starting the modification. If you face any issue or have any suggestion, please let me know.

Copy link
Contributor

❌ Linting errors found!

@Tarunkumarkanakam Please fix the following errors:

Core/src/main/java/utils/Utility.java:872:9: '}' at column 9 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally). [RightCurly]
Core/src/main/java/utils/Utility.java:942:9: 'if' construct must use '{}'s. [NeedBraces]
CLI/src/main/java/main/Drifty_CLI.java:297:21: '}' at column 21 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally). [RightCurly]

Generated from this workflow run (ID: 11100480958)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (3)
Core/src/main/java/utils/Utility.java (1)

862-887: LGTM! Consider a minor readability improvement.

The formatYoutubeLink method effectively handles different YouTube URL formats and standardizes them. It correctly extracts the video ID from both youtu.be and youtube.com URLs.

Consider extracting the domain check into a separate method for improved readability:

 public static String formatYoutubeLink(String link) throws MalformedURLException, URISyntaxException {
     String videoId = null;
     URI uri = URI.create(link);
-    String domain = uri.getHost();
+    videoId = extractVideoId(uri);
-    if ("youtu.be".equals(domain)) {
-        String path = uri.getPath();
-        if (path != null && path.length() > 1) {
-            videoId = path.substring(1); // removing the leading "/"
-        }
-    }
-    else if ("www.youtube.com".equals(domain) || "youtube.com".equals(domain)) {
-        Map<String, String> queryParams = extractQueryParams(link, "v");
-        videoId = queryParams.get("v");
-    }

     if (videoId != null) {
         uri = new URI("https", "www.youtube.com", "/watch", "v=" + videoId, null);
         link = uri.toString();
     } else {
         throw new MalformedURLException(link + " is not a valid youtube link!");
     }

     return link;
 }

+private static String extractVideoId(URI uri) {
+    String domain = uri.getHost();
+    if ("youtu.be".equals(domain)) {
+        String path = uri.getPath();
+        if (path != null && path.length() > 1) {
+            return path.substring(1); // removing the leading "/"
+        }
+    }
+    else if ("www.youtube.com".equals(domain) || "youtube.com".equals(domain)) {
+        Map<String, String> queryParams = extractQueryParams(uri.toString(), "v");
+        return queryParams.get("v");
+    }
+    return null;
+}

This change would make the main method more concise and easier to understand at a glance.

CLI/src/main/java/main/Drifty_CLI.java (2)

298-312: LGTM: Improved YouTube link processing with robust error handling.

This new code block effectively addresses the PR objective of enhancing YouTube link handling. It includes:

  1. Proper formatting of YouTube links using the formatYoutubeLink method.
  2. Comprehensive error handling for various exceptions.
  3. User-friendly interaction allowing continuation or quitting upon errors.

These changes align well with the requirements from issue #601 and improve the overall robustness of the application.

Consider enhancing the error message slightly for more clarity:

-            messageBroker.msgLinkError("Failed to process the YouTube link: " + e.getMessage());
+            messageBroker.msgLinkError("Failed to process the YouTube link. Error: " + e.getMessage());

This minor change makes the error message more explicit about the nature of the failure.


Line range hint 679-684: LGTM: Robust URL normalization method added.

The new normalizeUrl method is a valuable addition that enhances URL handling in the application. Key benefits include:

  1. Normalizing the URL scheme to lowercase for consistency.
  2. Decoding the URL path, improving handling of encoded URLs.
  3. Removing trailing slashes (except for root "/"), adhering to common URL normalization practices.
  4. Comprehensive error handling for various exception types.

This method contributes significantly to the PR's objective of standardizing and improving URL processing.

Consider adding a null check at the beginning of the method for robustness:

 private static String normalizeUrl(String urlString) {
+    if (urlString == null) {
+        return null;
+    }
     try {
         URI uri = new URI(urlString.trim());
         // ... rest of the method
     }
     // ... exception handling
 }

This addition would prevent potential NullPointerExceptions if the method is called with a null argument.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 17a956c and 609b852.

📒 Files selected for processing (2)
  • CLI/src/main/java/main/Drifty_CLI.java (2 hunks)
  • Core/src/main/java/utils/Utility.java (3 hunks)
🔇 Additional comments (2)
Core/src/main/java/utils/Utility.java (1)

862-949: Overall improvements in YouTube link handling and query parameter extraction.

The changes introduced in this file significantly enhance the functionality for handling YouTube links and extracting query parameters. The new methods formatYoutubeLink, extractQueryParams, and contains work together to provide a robust solution for standardizing YouTube URLs and parsing their parameters.

Key improvements:

  1. Standardization of YouTube links to a consistent format.
  2. Flexible query parameter extraction with the ability to filter specific parameters.
  3. Better error handling for malformed URLs.

While the implementation is generally good, the suggested refactorings in the previous comments will further improve readability, efficiency, and robustness of the code.

These changes align well with the PR objectives of improving YouTube playlist detection and enhancing the overall URL processing capabilities of the application.

CLI/src/main/java/main/Drifty_CLI.java (1)

24-24: LGTM: New import for improved error handling.

The addition of java.net.MalformedURLException import is appropriate for handling potential URL-related errors, which aligns with the PR's objective of improving YouTube link processing.

Comment on lines +934 to +949
/**
* Helper method to check if an array contains a specific value.
*
* @param array The array to check.
* @param value The value to search for.
* @return True if the array contains the value, false otherwise.
*/
private static boolean contains(String[] array, String value) {
if (array == null) return false;
for (String item : array) {
if (item.equals(value)) {
return true;
}
}
return false;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider using Java's built-in method for array contains check.

The contains method is correctly implemented, but we can improve its efficiency by using Java's built-in methods.

Consider replacing the method with this more concise and potentially more efficient version:

-private static boolean contains(String[] array, String value) {
-    if (array == null) return false;
-    for (String item : array) {
-        if (item.equals(value)) {
-            return true;
-        }
-    }
-    return false;
-}
+private static boolean contains(String[] array, String value) {
+    return array != null && Arrays.asList(array).contains(value);
+}

This change utilizes Java's Arrays.asList(array).contains(value) method, which may be more efficient, especially for larger arrays. It also maintains the null check for the input array.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* Helper method to check if an array contains a specific value.
*
* @param array The array to check.
* @param value The value to search for.
* @return True if the array contains the value, false otherwise.
*/
private static boolean contains(String[] array, String value) {
if (array == null) return false;
for (String item : array) {
if (item.equals(value)) {
return true;
}
}
return false;
}
/**
* Helper method to check if an array contains a specific value.
*
* @param array The array to check.
* @param value The value to search for.
* @return True if the array contains the value, false otherwise.
*/
private static boolean contains(String[] array, String value) {
return array != null && Arrays.asList(array).contains(value);
}

Comment on lines +889 to +932
/**
* Extracts the specified query parameters from the given URL. If no parameter names are provided (null or empty), all parameters are returned.
*
* @param urlLink The URL string from which to extract parameters.
* @param paramNames The names of the query parameters to extract. If null or empty, all parameters will be returned.
* @return A map containing the query parameter names and their corresponding values.
*/
public static Map<String, String> extractQueryParams(String urlLink, String... paramNames) {
Map<String, String> paramMap = new HashMap<>();

URL url = null;
try {
url = URI.create(urlLink).toURL();
} catch (MalformedURLException e) {
msgBroker.msgLinkError("Connection to the link timed out! Please check your internet connection. " + e.getMessage());
}
String query = url != null ? url.getQuery() : null;

// query is null or empty, return an empty map (no query parameters)
if (query == null || query.isEmpty()) {
return paramMap;
}

// splitting query string into individual parameters
String[] params = query.split("&");

// check if specific parameters are requested or if all should be returned
boolean returnAllParams = (paramNames == null || paramNames.length == 0);

for (String param : params) {
String[] pair = param.split("=");
if (pair.length == 2) {
String paramName = pair[0];
String paramValue = pair[1];

// add parameter to the map if it's requested or if all parameters should be returned
if (returnAllParams || contains(paramNames, paramName)) {
paramMap.put(paramName, paramValue);
}
}
}

return paramMap;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve error handling and efficiency in extractQueryParams.

The method correctly extracts query parameters, but there are opportunities for improvement:

  1. Error handling can be enhanced by returning early if the URL is malformed.
  2. The method can be more efficient by avoiding unnecessary null checks after URL creation.
  3. Handling of parameters without values can be improved.

Consider applying these changes:

 public static Map<String, String> extractQueryParams(String urlLink, String... paramNames) {
     Map<String, String> paramMap = new HashMap<>();

-    URL url = null;
     try {
-        url = URI.create(urlLink).toURL();
+        URL url = URI.create(urlLink).toURL();
+        String query = url.getQuery();
+
+        if (query == null || query.isEmpty()) {
+            return paramMap;
+        }
+
+        String[] params = query.split("&");
+        boolean returnAllParams = (paramNames == null || paramNames.length == 0);
+
+        for (String param : params) {
+            String[] pair = param.split("=", 2);
+            String paramName = pair[0];
+            String paramValue = pair.length > 1 ? pair[1] : "";
+
+            if (returnAllParams || contains(paramNames, paramName)) {
+                paramMap.put(paramName, paramValue);
+            }
+        }
     } catch (MalformedURLException e) {
-        msgBroker.msgLinkError("Connection to the link timed out! Please check your internet connection. " + e.getMessage());
+        msgBroker.msgLinkError("Malformed URL: " + e.getMessage());
     }
-    String query = url != null ? url.getQuery() : null;
-
-    if (query == null || query.isEmpty()) {
-        return paramMap;
-    }
-
-    String[] params = query.split("&");
-    boolean returnAllParams = (paramNames == null || paramNames.length == 0);
-
-    for (String param : params) {
-        String[] pair = param.split("=");
-        if (pair.length == 2) {
-            String paramName = pair[0];
-            String paramValue = pair[1];
-
-            if (returnAllParams || contains(paramNames, paramName)) {
-                paramMap.put(paramName, paramValue);
-            }
-        }
-    }

     return paramMap;
 }

These changes address the issues mentioned in the past review comment and improve the overall efficiency and robustness of the method.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* Extracts the specified query parameters from the given URL. If no parameter names are provided (null or empty), all parameters are returned.
*
* @param urlLink The URL string from which to extract parameters.
* @param paramNames The names of the query parameters to extract. If null or empty, all parameters will be returned.
* @return A map containing the query parameter names and their corresponding values.
*/
public static Map<String, String> extractQueryParams(String urlLink, String... paramNames) {
Map<String, String> paramMap = new HashMap<>();
URL url = null;
try {
url = URI.create(urlLink).toURL();
} catch (MalformedURLException e) {
msgBroker.msgLinkError("Connection to the link timed out! Please check your internet connection. " + e.getMessage());
}
String query = url != null ? url.getQuery() : null;
// query is null or empty, return an empty map (no query parameters)
if (query == null || query.isEmpty()) {
return paramMap;
}
// splitting query string into individual parameters
String[] params = query.split("&");
// check if specific parameters are requested or if all should be returned
boolean returnAllParams = (paramNames == null || paramNames.length == 0);
for (String param : params) {
String[] pair = param.split("=");
if (pair.length == 2) {
String paramName = pair[0];
String paramValue = pair[1];
// add parameter to the map if it's requested or if all parameters should be returned
if (returnAllParams || contains(paramNames, paramName)) {
paramMap.put(paramName, paramValue);
}
}
}
return paramMap;
}
/**
* Extracts the specified query parameters from the given URL. If no parameter names are provided (null or empty), all parameters are returned.
*
* @param urlLink The URL string from which to extract parameters.
* @param paramNames The names of the query parameters to extract. If null or empty, all parameters will be returned.
* @return A map containing the query parameter names and their corresponding values.
*/
public static Map<String, String> extractQueryParams(String urlLink, String... paramNames) {
Map<String, String> paramMap = new HashMap<>();
try {
URL url = URI.create(urlLink).toURL();
String query = url.getQuery();
if (query == null || query.isEmpty()) {
return paramMap;
}
String[] params = query.split("&");
boolean returnAllParams = (paramNames == null || paramNames.length == 0);
for (String param : params) {
String[] pair = param.split("=", 2);
String paramName = pair[0];
String paramValue = pair.length > 1 ? pair[1] : "";
if (returnAllParams || contains(paramNames, paramName)) {
paramMap.put(paramName, paramValue);
}
}
} catch (MalformedURLException e) {
msgBroker.msgLinkError("Malformed URL: " + e.getMessage());
}
return paramMap;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
App 💻 Issues/Pull Requests which update Drifty Application Code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] YouTube video link with playlist parameter is mistaken as playlist link
2 participants