Beispiel #1
0
 protected void ProcessSendTrackTimeUpdateResponse(HTTPRequestInfo requestInfo)
 {
     if (sendTrackTimeChangeWhenFinished >= 0)
     {
         int newPos = sendTrackTimeChangeWhenFinished;
         sendTrackTimeChangeWhenFinished = -1;
         SendTrackTimeUpdate(newPos);
     }
     else
     {
         ignoringTrackTimeChanges = false;
     }
 }
        /// <summary>
        /// Submits a HTTP request to the DACP server
        /// </summary>
        /// <param name="url">The URL request (e.g., "/server-info").</param>
        /// <param name="callback">If no callback is specified, the default HTTPByteCallback will be used.</param>
        internal HTTPRequestInfo SubmitHTTPRequest(string url, HTTPResponseHandler responseHandlerDelegate = null, bool isDataRetrieval = false, Action <HTTPRequestInfo> additionalSettings = null)
        {
            _log.Info("Submitting HTTP request for: " + url);

            try
            {
                // Set up HTTPWebRequest
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(HTTPPrefix + url);
                webRequest.Method = "POST";
                webRequest.Headers["Viewer-Only-Client"] = "1";

                // Create a new HTTPRequestState object
                HTTPRequestInfo requestInfo = new HTTPRequestInfo(webRequest);
                requestInfo.ResponseHandlerDelegate = responseHandlerDelegate;
                requestInfo.IsDataRetrieval         = isDataRetrieval;
                if (additionalSettings != null)
                {
                    additionalSettings(requestInfo);
                }

                // Send HTTP request
                webRequest.BeginGetResponse(new AsyncCallback(HTTPByteCallback), requestInfo);

                lock (PendingHttpRequests)
                    PendingHttpRequests.Add(requestInfo);

                if (isDataRetrieval)
                {
                    UpdateGettingData(true);
                }

                return(requestInfo);
            }
            catch (Exception e)
            {
                _log.Error("Caught exception: " + e.Message);
                StringBuilder errorString = new StringBuilder("Error creating HTTP Request:\r\n");
                errorString.AppendLine("URL: " + url);
                errorString.AppendLine(e.ToString());
                HandleConnectionError(errorString.ToString());
                return(null);
            }
        }
