public async Task <ActionResult> Start(int id)
        {
            var q = db.YoutubeLiveDetails.Where(x => x.Id == id).FirstOrDefault();

            try
            {
                if (q != null)
                {
                    var liveController = new BroadcastController();

                    var youtube          = new YouTubeService(await(new GoogleAuthentication()).GetInitializer());
                    var broadcastRequest = youtube.LiveBroadcasts.List("id,status");
                    broadcastRequest.Id = q.BroadcastId;
                    var returnedList = broadcastRequest.Execute();
                    var broadcast    = returnedList.Items.FirstOrDefault();

                    var streamRequest = youtube.LiveStreams.List("id,status");
                    streamRequest.Id = q.StreamId;
                    var streamList = streamRequest.Execute();
                    var stream     = streamList.Items.FirstOrDefault();

                    if (broadcast != null && stream != null)
                    {
                        LiveBroadcast transBroadcast = await liveController.transitionBroadcast(broadcast, stream, Google.Apis.YouTube.v3.LiveBroadcastsResource.TransitionRequest.BroadcastStatusEnum.Live);
                    }
                }
                return(View("Details", q));
            }
            catch
            {
                return(View("Index", db.YoutubeLiveDetails));
            }
        }
        // needs to be tested
        public async Task <LiveBroadcast> updateBroadcast(String broadcastId, String snippetTitle, DateTime startTime, DateTime endTime, String privacyStatus)
        {
            youtube = new YouTubeService(await youtubeAuthen.GetInitializer());

            IList <LiveBroadcast> broadcasts = await listBroadcast();

            for (int i = 0; i < broadcasts.Count; i++)
            {
                if (broadcasts[i].Id == broadcastId)
                {
                    LiveBroadcast updateBroadcast = new LiveBroadcast();

                    // Set broadcast snippet
                    updateBroadcast.Snippet       = new LiveBroadcastSnippet();
                    updateBroadcast.Snippet.Title = snippetTitle;
                    updateBroadcast.Snippet.ScheduledStartTime = startTime;
                    updateBroadcast.Snippet.ScheduledEndTime   = endTime;

                    //Set broadcast status
                    updateBroadcast.Status = new LiveBroadcastStatus();
                    updateBroadcast.Status.PrivacyStatus = privacyStatus;

                    LiveBroadcastsResource.UpdateRequest liveBroadcastUpdate = youtube.LiveBroadcasts.Update(updateBroadcast, "id, snippet,contentDetails,status");

                    LiveBroadcast broadcastResponse = liveBroadcastUpdate.Execute();

                    return(broadcastResponse);
                }
            }
            throw new System.ArgumentException("Parameter must belong to user and not be null", "Invalid");
        }
 /// <summary>
 /// Gets the currently active broadcast associated with the specified channel.
 /// </summary>
 /// <param name="channel">The channel to get the live broadcast for</param>
 /// <returns>The current live broadcast</returns>
 public async Task <LiveBroadcast> GetChannelActiveBroadcast(Channel channel)
 {
     return(await this.YouTubeServiceWrapper(async() =>
     {
         IEnumerable <Video> videos = await connection.Videos.GetVideosForChannel(channel, 5);
         if (videos != null && videos.Count() > 0)
         {
             Video video = videos.FirstOrDefault(v => string.Equals(v.Snippet.LiveBroadcastContent, "live", StringComparison.InvariantCultureIgnoreCase));
             if (video != null && !string.IsNullOrEmpty(video.LiveStreamingDetails?.ActiveLiveChatId))
             {
                 LiveBroadcast broadcast = await this.GetBroadcastByID(video.Id);
                 if (broadcast == null)
                 {
                     broadcast = new LiveBroadcast()
                     {
                         Snippet = new LiveBroadcastSnippet()
                         {
                             LiveChatId = video.LiveStreamingDetails.ActiveLiveChatId
                         }
                     };
                 }
                 return broadcast;
             }
         }
         return null;
     }));
 }
Example #4
0
        /// <summary>
        /// Gets the messages for a live chat.
        /// </summary>
        /// <param name="broadcast">The broadcast of the live chat</param>
        /// <param name="nextResultsToken">The token for querying the next set of results from a previous query</param>
        /// <param name="maxResults">The maximum results to return</param>
        /// <returns>The list of chat messages</returns>
        public async Task <LiveChatMessagesResultModel> GetMessages(LiveBroadcast broadcast, string nextResultsToken = null, int maxResults = 0)
        {
            Validator.ValidateVariable(broadcast, "broadcast");
            return(await this.YouTubeServiceWrapper(async() =>
            {
                LiveChatMessagesResource.ListRequest request = this.connection.GoogleYouTubeService.LiveChatMessages.List(broadcast.Snippet.LiveChatId, "id,snippet,authorDetails");

                if (maxResults > 0)
                {
                    request.MaxResults = maxResults;
                }

                if (!string.IsNullOrEmpty(nextResultsToken))
                {
                    request.PageToken = nextResultsToken;
                }

                LogRequest(request);

                LiveChatMessageListResponse response = await request.ExecuteAsync();
                LogResponse(request, response);

                return new LiveChatMessagesResultModel(response);
            }));
        }
