Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/main/java/com/sapher/youtubedl/YoutubeDL.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

Expand Down Expand Up @@ -122,6 +123,41 @@ public static String getVersion() throws YoutubeDLException {
request.setOption("version");
return YoutubeDL.execute(request).getOut();
}

/**
* List the first {@amount} of video's found by searching on YouTube
* @param searchQuery Search query
* @param amount Amount of videos to search for
* @return List of videos
* @throws YoutubeDLException
*/
public static List<VideoInfo> search(String searchQuery, int amount) throws YoutubeDLException {

// Build query
String query = "ytsearch" + amount + ":\"" + searchQuery + "\"";

// Build request
YoutubeDLRequest request = new YoutubeDLRequest(query);
request.setOption("dump-json");
request.setOption("no-playlist");
YoutubeDLResponse response = YoutubeDL.execute(request);

// Parse result
String[] out = response.getOut().split("\n");
ObjectMapper objectMapper = new ObjectMapper();
List<VideoInfo> videos = new ArrayList<VideoInfo>();

try {
for (int i = 0; i < out.length; i++) {
VideoInfo video = objectMapper.readValue(out[i], VideoInfo.class);
videos.add(video);
}
} catch (IOException e) {
throw new YoutubeDLException("Unable to parse video information: " + e.getMessage());
}

return videos;
}

/**
* Retrieve all information available on a video
Expand Down
8 changes: 8 additions & 0 deletions src/test/java/com/sapher/youtubedl/YoutubeDLTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
public class YoutubeDLTest {

private final static String DIRECTORY = System.getProperty("java.io.tmpdir");
private final static String SEARCH_QUERY = "Rick Astley - Never Gonna Give You Up";
private final static int SEARCH_AMOUNT = 5;
private final static String VIDEO_URL = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
private final static String NONE_EXISTENT_VIDEO_URL = "https://www.youtube.com/watch?v=dQw4w9WgXcZ";

Expand Down Expand Up @@ -62,6 +64,12 @@ public void testDirectory() throws YoutubeDLException {

Assert.assertEquals(DIRECTORY, response.getDirectory());
}

@Test
public void testSearch() throws YoutubeDLException {
List<VideoInfo> videos = YoutubeDL.search(SEARCH_QUERY, SEARCH_AMOUNT);
Assert.assertFalse(videos.isEmpty());
}

@Test
public void testGetVideoInfo() throws YoutubeDLException {
Expand Down