Beispiel #3
0
        protected void ProcessVolumeUpdateResponse(HTTPRequestInfo requestInfo)
        {
            if (sendVolumeChangeWhenFinished >= 0)
            {
                int newVolume = sendVolumeChangeWhenFinished;
                sendVolumeChangeWhenFinished = -1;

                if (sendExtendedVolumeChangeWhenFinished)
                {
                    SendExtendedVolumeUpdate(newVolume);
                }
                else
                {
                    SendSimpleVolumeUpdate(newVolume);
                }
            }
            else
            {
                ignoringVolumeChanges = false;
                Server.GetSpeakersIfNeeded();
            }
        }
        protected void HTTPByteCallback(IAsyncResult result)
        {
            // Get the HTTPRequestInfo object
            HTTPRequestInfo requestInfo = (HTTPRequestInfo)result.AsyncState;

            _log.Info("Got HTTP response for: " + requestInfo.WebRequest.RequestUri);

            try
            {
                WebResponse response = requestInfo.WebRequest.EndGetResponse(result);
                requestInfo.WebResponse = response as HttpWebResponse;

                if (!IsConnected)
                {
                    return;
                }

                Stream       responseStream = response.GetResponseStream();
                BinaryReader br             = new BinaryReader(responseStream);
                MemoryStream data           = new MemoryStream();
                byte[]       buffer;

                do
                {
                    buffer = br.ReadBytes(8192);
                    data.Write(buffer, 0, buffer.Length);
                } while (buffer.Length > 0);

                data.Flush();

                byte[] byteResult = data.GetBuffer();

                var parsedResponse = DACPUtility.GetResponseNodes(byteResult).FirstOrDefault();
                if (parsedResponse != null)
                {
                    requestInfo.ResponseCode = parsedResponse.Key;
                    requestInfo.ResponseBody = parsedResponse.Value;
                }

                if (requestInfo.ResponseHandlerDelegate != null)
                {
                    requestInfo.ResponseHandlerDelegate(requestInfo);
                }
            }
            catch (Exception e)
            {
                _log.Warning("Caught exception for {0}: {1}", requestInfo.WebRequest.RequestUri, e.Message);
                _log.Debug("Exception details: " + e.ToString());

                if (e is WebException)
                {
                    WebException webException = (WebException)e;

                    _log.Warning("Caught web exception: " + webException.Message);
                    _log.Debug("WebException Status: " + webException.Status.ToString());

                    if (webException.Status == WebExceptionStatus.RequestCanceled)
                    {
                        lock (PendingHttpRequests)
                        {
                            if (!PendingHttpRequests.Contains(requestInfo))
                            {
                                return;
                            }
                        }
                    }

                    if (requestInfo.ExceptionHandlerDelegate != null)
                    {
                        requestInfo.ExceptionHandlerDelegate(requestInfo, webException);
                        return;
                    }
                }
                StringBuilder errorString = new StringBuilder("HTTPByteCallback Error:\r\n");
                errorString.AppendLine("URL: " + requestInfo.WebRequest.RequestUri.GetPathAndQueryString());
                errorString.AppendLine(e.ToString());
                _log.Error("Unhandled web exception.");
                _log.Debug(errorString.ToString());
                HandleConnectionError(errorString.ToString());
            }
            finally
            {
                lock (PendingHttpRequests)
                    PendingHttpRequests.Remove(requestInfo);
                UpdateGettingData();
            }
        }
 private void HandlePlayTransportException(HTTPRequestInfo requestInfo, WebException e)
 {
     // Do nothing
 }
        protected void ProcessGetSpeakersResponse(HTTPRequestInfo requestInfo)
        {
            List <UInt64> foundSpeakerIDs = new List <UInt64>();

            string name;
            UInt64 id;
            bool   hasPassword;
            bool   hasVideo;
            bool   active;
            int    volume;

            foreach (var kvp in requestInfo.ResponseNodes)
            {
                if (kvp.Key == "mdcl")
                {
                    name        = string.Empty;
                    id          = 0;
                    hasPassword = false;
                    hasVideo    = false;
                    active      = false;
                    volume      = 0;

                    var speakerNodes = DACPUtility.GetResponseNodes(kvp.Value);

                    foreach (var speakerKvp in speakerNodes)
                    {
                        switch (speakerKvp.Key)
                        {
                        case "minm":     // Speaker name
                            name = speakerKvp.Value.GetStringValue();
                            break;

                        case "msma":     // Speaker ID
                            id = (UInt64)speakerKvp.Value.GetInt64Value();
                            break;

                        case "cahp":     // Has Password
                            hasPassword = (speakerKvp.Value[0] > 0);
                            break;

                        case "caiv":     // Has Video
                            hasVideo = true;
                            break;

                        case "caia":     // Speaker active
                            active = (speakerKvp.Value[0] > 0);
                            break;

                        case "cmvo":     // Speaker volume
                            volume = speakerKvp.Value.GetInt32Value();
                            break;

                        default:
                            break;
                        }
                    }

                    if (foundSpeakerIDs.Contains(id))
                    {
                        continue;
                    }

                    foundSpeakerIDs.Add(id);

                    AirPlaySpeaker speaker;

                    lock (Speakers)
                    {
                        speaker = Speakers.FirstOrDefault(s => s.ID == id);
                        if (speaker == null)
                        {
                            speaker          = new AirPlaySpeaker(this, id);
                            speaker.HasVideo = (hasVideo || id == 0);
                            ThreadUtility.RunOnUIThread(() => Speakers.Add(speaker));
                        }
                    }

                    speaker.HasPassword = hasPassword;
                    speaker.Name        = name;
                    speaker.Active      = active;
                    speaker.Volume      = volume;
                    speaker.WaitingForActiveResponse = false;
                }
            }

            lock (Speakers)
            {
                // Handle speakers that are no longer available
                // Need to call ToList() so the source collection doesn't change during enumeration
                var removedSpeakers = Speakers.Where(s => !foundSpeakerIDs.Contains(s.ID)).ToList();
                foreach (AirPlaySpeaker removedSpeaker in removedSpeakers)
                {
                    ThreadUtility.RunOnUIThread(() => Speakers.Remove(removedSpeaker));
                }
            }

            SendAirPlaySpeakerUpdate();
            gettingSpeakers = false;
        }
 protected void ProcessSetActiveSpeakersResponse(HTTPRequestInfo requestInfo)
 {
     SubmitGetSpeakersRequest();
 }
 protected void HandleSetActiveSpeakersException(HTTPRequestInfo requestInfo, WebException e)
 {
     // TODO
     //SendServerUpdate(ServerUpdateType.AirPlaySpeakerPassword);
     SubmitGetSpeakersRequest();
 }