Example #5
0
    public string GetLiveBroadcasts()
    {
        List <LiveBroadcast> LiveBroadcasts = LiveBroadcast.GetAllLiveBroadcastNOW();

        StringBuilder sbHTMLList = new StringBuilder();

        for (int i = 0; i < 3; i++)
        {
            if (LiveBroadcasts.Count <= i)
            {
                break;
            }

            StringBuilder sbHTMLItem = new StringBuilder();

            object[] parameters = new object[4];


            //parameters[0] = "http://www.next2friends.com/" + LiveBroadcasts[i].ThumbnailResourceFile.FullyQualifiedURL;
            //parameters[1] = "http://www.next2friends.com/" + LiveBroadcasts[i].ThumbnailResourceFile.FullyQualifiedURL;
            //parameters[2] = "http://www.next2friends.com/" + LiveBroadcasts[i].ThumbnailResourceFile.FullyQualifiedURL;
            //parameters[3] = "http://www.next2friends.com/" + LiveBroadcasts[i].ThumbnailResourceFile.FullyQualifiedURL;


            string HTMLItem = @"videoSlider.insert( 0, '{1}', '{2}', '{3}', false, true );";

            sbHTMLItem.AppendFormat(HTMLItem, parameters);
            sbHTMLList.Append(sbHTMLItem.ToString());
        }

        return(sbHTMLList.ToString());
    }
        /// <summary>
        /// Updates a broadcast. For example, you could modify the broadcast settings defined in the liveBroadcast resource's contentDetails object.
        /// Documentation https://developers.google.com/youtube/v3/reference/liveBroadcasts/update
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Youtube service.</param>
        /// <param name="part">The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.The part properties that you can include in the parameter value are id, snippet, contentDetails, and status.Note that this method will override the existing values for all of the mutable properties that are contained in any parts that the parameter value specifies. For example, a broadcast's privacy status is defined in the status part. As such, if your request is updating a private or unlisted broadcast, and the request's part parameter value includes the status part, the broadcast's privacy setting will be updated to whatever value the request body specifies. If the request body does not specify a value, the existing privacy setting will be removed and the broadcast will revert to the default privacy setting.</param>
        /// <param name="body">A valid Youtube v3 body.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>LiveBroadcastResponse</returns>
        public static LiveBroadcast Update(YoutubeService service, string part, LiveBroadcast body, LiveBroadcastsUpdateOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (part == null)
                {
                    throw new ArgumentNullException(part);
                }

                // Building the initial request.
                var request = service.LiveBroadcasts.Update(body, part);

                // Applying optional parameters to the request.
                request = (LiveBroadcastsResource.UpdateRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request LiveBroadcasts.Update failed.", ex);
            }
        }
Example #7
0
        public FlashVideoDescriptor FlashVideos(string Nickname)
        {
            FlashPollType flashPollType = FlashPollType.LiveOnly;

            FlashVideoDescriptor ReturnFlashVideoDescriptor = null;
            Member member = Member.GetMemberViaNickname(Nickname);


            if (flashPollType == FlashPollType.LiveOnly)
            {
                LiveBroadcast live = LiveBroadcast.GetLiveBroadcastByMemberID(member.WebMemberID);
                ReturnFlashVideoDescriptor = FlashVideoDescriptor.ParseLive(live);
            }
            else if (flashPollType == FlashPollType.LastClip)
            {
                // Next2Friends.Data.Video video = Next2Friends.Data.Video.GetLatestVideoByNickname(Nickname);
            }
            else if (flashPollType == FlashPollType.LiveAndLastClip)
            {
                //LiveBroadcast live = LiveBroadcast.GetLiveBroadcastByMemberID(member.MemberID);

                //if (live != null)
                //{
                //ReturnFlashVideoDescriptor = FlashVideoDescriptor.ParseLive(live);
                //}
                //else
                //{

                //}
            }

            return(ReturnFlashVideoDescriptor);
        }
Example #8
0
    public string GetLiveBroadcasts()
    {
        List <LiveBroadcast> LiveBroadcasts = LiveBroadcast.GetAllLiveBroadcastNOW2();

        NumberOfLiveStreams = LiveBroadcasts.Count;

        StringBuilder sbHTMLList = new StringBuilder();

        for (int i = LiveBroadcasts.Count - 1; i >= 0; i--)
        {
            StringBuilder sbHTMLItem = new StringBuilder();

            object[] parameters = new object[4];

            parameters[0] = LiveBroadcasts[i].WebLiveBroadcastID;
            parameters[1] = "";
            parameters[2] = "http://www.next2friends.com/" + LiveBroadcasts[i].ThumbnailURL;
            parameters[3] = LiveBroadcasts[i].Member.NickName + ":" + LiveBroadcasts[i].Member.ISOCountry;

            string HTMLItem = @"livePush('{0}', '{1}', '{2}', '{3}', true, false);";

            sbHTMLItem.AppendFormat(HTMLItem, parameters);
            sbHTMLList.Append(sbHTMLItem.ToString());
        }

        if (LiveBroadcasts.Count > 0)
        {
            //player(fl,fr,play,live,id){
            DefaultPlayerJS  = "player('','',true,true,'" + LiveBroadcasts[0].WebLiveBroadcastID + "');";
            DefaultLiveTitle = LiveBroadcasts[0].Member.NickName + ":" + LiveBroadcasts[0].Member.ISOCountry;
            IsLive           = "true";
        }

        return(sbHTMLList.ToString());
    }
