//private void NewPlay(MyWebRequest req, TranslationStream url)
        //{
        //    string cid = url.Source;
        //    if (url.Type != SourceType.ContentId)
        //    {
        //        TorrentStream ts1 = new TorrentStream(req.Client);
        //        ts1.Connect();
        //        var respData = ts1.ReadTorrent(url.Source, url.Type);
        //        cid = ts1.GetContentId(respData);
        //    }
        //    var stream = _device.Proxy.GetStreamFromCID(cid, req.Parameters);
        //    var resp = req.GetResponse();
        //    //resp.AddHeader("Transfer-Encoding", "chunked");
        //    //resp.AddHeader("Content-Type", "video/mp2t");
        //    //resp.SendHeaders();
        //    //req.GetResponse().AddHeader("Transfer-Encoding", "chunked");
        //    SendHead(req);
        //    try
        //    {
        //        stream.CopyTo(req.GetResponse().GetStream());
        //    }
        //    catch
        //    {
        //        stream.Close();
        //    }
        //}

        public override void Play(MyWebRequest req)
        {
            int id = int.Parse(req.Parameters["id"].Split("#".ToCharArray(), 2)[0]);
            if (_device.Proxy.SessionState == null)
                throw new Exception("Необходима авторизация");
            var url = new TranslationStream(id).Run(_device.Proxy.SessionState.session);
            if (!url.IsSuccess)
            {
                if (url.Error == ApiError.incorrect)
                {
                    while (!_device.Proxy.Login() && _device.Proxy.SessionState.Error == ApiError.noconnect)
                    {
                        P2pProxyApp.Log.Write("Попыдка авторизации", TypeMessage.Info);
                    }
                    if (!_device.Proxy.SessionState.IsSuccess)
                        throw new Exception("No authorized");
                    Play(req);
                    return;
                }
                throw new Exception(url.error.ToString());
            }

            var ts = _device.Proxy.GetTsClient(url.Source);
            Task<string> waiter;
            if (ts == null)
            {
                if (!req.Client.Connected)
                    return;
                ts = new TorrentStream(req.Client);
                ts.Connect();
                waiter = ts.Play(url.Source, url.Type);

                if (waiter != null)
                    _device.Proxy.AddToTsPool(ts);
            }
            else
            {
                waiter = ts.GetPlayTask();
                ts.Owner.Add(req.Client);
            }

            if (waiter != null && !waiter.IsCompleted)
                waiter.Wait();
            else if (waiter == null)
                throw new FileNotFoundException();

            if (string.IsNullOrEmpty(waiter.Result))
            {
                _device.Proxy.RemoveFromTsPoos(ts);
                req.GetResponse().SendText("AceStream TimeOut");
                return;
            }
            string aceurl = waiter.Result;
            string file = string.Empty;
            try
            {
                Uri aceuri = new Uri(aceurl);

                var broadcast = _device.Proxy.Broadcaster.GetStream(aceurl, req.Parameters, req.Client);
                
                //file = _device.Proxy.FindBroadcastUrl(aceurl);
                //if (string.IsNullOrEmpty(file))
                //    file = _device.Proxy.StartBroadcastStream(aceurl,
                //        req.Parameters.ContainsKey("transcode") ? req.Parameters["transcode"] : "");

                //_device.Proxy.AddVlcBroadcastClient(file, req.Client);
                SendHead(req);
                try
                {
                    broadcast.CopyTo(req.GetResponse().GetStream());
                    //req.GetResponse().SendBroadcast(file);
                }
                catch
                {
                    
                }
                finally
                {
                    broadcast.Close();
                    req.Client.Close();
                    //if (req.Client.Connected)
                    //    req.Client.Close();
                    if (!_device.Proxy.Broadcaster.Contains(aceurl))
                    {
                        ts.Disconnect();
                        _device.Proxy.RemoveFromTsPoos(ts);
                    }
                }
                //if (_device.UpnpSettings.Profile.Live.SendHead)
                //    req.GetResponse().SendBroadcast(file, SendHead);
                //else
                //    req.GetResponse().SendBroadcast(file);
                
                //if (_device.Proxy.StopBroadcast(file, aceurl))
                //{
                //    ts.Disconnect();
                //    _device.Proxy.RemoveFromTsPoos(ts);
                //}
            }
            catch (Exception ex)
            {
                
                P2pProxyApp.Log.Write(ex.Message, TypeMessage.Error);
                ts.Disconnect();
                _device.Proxy.RemoveFromTsPoos(ts);
                _device.Proxy.Broadcaster.StopBroadcast(aceurl);
            }
        }
        //private void NewPlay(MyWebRequest req, TranslationStream url)
        //{
        //    string cid = url.Source;
        //    if (url.Type != SourceType.ContentId)
        //    {
        //        TorrentStream ts1 = new TorrentStream(req.Client);
        //        ts1.Connect();
        //        var respData = ts1.ReadTorrent(url.Source, url.Type);
        //        cid = ts1.GetContentId(respData);
        //    }
        //    var stream = _device.Proxy.GetStreamFromCID(cid, req.Parameters);
        //    var resp = req.GetResponse();
        //    //resp.AddHeader("Transfer-Encoding", "chunked");
        //    //resp.AddHeader("Content-Type", "video/mp2t");
        //    //resp.SendHeaders();
        //    //req.GetResponse().AddHeader("Transfer-Encoding", "chunked");
        //    SendHead(req);
        //    try
        //    {
        //        stream.CopyTo(req.GetResponse().GetStream());
        //    }
        //    catch
        //    {
        //        stream.Close();
        //    }
        //}

        public override void Play(MyWebRequest req)
        {
            int id = int.Parse(req.Parameters["id"].Split("#".ToCharArray(), 2)[0]);

            if (_device.Proxy.SessionState == null)
            {
                throw new Exception("Необходима авторизация");
            }
            var url = new TranslationStream(id).Run(_device.Proxy.SessionState.session);

            if (!url.IsSuccess)
            {
                if (url.Error == ApiError.incorrect)
                {
                    while (!_device.Proxy.Login() && _device.Proxy.SessionState.Error == ApiError.noconnect)
                    {
                        P2pProxyApp.Log.Write("Попыдка авторизации", TypeMessage.Info);
                    }
                    if (!_device.Proxy.SessionState.IsSuccess)
                    {
                        throw new Exception("No authorized");
                    }
                    Play(req);
                    return;
                }
                throw new Exception(url.error.ToString());
            }

            var           ts = _device.Proxy.GetTsClient(url.Source);
            Task <string> waiter;

            if (ts == null)
            {
                if (!req.Client.Connected)
                {
                    return;
                }
                ts = new TorrentStream(req.Client);
                ts.Connect();
                waiter = ts.Play(url.Source, url.Type);

                if (waiter != null)
                {
                    _device.Proxy.AddToTsPool(ts);
                }
            }
            else
            {
                waiter = ts.GetPlayTask();
                ts.Owner.Add(req.Client);
            }

            if (waiter != null && !waiter.IsCompleted)
            {
                waiter.Wait();
            }
            else if (waiter == null)
            {
                throw new FileNotFoundException();
            }

            if (string.IsNullOrEmpty(waiter.Result))
            {
                _device.Proxy.RemoveFromTsPoos(ts);
                req.GetResponse().SendText("AceStream TimeOut");
                return;
            }
            string aceurl = waiter.Result;
            string file   = string.Empty;

            try
            {
                Uri aceuri = new Uri(aceurl);

                var broadcast = _device.Proxy.Broadcaster.GetStream(aceurl, req.Parameters, req.Client);

                //file = _device.Proxy.FindBroadcastUrl(aceurl);
                //if (string.IsNullOrEmpty(file))
                //    file = _device.Proxy.StartBroadcastStream(aceurl,
                //        req.Parameters.ContainsKey("transcode") ? req.Parameters["transcode"] : "");

                //_device.Proxy.AddVlcBroadcastClient(file, req.Client);
                SendHead(req);
                try
                {
                    broadcast.CopyTo(req.GetResponse().GetStream());
                    //req.GetResponse().SendBroadcast(file);
                }
                catch
                {
                }
                finally
                {
                    broadcast.Close();
                    req.Client.Close();
                    //if (req.Client.Connected)
                    //    req.Client.Close();
                    if (!_device.Proxy.Broadcaster.Contains(aceurl))
                    {
                        ts.Disconnect();
                        _device.Proxy.RemoveFromTsPoos(ts);
                    }
                }
                //if (_device.UpnpSettings.Profile.Live.SendHead)
                //    req.GetResponse().SendBroadcast(file, SendHead);
                //else
                //    req.GetResponse().SendBroadcast(file);

                //if (_device.Proxy.StopBroadcast(file, aceurl))
                //{
                //    ts.Disconnect();
                //    _device.Proxy.RemoveFromTsPoos(ts);
                //}
            }
            catch (Exception ex)
            {
                P2pProxyApp.Log.Write(ex.Message, TypeMessage.Error);
                ts.Disconnect();
                _device.Proxy.RemoveFromTsPoos(ts);
                _device.Proxy.Broadcaster.StopBroadcast(aceurl);
            }
        }