use of com.google.api.services.youtube.model.Video in project SkyBot by duncte123.
the class SpotifyAudioSourceManager method loadItem.
@Override
public AudioItem loadItem(DefaultAudioPlayerManager manager, AudioReference reference) {
if (isSpotifyAlbum(reference.identifier)) {
if (youtube == null)
return null;
Matcher res = SPOTIFY_ALBUM_REGEX.matcher(reference.identifier);
if (res.matches()) {
try {
final List<AudioTrack> playList = new ArrayList<>();
final Album album = api.getAlbum(res.group(res.groupCount())).build().get();
for (SimpleTrack t : album.getTracks().getItems()) {
List<SearchResult> results = searchYoutube(album.getArtists().get(0).getName() + " - " + t.getName());
playList.addAll(doThingWithPlaylist(results));
}
return new BasicAudioPlaylist(album.getName(), playList, playList.get(0), false);
} catch (Exception e) {
// logger.error("Something went wrong!", e);
throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
// return null;
}
}
} else if (isSpotifyPlaylist(reference.identifier)) {
if (youtube == null)
return null;
Matcher res = SPOTIFY_PLAYLIST_REGEX.matcher(reference.identifier);
if (res.matches()) {
try {
final List<AudioTrack> finalPlaylist = new ArrayList<>();
final Playlist spotifyPlaylist = api.getPlaylist(res.group(res.groupCount() - 1), res.group(res.groupCount())).build().get();
for (PlaylistTrack playlistTrack : spotifyPlaylist.getTracks().getItems()) {
List<SearchResult> results = searchYoutube(playlistTrack.getTrack().getArtists().get(0).getName() + " - " + playlistTrack.getTrack().getName());
finalPlaylist.addAll(doThingWithPlaylist(results));
}
return new BasicAudioPlaylist(spotifyPlaylist.getName(), finalPlaylist, finalPlaylist.get(0), false);
} catch (Exception e) {
// logger.error("Something went wrong!", e);
throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
// return null;
}
}
} else if (isSpotyfyTrack(reference.identifier)) {
if (youtube == null)
return null;
Matcher res = SPOTIFY_TRACK_REGEX.matcher(reference.identifier);
if (res.matches()) {
try {
final Track track = api.getTrack(res.group(res.groupCount())).build().get();
List<SearchResult> results = searchYoutube(track.getArtists().get(0).getName() + " - " + track.getName());
Video v = getVideoById(results.get(0).getId().getVideoId());
return new SpotifyAudioTrack(new AudioTrackInfo(v.getSnippet().getTitle(), v.getSnippet().getChannelId(), toLongDuration(v.getContentDetails().getDuration()), v.getId(), false, "https://youtube.com/watch?v=" + v.getId()), youtubeAudioSourceManager);
// return youtubeSearchProvider.loadSearchResult(track.getArtists().get(0).getName() + " - "+ track.getName());
} catch (Exception e) {
// logger.error("Something went wrong!", e);
throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
// return null;
}
}
}
/*if(isSpotifyAlbum(reference.identifier)) {
if(this.youtubeAudioSourceManager == null)
return null;
Matcher res = SPOTIFY_ALBUM_REGEX.matcher(reference.identifier);
if (res.matches()) {
try {
final List<AudioTrack> playList = new ArrayList<>();
final Album album = api.getAlbum(res.group(res.groupCount())).build().get();
for(SimpleTrack t : album.getTracks().getItems()){
String fakeUrl = album.getArtists().get(0).getName() + " - "+ t.getName();
List<AudioTrack> tracks = ((AudioPlaylist)youtubeSearchProvider.loadSearchResult(fakeUrl)).getTracks();
if(tracks.size() > 0)
playList.add(tracks.get(0));
}
return new BasicAudioPlaylist(album.getName(), playList, playList.get(0), false);
} catch (Exception e) {
//logger.error("Something went wrong!", e);
throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
//return null;
}
}
} else if(isSpotifyPlaylist(reference.identifier)) {
if(this.youtubeAudioSourceManager == null)
return null;
Matcher res = SPOTIFY_PLAYLIST_REGEX.matcher(reference.identifier);
if (res.matches()) {
try {
final List<AudioTrack> finalPlaylist = new ArrayList<>();
final Playlist spotifyPlaylist = api.getPlaylist(res.group(res.groupCount()-1), res.group(res.groupCount())).build().get();
for(PlaylistTrack playlistTrack : spotifyPlaylist.getTracks().getItems()){
String fakeUrl = playlistTrack.getTrack().getArtists().get(0).getName() + " - " + playlistTrack.getTrack().getName();
System.out.println(fakeUrl);
List<AudioTrack> tracks = ((AudioPlaylist)youtubeSearchProvider.loadSearchResult(fakeUrl)).getTracks();
if(tracks.size() > 0)
finalPlaylist.add(tracks.get(0));
}
return new BasicAudioPlaylist(spotifyPlaylist.getName(), finalPlaylist, finalPlaylist.get(0), false);
} catch (Exception e) {
//logger.error("Something went wrong!", e);
throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
//return null;
}
}
} else if(isSpotyfyTrack(reference.identifier)) {
if(this.youtubeAudioSourceManager == null)
return null;
Matcher res = SPOTIFY_TRACK_REGEX.matcher(reference.identifier);
if (res.matches()) {
try {
final Track track = api.getTrack(res.group(res.groupCount())).build().get();
return youtubeSearchProvider.loadSearchResult(track.getArtists().get(0).getName() + " - "+ track.getName());
} catch (Exception e) {
//logger.error("Something went wrong!", e);
throw new FriendlyException(e.getMessage(), FriendlyException.Severity.FAULT, e);
//return null;
}
}
}*/
return null;
}
use of com.google.api.services.youtube.model.Video in project opencast by opencast.
the class YouTubeAPIVersion3ServiceImpl method addVideoToMyChannel.
@Override
public Video addVideoToMyChannel(final VideoUpload videoUpload) throws IOException {
final Video videoObjectDefiningMetadata = new Video();
final VideoStatus status = new VideoStatus();
status.setPrivacyStatus(videoUpload.getPrivacyStatus());
videoObjectDefiningMetadata.setStatus(status);
// Metadata lives in VideoSnippet
final VideoSnippet snippet = new VideoSnippet();
snippet.setTitle(videoUpload.getTitle());
snippet.setDescription(videoUpload.getDescription());
final String[] tags = videoUpload.getTags();
if (ArrayUtils.isNotEmpty(tags)) {
snippet.setTags(Collections.list(tags));
}
// Attach metadata to video object.
videoObjectDefiningMetadata.setSnippet(snippet);
final File videoFile = videoUpload.getVideoFile();
final BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(videoFile));
final InputStreamContent mediaContent = new InputStreamContent("video/*", inputStream);
mediaContent.setLength(videoFile.length());
final YouTube.Videos.Insert videoInsert = youTube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
final MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(false);
uploader.setProgressListener(videoUpload.getProgressListener());
return execute(videoInsert);
}
use of com.google.api.services.youtube.model.Video in project opencast by opencast.
the class YouTubeV3PublicationServiceImpl method publish.
/**
* Publishes the element to the publication channel and returns a reference to the published version of the element.
*
* @param job
* the associated job
* @param mediaPackage
* the mediapackage
* @param elementId
* the mediapackage element id to publish
* @return the published element
* @throws PublicationException
* if publication fails
*/
private Publication publish(final Job job, final MediaPackage mediaPackage, final String elementId) throws PublicationException {
if (mediaPackage == null) {
throw new IllegalArgumentException("Mediapackage must be specified");
} else if (elementId == null) {
throw new IllegalArgumentException("Mediapackage ID must be specified");
}
final MediaPackageElement element = mediaPackage.getElementById(elementId);
if (element == null) {
throw new IllegalArgumentException("Mediapackage element must be specified");
}
if (element.getIdentifier() == null) {
throw new IllegalArgumentException("Mediapackage element must have an identifier");
}
if (element.getMimeType().toString().matches("text/xml")) {
throw new IllegalArgumentException("Mediapackage element cannot be XML");
}
try {
// create context strategy for publication
final YouTubePublicationAdapter c = new YouTubePublicationAdapter(mediaPackage, workspace);
final File file = workspace.get(element.getURI());
final String episodeName = c.getEpisodeName();
final UploadProgressListener operationProgressListener = new UploadProgressListener(mediaPackage, file);
final String privacyStatus = makeVideosPrivate ? "private" : "public";
final VideoUpload videoUpload = new VideoUpload(truncateTitleToMaxFieldLength(episodeName, false), c.getEpisodeDescription(), privacyStatus, file, operationProgressListener, tags);
final Video video = youTubeService.addVideoToMyChannel(videoUpload);
final int timeoutMinutes = 60;
final long startUploadMilliseconds = new Date().getTime();
while (!operationProgressListener.isComplete()) {
Thread.sleep(POLL_MILLISECONDS);
final long howLongWaitingMinutes = (new Date().getTime() - startUploadMilliseconds) / 60000;
if (howLongWaitingMinutes > timeoutMinutes) {
throw new PublicationException("Upload to YouTube exceeded " + timeoutMinutes + " minutes for episode " + episodeName);
}
}
String playlistName = StringUtils.trimToNull(truncateTitleToMaxFieldLength(mediaPackage.getSeriesTitle(), true));
playlistName = (playlistName == null) ? this.defaultPlaylist : playlistName;
final Playlist playlist;
final Playlist existingPlaylist = youTubeService.getMyPlaylistByTitle(playlistName);
if (existingPlaylist == null) {
playlist = youTubeService.createPlaylist(playlistName, c.getContextDescription(), mediaPackage.getSeries());
} else {
playlist = existingPlaylist;
}
youTubeService.addPlaylistItem(playlist.getId(), video.getId());
// Create new publication element
final URL url = new URL("http://www.youtube.com/watch?v=" + video.getId());
return PublicationImpl.publication(UUID.randomUUID().toString(), CHANNEL_NAME, url.toURI(), MimeTypes.parseMimeType(MIME_TYPE));
} catch (Exception e) {
logger.error("failed publishing to Youtube", e);
logger.warn("Error publishing {}, {}", element, e.getMessage());
if (e instanceof PublicationException) {
throw (PublicationException) e;
} else {
throw new PublicationException("YouTube publish failed on job: " + ToStringBuilder.reflectionToString(job, ToStringStyle.MULTI_LINE_STYLE), e);
}
}
}
use of com.google.api.services.youtube.model.Video in project opencast by opencast.
the class YouTubeV3PublicationServiceImplTest method testPublishNewPlaylist.
@Test
public void testPublishNewPlaylist() throws Exception {
final File baseDir = new File(this.getClass().getResource("/mediapackage").toURI());
final String xml = FileUtils.readFileToString(new File(baseDir, "manifest.xml"));
final MediaPackage mediaPackage = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().loadFromXml(xml);
//
expect(youTubeService.getMyPlaylistByTitle(mediaPackage.getTitle())).andReturn(null).once();
expect(youTubeService.createPlaylist(mediaPackage.getSeriesTitle(), null, mediaPackage.getSeries())).andReturn(new Playlist()).once();
expect(youTubeService.addVideoToMyChannel(anyObject(VideoUpload.class))).andReturn(new Video()).once();
expect(youTubeService.addPlaylistItem(anyObject(String.class), anyObject(String.class))).andReturn(new PlaylistItem()).once();
expect(registry.createJob(anyObject(String.class), anyObject(String.class), anyObject(List.class), anyObject(Float.class))).andReturn(new JobImpl()).once();
replay(youTubeService, orgDirectory, security, registry, userDirectoryService, workspace);
service.updated(getServiceProperties());
service.publish(mediaPackage, mediaPackage.getTracks()[0]);
}
use of com.google.api.services.youtube.model.Video in project api-samples by youtube.
the class UpdateVideo method main.
/**
* Add a keyword tag to a video that the user specifies. Use OAuth 2.0 to
* authorize the API request.
*
* @param args command line args (not used).
*/
public static void main(String[] args) {
// This OAuth 2.0 access scope allows for full read/write access to the
// authenticated user's account.
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
try {
// Authorize the request.
Credential credential = Auth.authorize(scopes, "updatevideo");
// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-updatevideo-sample").build();
// Prompt the user to enter the video ID of the video being updated.
String videoId = getVideoIdFromUser();
System.out.println("You chose " + videoId + " to update.");
// Prompt the user to enter a keyword tag to add to the video.
String tag = getTagFromUser();
System.out.println("You chose " + tag + " as a tag.");
// Call the YouTube Data API's youtube.videos.list method to
// retrieve the resource that represents the specified video.
YouTube.Videos.List listVideosRequest = youtube.videos().list("snippet").setId(videoId);
VideoListResponse listResponse = listVideosRequest.execute();
// Since the API request specified a unique video ID, the API
// response should return exactly one video. If the response does
// not contain a video, then the specified video ID was not found.
List<Video> videoList = listResponse.getItems();
if (videoList.isEmpty()) {
System.out.println("Can't find a video with ID: " + videoId);
return;
}
// Extract the snippet from the video resource.
Video video = videoList.get(0);
VideoSnippet snippet = video.getSnippet();
// Preserve any tags already associated with the video. If the
// video does not have any tags, create a new array. Append the
// provided tag to the list of tags associated with the video.
List<String> tags = snippet.getTags();
if (tags == null) {
tags = new ArrayList<String>(1);
snippet.setTags(tags);
}
tags.add(tag);
// Update the video resource by calling the videos.update() method.
YouTube.Videos.Update updateVideosRequest = youtube.videos().update("snippet", video);
Video videoResponse = updateVideosRequest.execute();
// Print information from the updated resource.
System.out.println("\n================== Returned Video ==================\n");
System.out.println(" - Title: " + videoResponse.getSnippet().getTitle());
System.out.println(" - Tags: " + videoResponse.getSnippet().getTags());
} catch (GoogleJsonResponseException e) {
System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Throwable: " + t.getMessage());
t.printStackTrace();
}
}
Aggregations