Example #9
0
        public static string GetHTML(LiveBroadcast stream)
        {
            StringBuilder returnMe = new StringBuilder();

            returnMe.Append("<iframe src=\"https://www.youtube.com/embed/" + stream.YouTubeID + "?autoplay=1\"" + " frameborder=\"0\" style=\"border: 0px solid black; width: " + stream.Width + "px; height: " + stream.Height + "px;\" allowfullscreen>");
            returnMe.Append("<object data=\"data:application/x-silverlight-2,\" type=\"application/x-silverlight-2\" width=\"" + stream.Width + "\" height=\"" + stream.Height + "\">");
            returnMe.Append("</iframe>");
            return(returnMe.ToString());
        }
 /// <summary>
 /// Updates the specified broadcast.
 /// </summary>
 /// <param name="broadcast">The broadcast to update</param>
 /// <returns>The updated broadcast</returns>
 public async Task <LiveBroadcast> UpdateBroadcast(LiveBroadcast broadcast)
 {
     Validator.ValidateVariable(broadcast, "broadcast");
     return(await this.YouTubeServiceWrapper(async() =>
     {
         LiveBroadcastsResource.UpdateRequest request = this.connection.GoogleYouTubeService.LiveBroadcasts.Update(broadcast, "id,snippet,contentDetails,status");
         return await request.ExecuteAsync();
     }));
 }
