Search code examples
c#youtubegoogle-api-clientyoutube-data-api

How to manage a YouTube account's playlist automatically


What I need

I'm working on a C# app that scans Facebook messages for youtube links and adds each new video to an existing playlist. If the playlist doesn't exist yet, it needs to be created.

What I have

I have this code that creates a new playlist:

// Create a new, private playlist in the authorized user's channel.
var newPlaylist = new Playlist();
newPlaylist.Snippet = new PlaylistSnippet();
newPlaylist.Snippet.Title = "Test Playlist";
newPlaylist.Snippet.Description = "A playlist created with the YouTube API v3";
newPlaylist.Status = new PlaylistStatus();
newPlaylist.Status.PrivacyStatus = "public";
newPlaylist = await youtubeService.Playlists.Insert(newPlaylist, "snippet,status").ExecuteAsync();

but since it's insert, it will always create a new instance of the same requested playlist, on multiple runs. It should be update if the playlist already exists.

This is the code that adds a new video, also insert:

try
{
    // Add a video to the newly created playlist.
    var newPlaylistItem = new PlaylistItem();
    newPlaylistItem.Snippet = new PlaylistItemSnippet();
    newPlaylistItem.Snippet.PlaylistId = "PLMl3RyOwPdGlcrBTNYiu1XiNNgqYx6mx8";
    //newPlaylistItem.Snippet.PlaylistId = newPlaylist.Id;
    newPlaylistItem.Snippet.ResourceId = new ResourceId();
    newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video";
    newPlaylistItem.Snippet.ResourceId.VideoId = videoId;
    newPlaylistItem = await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync();
}
catch (Exception ex)
{
    // Do some logging.
    // Likely doesn't exist anymore, ignore.
}

Question

  1. How do I check if a playlist already exists?

  2. How do I check if a videa was already added?


Solution

  • You can use the YouTube Data API v3 to access the data:

    1. Playlists: list - will allow you to list all the playlists of a user
    2. PlaylistItems: list - will allow you to list the items in playlist