Example #11
0
 /// <summary>
 /// Disconnectes from the current broadcast.
 /// </summary>
 /// <returns>An awaitable Task</returns>
 public Task Disconnect()
 {
     this.broadcast = null;
     if (this.messageBackgroundPollingTokenSource != null)
     {
         this.messageBackgroundPollingTokenSource.Cancel();
     }
     return(Task.FromResult(0));
 }
        public static void Main(string[] args)
        {
            Logger.SetLogLevel(LogLevel.Debug);

            Logger.LogOccurred += Logger_LogOccurred;
            Task.Run(async () =>
            {
                try
                {
                    System.Console.WriteLine("Initializing connection");

                    YouTubeConnection connection = await YouTubeConnection.ConnectViaLocalhostOAuthBrowser(clientID, clientSecret, scopes);
                    if (connection != null)
                    {
                        Channel channel = await connection.Channels.GetMyChannel();

                        //Channel channel = await connection.Channels.GetChannelByID("");

                        if (channel != null)
                        {
                            System.Console.WriteLine("Connection successful. Logged in as: " + channel.Snippet.Title);

                            LiveBroadcast broadcast = await connection.LiveBroadcasts.GetChannelActiveBroadcast(channel);

                            System.Console.WriteLine("Connecting chat client!");

                            ChatClient client = new ChatClient(connection);
                            client.OnMessagesReceived += Client_OnMessagesReceived;

                            if (await client.Connect(broadcast))
                            {
                                System.Console.WriteLine("Live chat connection successful!");

                                if (await connection.LiveBroadcasts.GetMyActiveBroadcast() != null)
                                {
                                    await client.SendMessage("Hello World!");
                                }

                                while (true) { }
                            }
                            else
                            {
                                System.Console.WriteLine("Failed to connect to live chat");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.ToString());
                }
            });

            System.Console.ReadLine();
        }
 /// <summary>
 /// Enables/Disables the slate for a live broadcast.
 /// </summary>
 /// <param name="broadcast">The broadcast to update</param>
 /// <param name="showSlate">Indicates whether to show or hide the slate</param>
 /// <returns>An awaitable Task</returns>
 public async Task EnableDisableSlate(LiveBroadcast broadcast, bool showSlate)
 {
     Validator.ValidateVariable(broadcast, "broadcast");
     await this.YouTubeServiceWrapper <object>(async() =>
     {
         LiveBroadcastsResource.ControlRequest request = this.connection.GoogleYouTubeService.LiveBroadcasts.Control(broadcast.Id, "snippet,contentDetails");
         request.DisplaySlate = showSlate;
         await request.ExecuteAsync();
         return(null);
     });
 }
        // Redo
        public async Task <LiveBroadcast> transitionBroadcast(LiveBroadcast broadcast, LiveStream stream, tranRef.BroadcastStatusEnum broadcastStatusEnum)
        {
            youtube = new YouTubeService(await youtubeAuthen.GetInitializer());
            if (stream.Status.StreamStatus != "active")
            {
                throw new Exception("stream is not active");
            }
            LiveBroadcastsResource.TransitionRequest liveBroadcastTransition = youtube.LiveBroadcasts.Transition(broadcastStatusEnum, broadcast.Id, "id,snippet,contentDetails,status");
            LiveBroadcast broadcastResponse = liveBroadcastTransition.Execute();

            return(broadcastResponse);
        }
Example #15
0
        public void BindBroadCast()
        {
            //Executes live broadcast by binding the livestream and broadcast together and submitting it
            var liveBroadcastBind = service.LiveBroadcasts.Bind(returnedBroadCast.Id, "id, contentDetails");

            liveBroadcastBind.StreamId = returnedStream.Id;
            returnedBroadCast          = liveBroadcastBind.Execute();

            Console.WriteLine("\n================== Returned Bound Broadcast ==================\n");
            Console.WriteLine("  - Broadcast Id: " + returnedBroadCast.Id);
            Console.WriteLine("  - Bound Stream Id: " + returnedBroadCast.ContentDetails.BoundStreamId);
        }
        // Binds a stream to a broadcast verified
        public async Task <LiveBroadcast> bindBroadcast(LiveBroadcast broadcast, LiveStream Livestream)
        {
            youtube = new YouTubeService(await youtubeAuthen.GetInitializer());

            LiveBroadcastsResource.BindRequest liveBroadcastBind = youtube.LiveBroadcasts.Bind(broadcast.Id, "id,contentDetails");
            liveBroadcastBind.StreamId = Livestream.Id;
            LiveBroadcast returnedBroadcast = liveBroadcastBind.Execute();

            returnedBroadcast.ContentDetails.EnableEmbed = true;

            return(returnedBroadcast);
        }
        public async Task <ActionResult> Create([Bind(Include = "Id,CourseId,BroadcastId,BroadcastKind,BroadcastTitle,BroadcastDescription,BroadcastScheduledStartTime,BroadcastScheduledEndTime,BroadcastStatus,BroadcastchannelId,BroadcastlifeCycleStatus,BroadcastEmbededhtml,StreamId,StreamKind,StreamName,StreamStatus,StreamSnippetTitle,StreamCDNFormat,StreamCDNIngestionType,StreamCDNIngestionUrl,StreamcontentclosedCaptionsIngestionUrl")] YoutubeLiveDetail youtubelivedetail)
        {
            BroadcastController liveController = new BroadcastController();

            youtubelivedetail.StreamCDNIngestionType = "rtmp";
            youtubelivedetail.BroadcastKind          = "youtube#liveBroadcast";
            youtubelivedetail.StreamKind             = "youtube#liveStream";
            // Create broadcast and stream for YoutubeLive
            LiveBroadcast broadcast = await liveController.createBroadcast(youtubelivedetail.BroadcastKind, youtubelivedetail.BroadcastTitle, youtubelivedetail.BroadcastScheduledStartTime, youtubelivedetail.BroadcastScheduledEndTime, youtubelivedetail.BroadcastStatus);

            LiveStream stream = await liveController.createStream(youtubelivedetail.StreamKind, youtubelivedetail.StreamSnippetTitle, youtubelivedetail.StreamCDNFormat, youtubelivedetail.StreamCDNIngestionType);

            // Bind them together
            LiveBroadcast bindedBroadcast = await liveController.bindBroadcast(broadcast, stream);

            // Values to-be inserted updated
            youtubelivedetail.BroadcastId           = bindedBroadcast.Id;
            youtubelivedetail.BroadcastchannelId    = bindedBroadcast.ContentDetails.BoundStreamId;
            youtubelivedetail.StreamName            = stream.Cdn.IngestionInfo.StreamName;
            youtubelivedetail.StreamStatus          = stream.Status.StreamStatus;
            youtubelivedetail.StreamId              = stream.Id;
            youtubelivedetail.StreamCDNIngestionUrl = stream.Cdn.IngestionInfo.IngestionAddress;

            String         id      = (bindedBroadcast.ContentDetails.MonitorStream.EmbedHtml).ToString();
            YouTubeService youtube = new YouTubeService(await(new GoogleAuthentication()).GetInitializer());

            bindedBroadcast.ContentDetails.MonitorStream.EnableMonitorStream = false;
            LiveBroadcastsResource.UpdateRequest disablePreview = youtube.LiveBroadcasts.Update(bindedBroadcast, "contentDetails");
            LiveBroadcast returnBroadcast = disablePreview.Execute();

            //substring for browser
            if (id.Contains("embed/"))
            {
                int startIndex = id.IndexOf("embed/");
                int endIndex   = id.IndexOf("?");
                id = id.Substring(startIndex + 6, (endIndex - (startIndex + 6)));
            }

            youtubelivedetail.BroadcastEmbededhtml = id;

            //BroadCastID for Player

            if (ModelState.IsValid)
            {
                db.YoutubeLiveDetails.Add(youtubelivedetail);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.CourseId = new SelectList(db.Courses, "Id", "Title", youtubelivedetail.CourseId);
            return(View(youtubelivedetail));
        }
Example #18
0
 protected void btnAdd_Click(object sender, EventArgs e)
 {
     try
     {
         LiveBroadcastRepository liveBroadcastRepository = new LiveBroadcastRepository();
         LiveBroadcast           stream = ParseStream();
         liveBroadcastRepository.Insert(stream);
         RedirectToStreamList(stream.ID);
     }
     catch (Exception ex)
     {
         displayError(ex.Message);
     }
 }
        /// <summary>
        /// Parse the livebroadcast into a FlashVideoDescriptor
        /// </summary>
        public static FlashVideoDescriptor ParseLive(LiveBroadcast livebroadcast)
        {
            FlashVideoDescriptor VideoDescriptor = null;

            if (livebroadcast != null)
            {
                VideoDescriptor        = new FlashVideoDescriptor();
                VideoDescriptor.IsLive = true;
                VideoDescriptor.Title  = livebroadcast.Title;
                VideoDescriptor.LiveID = livebroadcast.WebLiveBroadcastID;
            }

            return(VideoDescriptor);
        }
Example #20
0
        public LiveBroadcast GenerateBroadCast()
        {
            //broadcast snippet contains basic info about the broadcast and this is shown on youtube when launched
            LiveBroadcastSnippet broadCastSnippet = new LiveBroadcastSnippet();

            broadCastSnippet.Title       = "Test";
            broadCastSnippet.Description = "A test of the youtube data API";
            //TODO: Add a thumbnail icon
            broadCastSnippet.ScheduledStartTime = DateTime.Now;

            //Applies settings of made for kids and unlisted to snippet i.e broadcast settings
            LiveBroadcastStatus broadCastStatus = new LiveBroadcastStatus();

            broadCastStatus.SelfDeclaredMadeForKids = false;
            broadCastStatus.PrivacyStatus           = "unlisted";

            //enables the broadcast to view a different "special stream" in case of time delays etc good for debugging
            MonitorStreamInfo broadCastMonitorStream = new MonitorStreamInfo();

            broadCastMonitorStream.EnableMonitorStream = true;

            //contains info about the monitor stream
            LiveBroadcastContentDetails broadCastContentDetails = new LiveBroadcastContentDetails();

            broadCastContentDetails.MonitorStream = broadCastMonitorStream;

            LiveBroadcast broadCast = new LiveBroadcast();

            broadCast.Snippet        = broadCastSnippet;        //binds the info regarding stream
            broadCast.Status         = broadCastStatus;         //privacy settings & reg settings
            broadCast.ContentDetails = broadCastContentDetails; //binds monitor info

            //Allows to finalise the setting up and is ready to be transmitted
            LiveBroadcastsResource.InsertRequest liveBroadCastInsert = service.LiveBroadcasts.Insert(broadCast, "snippet,status,contentDetails");
            //Reads the returned var

            LiveBroadcast returnedBroadCast = liveBroadCastInsert.Execute();

            Console.WriteLine("\n================== Returned Broadcast ==================\n");
            Console.WriteLine("  - Id: " + returnedBroadCast.Id);
            Console.WriteLine("  - Title: " + returnedBroadCast.Snippet.Title);
            Console.WriteLine("  - Description: " + returnedBroadCast.Snippet.Description);
            Console.WriteLine("  - Published At: " + returnedBroadCast.Snippet.PublishedAt);
            Console.WriteLine(
                "  - Scheduled Start Time: " + returnedBroadCast.Snippet.ScheduledStartTime);
            Console.WriteLine(
                "  - Scheduled End Time: " + returnedBroadCast.Snippet.ScheduledEndTime);

            return(returnedBroadCast);
        }
        /// <summary>
        /// Connects to the specified broadcast.
        /// </summary>
        /// <param name="broadcast">The broadcast to connect to</param>
        /// <param name="listenForMessage">Whether to enable message listen polling</param>
        /// <returns>Whether the connection was successful</returns>
        public Task <bool> Connect(LiveBroadcast broadcast, bool listenForMessage = true)
        {
            this.broadcast = broadcast;

            if (listenForMessage)
            {
                this.messageBackgroundPollingTokenSource = new CancellationTokenSource();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                Task.Run(this.MessageBackgroundPolling, this.messageBackgroundPollingTokenSource.Token);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }

            return(Task.FromResult(true));
        }
Example #22
0
        public YoutubeAPI()
        {
            service           = OAuth();
            returnedBroadCast = GenerateBroadCast();
            returnedStream    = GenerateAPIKey();
            BindBroadCast();

            Thread ffMPEGThread = new Thread(FFMPEGStream.Start);

            ffMPEGThread.Start();

            PrepareStream();
            Console.WriteLine("\nFinished Youtube API Function");
        }
        private static string buildLiveStreamInfoHTML(LiveBroadcast stream)
        {
            int           container_width = stream.Width;
            StringBuilder returnMe        = new StringBuilder();

            returnMe.Append("<div style=\"max-width: " + container_width + "px; margin-left: auto; margin-right: auto;\">");
            returnMe.Append("<div class=\"video_list_name\">" + stream.Name + "</div>");
            returnMe.Append("<div class=\"video_list_info\"><b>Broadcasting from:</b> " + stream.Location + "</div>");
            returnMe.Append("<div class=\"video_list_info\"><b>Scheduled start:</b> " + stream.StartTime.ToLongDateString() + " " + stream.StartTime.ToLongTimeString() + "</div>");
            returnMe.Append("<div class=\"video_list_info\"><b>Scheduled end:</b> " + stream.EndTime.ToLongDateString() + " " + stream.EndTime.ToLongTimeString() + "</div>");
            returnMe.Append("<br/><div class=\"video_list_description\">" + stream.Description + "</div>");
            returnMe.Append("</div><br/><br/><br/>");
            return(returnMe.ToString());
        }
Example #24
0
        /// <summary>
        /// Connects to the chat for the current broadcast.
        /// </summary>
        /// <returns>Whether the connection was successful</returns>
        public async Task <bool> Connect()
        {
            IEnumerable <LiveBroadcast> broadcasts = await this.connection.LiveBroadcasts.GetMyBroadcasts();

            if (broadcasts.Count() > 0)
            {
                this.broadcast = broadcasts.First();

                this.messageBackgroundPollingTokenSource = new CancellationTokenSource();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                Task.Run(this.MessageBackgroundPolling, this.messageBackgroundPollingTokenSource.Token);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
            return(false);
        }
        /// <summary>
        /// Starts an ad break for the live broadcast.
        /// </summary>
        /// <param name="broadcast">The broadcast of the live broadcast</param>
        /// <param name="duration">The duration of the ad break</param>
        /// <returns>Information about the ad break</returns>
        public async Task <LiveCuepoint> StartAdBreak(LiveBroadcast broadcast, long duration)
        {
            Validator.ValidateVariable(broadcast, "broadcast");
            return(await this.YouTubeServiceWrapper(async() =>
            {
                LiveCuepoint liveCuepoint = new LiveCuepoint();
                liveCuepoint.BroadcastId = broadcast.Id;
                liveCuepoint.Settings = new CuepointSettings();
                liveCuepoint.Settings.CueType = "ad";
                liveCuepoint.Settings.DurationSecs = duration;

                LiveCuepointsResource.InsertRequest request = this.connection.GoogleYouTubePartnerService.LiveCuepoints.Insert(liveCuepoint, broadcast.Snippet.ChannelId);
                return await request.ExecuteAsync();
            }));
        }
        private async Task MessageBackgroundPolling()
        {
            string nextResultsToken = null;

            while (!this.messageBackgroundPollingTokenSource.IsCancellationRequested)
            {
                try
                {
                    if (broadcast != null)
                    {
                        LiveChatMessagesResultModel result = await this.connection.LiveChat.GetMessages(this.broadcast, nextResultsToken : nextResultsToken, maxResults : 200);

                        if (result != null)
                        {
                            List <LiveChatMessage> newMessages = new List <LiveChatMessage>();
                            foreach (LiveChatMessage message in result.Messages)
                            {
                                if (!messageIDs.Contains(message.Id))
                                {
                                    newMessages.Add(message);
                                    messageIDs.Add(message.Id);
                                }
                            }

                            if (newMessages.Count > 0)
                            {
                                this.OnMessagesReceived?.Invoke(this, newMessages);
                            }

                            nextResultsToken = result.NextResultsToken;
                            await Task.Delay((int)result.PollingInterval);
                        }
                        else
                        {
                            await Task.Delay(10000);
                        }
                    }
                    else
                    {
                        this.broadcast = await this.connection.LiveBroadcasts.GetActiveBroadcast();

                        await Task.Delay(60000);
                    }
                }
                catch (TaskCanceledException) { }
                catch (Exception ex) { Logger.Log(ex); }
            }
        }
Example #27
0
        /// <summary>
        /// Makes the specified user a moderator.
        /// </summary>
        /// <param name="broadcast">The broadcast of the live chat</param>
        /// <param name="user">The user to mod</param>
        /// <returns>Information about the modded user</returns>
        public async Task <LiveChatModerator> ModUser(LiveBroadcast broadcast, Channel user)
        {
            Validator.ValidateVariable(broadcast, "broadcast");
            Validator.ValidateVariable(user, "user");
            return(await this.YouTubeServiceWrapper(async() =>
            {
                LiveChatModerator moderator = new LiveChatModerator();
                moderator.Snippet = new LiveChatModeratorSnippet();
                moderator.Snippet.LiveChatId = broadcast.Snippet.LiveChatId;
                moderator.Snippet.ModeratorDetails = new ChannelProfileDetails();
                moderator.Snippet.ModeratorDetails.ChannelId = user.Id;

                LiveChatModeratorsResource.InsertRequest request = this.connection.GoogleYouTubeService.LiveChatModerators.Insert(moderator, "snippet");
                return await request.ExecuteAsync();
            }));
        }
Example #28
0
        public async Task <VideoMetadataModel> GetUpcomingLiveAsync(CancellationToken cancellationToken)
        {
            _logger.LogTrace($"{GetType()} - BEGIN {nameof(GetUpcomingLiveAsync)}");

            LiveBroadcast res = await GetUpcomingLiveInternalAsync(cancellationToken);

            if (res != null)
            {
                VideoMetadataModel metadata = _mapper.Map <VideoMetadataModel>(res);
                metadata.VideoUrl = BuildVideoUrl(res.Id);

                return(metadata);
            }

            return(null);
        }
Example #29
0
        private async Task MessageBackgroundPolling()
        {
            while (!this.messageBackgroundPollingTokenSource.IsCancellationRequested)
            {
                try
                {
                    if (this.Broadcast != null)
                    {
                        LiveChatMessagesResultModel result = await this.connection.LiveChat.GetMessages(this.Broadcast);

                        if (result != null)
                        {
                            List <LiveChatMessage> newMessages = new List <LiveChatMessage>();
                            foreach (LiveChatMessage message in result.Messages)
                            {
                                if (!messageIDs.Contains(message.Id))
                                {
                                    newMessages.Add(message);
                                    messageIDs.Add(message.Id);
                                }
                            }

                            if (newMessages.Count > 0)
                            {
                                this.OnMessagesReceived?.Invoke(this, newMessages);
                            }

                            int pollingInterval = Math.Max((int)result.PollingInterval, this.minimumPollTimeMilliseconds);
                            await Task.Delay(pollingInterval);
                        }
                        else
                        {
                            await Task.Delay(10000);
                        }
                    }
                    else
                    {
                        this.Broadcast = await this.connection.LiveBroadcasts.GetMyActiveBroadcast();

                        await Task.Delay(60000);
                    }
                }
                catch (TaskCanceledException) { }
                catch (Exception ex) { Logger.Log(ex); }
            }
        }
Example #30
0
    public AjaxLB[] GetLB()
    {
        List <LiveBroadcast> LiveBroadcasts = LiveBroadcast.GetAllLiveBroadcastNOW2();

        AjaxLB[] AjaxLBs = new AjaxLB[LiveBroadcasts.Count];

        for (int i = LiveBroadcasts.Count - 1; i >= 0; i--)
        {
            AjaxLBs[i] = new AjaxLB();

            AjaxLBs[i].UniqueID     = LiveBroadcasts[i].WebLiveBroadcastID;
            AjaxLBs[i].ThumbnailURL = "http://www.next2friends.com/" + LiveBroadcasts[i].ThumbnailURL;
            AjaxLBs[i].Title        = LiveBroadcasts[i].Member.NickName + ":" + LiveBroadcasts[i].Member.ISOCountry;
        }

        return(AjaxLBs);
    }
        public async Task<ActionResult> IndexAsync(LiveStreamingModel liveModel, CancellationToken cancellationToken)
        {
            if (ModelState.IsValid)
            {
                HttpCookie newModel = new HttpCookie("liveModel");
                newModel.Value = new JavaScriptSerializer().Serialize(liveModel);
                newModel.Expires = DateTime.Now.AddHours(10);
                Response.Cookies.Add(newModel);
            }
            else 
            {
                if (Request.Cookies["liveModel"] != null)
                {
                    JavaScriptSerializer objJavascript = new JavaScriptSerializer();
                    liveModel = objJavascript.Deserialize<LiveStreamingModel>(Request.Cookies["liveModel"].Value);
                }
                else {
                    TempData["errorTitle"] = "Error";
                    TempData["errorMessage"] = "Something wrong! Please try again later!";
                    return RedirectToAction("Index", "Home", liveModel.eventID);
                }
            }
            
                var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
                AuthorizeAsync(cancellationToken);
                
                
                if (result.Credential != null)
                {
                    var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = result.Credential,
                        ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
                    });
                    LiveBroadcastSnippet broadcastSnippet = new LiveBroadcastSnippet();
                    broadcastSnippet.Title = liveModel.Title;
                    broadcastSnippet.ScheduledStartTime = liveModel.StartTimeYoutube.CompareTo(DateTime.Now) < 0 ? (DateTime.Now) : liveModel.StartTimeYoutube;
                    broadcastSnippet.ScheduledEndTime = liveModel.EndTimeYoutube;
                    // Set the broadcast's privacy status to "private". See:
                    // https://developers.google.com/youtube/v3/live/docs/liveBroadcasts#status.privacyStatus
                    LiveBroadcastStatus status = new LiveBroadcastStatus();
                    if (liveModel.PrivacyYoutube == EventZoneConstants.publicEvent)
                    {
                        status.PrivacyStatus = "public";
                    }
                    else if (liveModel.PrivacyYoutube == EventZoneConstants.unlistedEvent)
                    {
                        status.PrivacyStatus = "unlisted";
                    }
                    else { 
                        status.PrivacyStatus= "private";
                    }
                    //Set LiveBroadcast
                    LiveBroadcast broadcast = new LiveBroadcast();
                    LiveBroadcast returnBroadcast = new LiveBroadcast();
                    broadcast.Kind = "youtube#liveBroadcast";
                    broadcast.Snippet = broadcastSnippet;
                    broadcast.Status = status;
                    LiveBroadcastsResource.InsertRequest liveBroadcastInsert = youtubeService.LiveBroadcasts.Insert(broadcast, "snippet,status");
                    try
                    {
                        returnBroadcast = liveBroadcastInsert.Execute();
                    }
                    catch (Exception ex){
                        TempData["ErrorCreateLiveMessage"] = "Your youtube account can not create live streaming";
                        result.Credential.RevokeTokenAsync(CancellationToken.None).Wait();
                        return RedirectToAction("Details", "Event", new { id = liveModel.eventID });
                    }
                    
                    //Set LiveStream Snippet
                    LiveStreamSnippet streamSnippet = new LiveStreamSnippet();
                    streamSnippet.Title = liveModel.Title + "Stream Title";
                    CdnSettings cdnSettings = new CdnSettings();
                    cdnSettings.Format = liveModel.Quality;
                    cdnSettings.IngestionType = "rtmp";

                    //Set LiveStream
                    LiveStream streamLive = new LiveStream();
                    streamLive.Kind = "youtube#liveStream";
                    streamLive.Snippet = streamSnippet;
                    streamLive.Cdn = cdnSettings;
                    LiveStream returnLiveStream = youtubeService.LiveStreams.Insert(streamLive, "snippet,cdn").Execute();
                    LiveBroadcastsResource.BindRequest liveBroadcastBind = youtubeService.LiveBroadcasts.Bind(returnBroadcast.Id, "id,contentDetails");
                    liveBroadcastBind.StreamId = returnLiveStream.Id;
                    try
                    {
                        returnBroadcast = liveBroadcastBind.Execute();
                    }
                    catch (Exception ex)
                    {
                        TempData["ErrorCreateLiveMessage"] = "Your youtube account can not create live streaming";
                        result.Credential.RevokeTokenAsync(CancellationToken.None).Wait();
                        return RedirectToAction("Details", "Event", new { id = liveModel.eventID });
                    }
                    
                    //Return Value
                    String streamName = returnLiveStream.Cdn.IngestionInfo.StreamName;
                    String primaryServerUrl = returnLiveStream.Cdn.IngestionInfo.IngestionAddress;
                    String backupServerUrl = returnLiveStream.Cdn.IngestionInfo.BackupIngestionAddress;
                    String youtubeUrl = "https://www.youtube.com/watch?v=" + returnBroadcast.Id;
                    
                    //youtubeReturnModel model = new youtubeReturnModel { streamName = streamName, primaryServerUrl = primaryServerUrl,backupServerUrl=backupServerUrl,youtubeUrl=youtubeUrl };
                    Video video = new Video {  EventPlaceID = liveModel.EventPlaceID,
                                               VideoLink = youtubeUrl,
                                               PrimaryServer = primaryServerUrl,
                                               StartTime = liveModel.StartTimeYoutube,
                                               Privacy = liveModel.PrivacyYoutube,
                                               EndTime = liveModel.EndTimeYoutube,
                                               BackupServer = backupServerUrl,
                                               StreamName= streamName};
                    EventDatabaseHelper.Instance.AddVideo(video);
                    HttpCookie newModel = new HttpCookie("liveModel");
                    newModel.Value = new JavaScriptSerializer().Serialize(liveModel);
                    newModel.Expires = DateTime.Now.AddHours(-1);
                    Response.Cookies.Add(newModel);
                    result.Credential.RevokeTokenAsync(CancellationToken.None).Wait();
                    TempData["ErrorCreateLiveMessage"] = "Success";
                    return RedirectToAction("Details", "Event", new { id = EventDatabaseHelper.Instance.GetEventPlaceByID(liveModel.EventPlaceID).EventID });
            }
            else
            {
                return new RedirectResult(result.RedirectUri);
            }
        }
        /// <summary>
        /// Setup youtube channel. Needs to refine it all.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void LaunchPage_Loaded(object sender, RoutedEventArgs e)
        {
            //Move authorize to a common class
            user = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new Uri("ms-appx:///client_secret.json"),
                scope,
                "user",
                CancellationToken.None
            );

            youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = user,
                ApplicationName = "WatchMe"
            });

            //Individual youtube section to be moved to helper classes

            SearchResource.ListRequest listRequest = youtubeService.Search.List("snippet");
            listRequest.MaxResults = 10;
            listRequest.Q = "Microsoft";
            SearchListResponse searchResponse = await listRequest.ExecuteAsync();
            //YoutubePlayer.Source = new Uri("https://progressivemlx-a.akamaihd.net:443/asset-5f19445d-1500-80c4-d8fd-f1e5a5ddee3a/16914-237342-od1s011z.knj_H264_3400kbps_AAC_und_ch2_96kbps.mp4");
            //YoutubePlayer.Source = new Uri("https://www.youtube.com/v/V_XUSOLVRzA");
            //YoutubePlayer.Play();

            //Create broadcast snippet
            LiveBroadcastSnippet livebcSnippet = new LiveBroadcastSnippet();
            livebcSnippet.Title = "Hello Public Broadcast";
            livebcSnippet.ScheduledStartTime = DateTime.Now;
            livebcSnippet.ScheduledEndTime = DateTime.Now.AddHours(2);

            //Set broadcast privacy
            LiveBroadcastStatus livebcStatus = new LiveBroadcastStatus();
            livebcStatus.PrivacyStatus = "public";

            //Create Live Broadcast request combining the above parts
            LiveBroadcast liveBCRequest = new LiveBroadcast();
            liveBCRequest.Kind = "youtube#liveBroadcast";
            liveBCRequest.Snippet = livebcSnippet;
            liveBCRequest.Status = livebcStatus;

            //Create the live broadcast in youtube
            LiveBroadcastsResource.InsertRequest liveBCInsertRequest = youtubeService.LiveBroadcasts.Insert(liveBCRequest, "snippet,status");

            //Final Live Broadcast reponse
            LiveBroadcast liveBCResponse = await liveBCInsertRequest.ExecuteAsync();

            //Create liveStream snippet
            LiveStreamSnippet liveStreamSnippet = new LiveStreamSnippet();
            liveStreamSnippet.Title = "Live Video Public";

            // Define the content distribution network settings for the video stream.
            // The settings specify the stream's format and ingestion type.
            CdnSettings cdnSettings = new CdnSettings();
            cdnSettings.Format = "1080p";
            cdnSettings.IngestionType = "rtmp";

            //Create liveStream request
            LiveStream liveStreamRequest = new LiveStream();
            liveStreamRequest.Kind = "youtube#liveStream";
            liveStreamRequest.Snippet = liveStreamSnippet;
            liveStreamRequest.Cdn = cdnSettings;

            //Create the live stream in youtube
            LiveStreamsResource.InsertRequest liveStreamInsertRequest = youtubeService.LiveStreams.Insert(liveStreamRequest, "snippet,cdn");

            //Final Live Stream reponse
            LiveStream liveStreamResponse = await liveStreamInsertRequest.ExecuteAsync();

            // Construct and execute a request to bind the new broadcast and stream.
            LiveBroadcastsResource.BindRequest bindRequest = youtubeService.LiveBroadcasts.Bind(liveBCResponse.Id, "id,contentDetails");
            bindRequest.StreamId = liveStreamResponse.Id;

            // The LiveBroadcast object bound to the LiveStream
            LiveBroadcast boundBroadcast = await bindRequest.ExecuteAsync();

            App.RTMPUrl = liveStreamResponse.Cdn.IngestionInfo.IngestionAddress + "/" + liveStreamResponse.Cdn.IngestionInfo.StreamName;

            encoder = new RTMPEncoder();
            if (encoder.Ffmpeg_init(400, 300, AUDIO_SAMPLE_RATE, App.RTMPUrl))
            {
                Debug.WriteLine("encoder initialization successfull");
            }
            else
            {
                Debug.WriteLine("encoder initialization failed");
            }
            
            ChangeScenarioState(ScenarioState.Ready);
        }