Ejemplo n.º 1
0
        private void StatRequest(MyWebRequest req)
        {
            StringBuilder sb = new StringBuilder("<html><head><meta http-equiv=\"Refresh\" content=\"30\" /><title>Статистика</title></head><body>");
            sb.Append("<h1>Версия приложения:</h1>");
            sb.Append(Assembly.GetExecutingAssembly().ManifestModule.Assembly);
            sb.Append("<h1>Статистика бродкаста</h1>");
            sb.Append("<table border=1><tr><td><b>Трансляция</b></td><td><b>Количество подключений</b></td></tr>");

            var broads = Proxy.Broadcaster.GetBroadcasts();
            foreach (var broad in broads)
            {
                sb.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", broad, Proxy.Broadcaster.GetClientConnected(broad));
            }
            
            sb.Append("</table><h1>Статистика VL VoD</h1><table border=1>");
            sb.Append("<tr><td><b>URL-источника</b></td><td><b>VLC VoD URL</b></td></tr>");

            sb.Append("</table></body></html>");
            var res = Encoding.UTF8.GetBytes(sb.ToString());
            var resp = req.GetResponse();
            resp.AddHeader(HttpHeader.ContentType, WebServer.GetMime(".html").ToString());
            resp.AddHeader(HttpHeader.ContentLength, res.Length.ToString());
            resp.SendHeaders();
            resp.GetStream().Write(res, 0, res.Length);
        }
Ejemplo n.º 2
0
 public override string GetPlaylist(MyWebRequest req)
 {
     int id = 0;
     if (req.Parameters.ContainsKey("id"))
         id = int.Parse(req.Parameters["id"]);
     return new StreamReader(new TranslationEpg(id).Execute(_device.Proxy.SessionState.session, TypeResult.Xml)).ReadToEnd();
 }
Ejemplo n.º 3
0
        private void UpdatePlaylist(MyWebRequest req)
        {

            if (_lastUpdate + _maxAge < DateTime.Now)
            {
                
                DateTime date = req.Parameters.ContainsKey("date") ? ParseDateTime(req.Parameters["date"]) : DateTime.Today;
                _channels = new ArcList().Run(_device.Proxy.SessionState.session);
                _channels.channels.RemoveAll(c => _device.Filter.Check("ttv").Find("ch" + c.id).Check());
                if (req.Parameters.ContainsKey("channel_id"))
                {
                    int channel_id = int.Parse(req.Parameters["channel_id"]);
                    var ch = _channels.channels.FirstOrDefault(c => c.epg_id == channel_id);
                    if (ch != null)
                        _records = new ArcRecords(ch == null ? 0 : ch.epg_id, date).Run(_device.Proxy.SessionState.session);
                    else
                        throw new FileNotFoundException();
                }
                else
                {
                    _records = new ArcRecords(0, date).Run(_device.Proxy.SessionState.session);
                    var groups = _records.records.GroupBy(r => r.epg_id).ToArray();
                    foreach (var kp in groups)
                    {
                        var ch = _channels.channels.Where(c => c.epg_id == kp.Key);
                        if (!ch.Any())
                            _records.records.RemoveAll(r => r.epg_id == kp.Key);
                    }
                }
                    
                    
            }

            if (!_channels.IsSuccess && !_records.IsSuccess)
            {
                if (_channels.Error == ApiError.incorrect || _channels.Error == ApiError.noconnect ||
                    _records.Error == ApiError.incorrect || _records.Error == ApiError.noconnect)
                {
                    while (!_device.Proxy.Login() || _device.Proxy.SessionState.Error == ApiError.noconnect)
                    {
                    }
                    if (!_device.Proxy.SessionState.IsSuccess)
                    {
                        throw new Exception("Ошибка подключения");
                    }
                    UpdatePlaylist(req);
                }
                else
                    switch (_records.Error)
                    {
                        case ApiError.norecord:
                            throw new Exception("Нет записей");
                        case ApiError.noconnect:
                            throw new Exception("ошибка соединения с БД");
                        case ApiError.noparam:
                            throw new Exception("ошибка входных параметров");
                    }
            }
        }
Ejemplo n.º 4
0
 private void StopRequest(MyWebRequest req)
 {
     if (!req.Parameters.ContainsKey("id"))
     {
         _device.Web.Send404(req);
         return;
     }
     Stop(req.Parameters["id"]);
     req.GetResponse().SendText("OK");
 }
Ejemplo n.º 5
0
 private void AddFavouriteRequest(MyWebRequest req)
 {
     int id = int.Parse(req.Parameters["id"].Split("#".ToCharArray(), 2)[0]);
     var res = new FavouriteAdd(id).Execute(_device.Proxy.SessionState.session, TypeResult.Xml);
     var resp = req.GetResponse();
     resp.AddHeader(HttpHeader.ContentType, WebServer.GetMime(".json").ToString());
     resp.AddHeader(HttpHeader.ContentLength, res.Length.ToString());
     resp.SendHeaders();
     res.CopyTo(resp.GetStream());
 }
Ejemplo n.º 6
0
        public void SendFile(MyWebRequest req, string fpath)
        {
            if (!File.Exists(fpath))
            {
                Send404(req);
            }
            FileStream stream = File.OpenRead(fpath);
            var        resp   = req.GetResponse();

            resp.AddHeader(HttpHeader.ContentType, _mimes[Path.GetExtension(fpath)].ToString());
            resp.AddHeader(HttpHeader.ContentLength, stream.Length.ToString());
            stream.CopyTo(resp.GetStream());
        }
Ejemplo n.º 7
0
        public void SendResponse(MyWebRequest req)
        {
            string res;
            try
            {
                res = GetPlaylist(req);
            }
            catch (Exception ex)
            {
                res = ex.Message;
            }

            MyWebResponse resp = req.GetResponse();
            resp.SendText(res);
        }
Ejemplo n.º 8
0
        public void Send404(MyWebRequest req)
        {
            var resp = req.GetResponse();

            resp.AddHeader(HttpHeader.ContentType, "text/html; charset=UTF-8");
            byte[] msg = Encoding.UTF8.GetBytes("<h1>404. Файл не найден</h1>");
            resp.AddHeader(HttpHeader.ContentLength, msg.Length.ToString());
            resp.SendHeaders();
            try
            {
                resp.GetStream().Write(msg, 0, msg.Length);
            }
            catch (Exception ex)
            {
                P2pProxyApp.Log.Write(ex.Message, TypeMessage.Error);
            }
        }
Ejemplo n.º 9
0
 private void Request(MyWebRequest req)
 {
     if (!req.Headers.ContainsKey("id"))
     {
         _server.Send404(req);
         return;
     }
     TcpClient client = new TcpClient("127.0.0.1", AceStream31.WebASPort);
     var stream = client.GetStream();
     Uri uri = new Uri(Acestream.Play(req.Headers["id"]));
     var sendreq = Encoding.UTF8.GetBytes(string.Format("GET {0}{1}\r\nHost: {2}:{3}\r\nConnection: Keep-Alive\r\n\r\n", uri.PathAndQuery, uri.Host, uri.Port));
     stream.Write(sendreq, 0, sendreq.Length);
     var resp = req.GetResponse();
     resp.AddHeader("Content-Type", "application/octet-stream");
     resp.AddHeader("Cache-control", "no-cache");
     resp.SendHeaders();
     stream.CopyTo(resp.GetStream());
 }
Ejemplo n.º 10
0
 private void AddRequest(MyWebRequest req)
 {
     if (!req.Parameters.ContainsKey("channel_id"))
     {
         _device.Web.Send404(req);
         return;
     }
     Channel ch = _device.ChannelsProvider.GetChannels().FirstOrDefault(channel => channel.id == int.Parse(req.Parameters["channel_id"]));
     if (ch == null)
     {
         _device.Web.Send404(req);
         return;
     }
     DateTime start = !req.Parameters.ContainsKey("start") ? DateTime.Now : ParseDateTime(req.Parameters["start"]);
     DateTime end = !req.Parameters.ContainsKey("end") ? DateTime.Today.AddDays(1).AddTicks(-1) : ParseDateTime(req.Parameters["end"]);
     Add(ch, start, end, req.Parameters.ContainsKey("name") ? req.Parameters["name"] : string.Empty);
     req.GetResponse().SendText("OK");
     
 }
Ejemplo n.º 11
0
 private void GetChannelsRequest(MyWebRequest req)
 {
     var resp = req.GetResponse();
     resp.AddHeader(HttpHeader.ContentType, WebServer.GetMime(".xml").ToString());
     var res = new ArcList().Execute(_device.Proxy.SessionState.session, TypeResult.Xml);
     XDocument xd = XDocument.Load(res);
     var xchs = xd.Root.Element("channels").Elements().ToArray();
     foreach (var xch in xchs)
     {
         if (_device.Filter.Check("ttv").Find("ch" + xch.Attribute("id").Value).Check())
             xch.Remove();
     }
     MemoryStream ms = new MemoryStream();
     xd.Save(ms);
     ms.Position = 0;
     resp.AddHeader(HttpHeader.ContentLength, ms.Length.ToString());
     resp.SendHeaders();
     ms.CopyTo(resp.GetStream());
 }
Ejemplo n.º 12
0
        private void SendHead(MyWebRequest obj)
        {
            var info =
                _device.UpnpSettings.Profile.VoD.Info.FirstOrDefault(i => i.FileExt.Equals(".ts", StringComparison.OrdinalIgnoreCase)) ??
                _device.UpnpSettings.Profile.VoD.Info[0];
            var resp = obj.GetResponse();
            resp.AddHeader(HttpHeader.ContentType, WebServer.GetMime(".ts").ToString());
            if (_device.UpnpSettings.Profile.Live.SendContentLength)
                resp.AddHeader(HttpHeader.ContentLength, "50000000000");
            resp.AddHeader(HttpHeader.AcceptRanges, "none");
            resp.AddHeader(HttpHeader.Date, DateTime.Now.ToString("r"));
            resp.AddHeader(HttpHeader.Server, String.Format("{0}/{1}.{2} UPnP/1.1 TestDlna/{3}", Environment.OSVersion.Platform, Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor, _device.ModelNumber));
            resp.AddHeader("Cache-control", "no-cache");
            resp.AddHeader("contentFeatures.dlna.org", info.DlnaType + info.Feature);
            resp.AddHeader("transferMode.dlna.org", "Streaming");
            resp.AddHeader("realTimeInfo.dlna.org", "DLNA.ORG_TLAG=*");
            resp.SendHeaders();

        }
Ejemplo n.º 13
0
        private void Browse(MyWebRequest request,
            [ObfuscationAttribute][UpnpServiceArgument("A_ARG_TYPE_ObjectID")][AliasAttribute("ObjectID")] string ObjectID,
            [ObfuscationAttribute][UpnpServiceArgument("A_ARG_TYPE_BrowseFlag")][AliasAttribute("BrowseFlag")] string BrowseFlag,
            [ObfuscationAttribute][UpnpServiceArgument("A_ARG_TYPE_Filter")][AliasAttribute("Filter")] string Filter,
            [ObfuscationAttribute][UpnpServiceArgument("A_ARG_TYPE_Index")][AliasAttribute("StartingIndex")] string StartingIndex,
            [ObfuscationAttribute][UpnpServiceArgument("A_ARG_TYPE_Count")][AliasAttribute("RequestedCount")] string RequestedCount,
            [ObfuscationAttribute][UpnpServiceArgument("A_ARG_TYPE_SortCriteria")] [AliasAttribute("SortCriteria")] string SortCriteria)
        {

            string Result = "", NumberReturned = "", TotalMatches = "";
            uint startingIndex, requestedCount;
            BrowseFlag browseFlag;
            
            if (!uint.TryParse(StartingIndex, out startingIndex) || !uint.TryParse(RequestedCount, out requestedCount) ||
                !Enum.TryParse(BrowseFlag, true, out browseFlag))
            {
                if (P2pProxyApp.Debug)
                {
                    Console.WriteLine("Invalid Args");
                }
                throw new SoapException(402, "Invalid Args");
            }
                

            SortCriteria = (SortCriteria == string.Empty) ? "+dc:title" : SortCriteria;
            try
            {
                this.device.ItemManager.Browse(request.Headers, ObjectID, browseFlag, Filter, startingIndex, requestedCount,
                                           SortCriteria, out Result, out NumberReturned, out TotalMatches);
            }
            catch (Exception ex)
            {
                P2pProxyApp.Log.Write(string.Format("Content::Browse({0}) - {1}", ObjectID, ex.Message), TypeMessage.Error);
                return;
            }
            

            MyWebResponse response = request.GetResponse();
            response.SendSoapHeadersBody(Result, NumberReturned, TotalMatches, "0");
        }
Ejemplo n.º 14
0
        private void ClientReceived(object o)
        {
            var client = (TcpClient)o;

            if (client.Connected)
            {
                MyWebRequest msg = null;
                try
                {
                    msg = MyWebRequest.Create(client);
                    if (msg.Url != null)
                    {
                        if (P2pProxyApp.Debug)
                        {
                            P2pProxyApp.Log.Write(string.Format("WebServer::ClientRequest({0}): {1}", msg.Client.Client.RemoteEndPoint, msg.Url), TypeMessage.Info);
                        }
                        if (_routers.ContainsKey(msg.Method + "_" + msg.Url))
                        {
                            _routers[msg.Method + "_" + msg.Url].Invoke(msg);
                        }
                        else
                        {
                            Send404(msg);
                        }
                    }
                }
                catch (SoapException ex)
                {
                    MyWebResponse response = msg.GetResponse();
                    try { response.SendSoapErrorHeadersBody(ex.Code, ex.Message); }
                    catch { }
                }
                catch (Exception ex)
                {
                    P2pProxyApp.Log.Write(string.Format("WebServer::ClientRequest({0}):{1}", msg != null ? msg.Url + "?" + msg.QueryString : "", ex.Message), TypeMessage.Error);
                }
                finally
                { client.Close(); }
            }
        }
Ejemplo n.º 15
0
 private void GetSearchCapabilities(MyWebRequest request)
 {
     MyWebResponse response = request.GetResponse();
     response.SendSoapHeadersBody("");
 }
Ejemplo n.º 16
0
        public override string GetPlaylist(MyWebRequest req)
        {
            var plugpath = GetPluginFromPath(req.Url);
            var plugin = _plugins.FirstOrDefault(p => plugpath == p.Id);
            if (plugin == null)
                return "Plugin not found";
            var container = plugin.GetContent(req.Parameters) as IPluginContainer;
            if (container == null)
                return "No data";
            if (req.Parameters.ContainsKey("type"))
            {
                Playlist pl = Playlist.CreatePlaylist(req.Parameters["type"], req.Headers["host"], Playlist.ContentType.Plugin);
                var content = container.Children.Where(c => !_device.Filter.Check(plugin.Id).Check(c.Id).Check());
                
                if (req.Parameters.ContainsKey("sort") && container.CanSorted)
                {
                    switch (req.Parameters["sort"])
                    {
                        case "title":
                            content = content.OrderBy(item => item.Title).ToList();
                            break;
                        case "-title":
                            content = content.OrderByDescending(item => item.Title).ToList();
                            break;
                        case "id":
                            content = content.OrderBy(item => item.Id).ToList();
                            break;
                        case "-id":
                            content = content.OrderByDescending(item => item.Id).ToList();
                            break;
                        default:
                            content = container.OrderBy(req.Parameters["sort"]).ToList();
                            break;
                    }
                }
                foreach (var item in content)
                {
                    if (item is IPluginContainer)
                    {

                        var it = new VirtualContainer
                        {
                            Title = item.Title,
                            Id = item.Id,
                            Parent = item.Parent,
                            Url =
                                !string.IsNullOrEmpty(item.GetUrl(req.Headers["host"]))
                                    ? item.GetUrl(req.Headers["host"])
                                    : string.Format("http://{0}/{1}/?id={2}&type=m3u", req.Headers["host"], plugin.Id,
                                        item.Id)
                        };

                        pl.AddLine(it, true, req.Parameters.ContainsKey("transcode") ? req.Parameters["transcode"] : "");
                    }
                    else
                    {

                        var it = VirtualItem.Copy(item);
                        it.Url = string.Format("http://{0}/{1}/play?id={2}", req.Headers["host"], plugin.Id, item.Id);
                        pl.AddLine(it, append: req.Parameters.ContainsKey("transcode") ? req.Parameters["transcode"] : "");

                    }
                }
                return pl.ToString();
            }

            return GetXDocument(container, plugin.Id, true).ToString();
        }
Ejemplo n.º 17
0
 private void HttpRequest(MyWebRequest req)
 {
     string[] url = req.Url.Split("/".ToCharArray(), 2, StringSplitOptions.RemoveEmptyEntries);
     var plugin = _plugins.FirstOrDefault(proxy => proxy.Id == url[0]);
     if (plugin == null)
     {
         _device.Web.Send404(req);
         return;
     }
     var res = plugin.HttpRequest(url[1], req.Parameters);
     var resp = req.GetResponse();
     foreach (var header in res.Headers)
         resp.AddHeader(header.Key, header.Value);
     resp.SendHeaders(res.ResultState);
     res.GetStream().CopyTo(resp.GetStream());
 }
Ejemplo n.º 18
0
 private void SendHeaders(MyWebRequest req, string ext)
 {
     var info =
         _device.UpnpSettings.Profile.Live.Info.FirstOrDefault(i => i.FileExt.Equals(ext, StringComparison.OrdinalIgnoreCase)) ??
         _device.UpnpSettings.Profile.Live.Info[0];
     var resp = req.GetResponse();
     resp.AddHeader(HttpHeader.ContentType, WebServer.GetMime(".ts").ToString());
     if (!resp.HeaderContains(HttpHeader.ContentLength) && _device.UpnpSettings.Profile.Live.SendContentLength)
         resp.AddHeader(HttpHeader.ContentLength, "2500000000");
     if (!resp.HeaderContains(HttpHeader.AcceptRanges))
         resp.AddHeader(HttpHeader.AcceptRanges, "none");
     resp.AddHeader("Cache-control", "no-cache");
     resp.AddHeader("contentFeatures.dlna.org", info.DlnaType + info.Feature);
     resp.AddHeader("transferMode.dlna.org", "Streaming");
     resp.AddHeader("realTimeInfo.dlna.org", "DLNA.ORG_TLAG=*");
     resp.SendHeaders();
 }
Ejemplo n.º 19
0
        //private void PlayNew(MyWebRequest req, ArcStream 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.Broadcaster.GetSource(cid);
        //    req.GetResponse().SendFile(stream);
        //}

        public override void Play(MyWebRequest req)
        {
            locker.isSet = true;
            int id = int.Parse(req.Parameters["id"].Split("#".ToCharArray(), 2)[0]);
            var url = new ArcStream(id).Run(_device.Proxy.SessionState.session);
            if (!url.IsSuccess)
            {
                while (!_device.Proxy.Login() && _device.Proxy.SessionState.Error == ApiError.noconnect)
                {

                }
                if (!_device.Proxy.SessionState.IsSuccess)
                    throw new Exception("No authorized");
                Play(req);
                return;
            }
            var ts = _device.Proxy.GetTsClient(url.source);
            Task<string> waiter;
            
            try
            {
                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[0].Close();
                    ts.Owner.Add(req.Client);
                    ts.Owner.RemoveAt(0);
                
                }
                locker.isSet = false;
                if (waiter != null && !waiter.IsCompleted)
                    waiter.Wait();
                else if (waiter == null)
                    throw new FileNotFoundException();

                if (string.IsNullOrEmpty(waiter.Result))
                {
                    _device.Proxy.RemoveFromTsPoos(ts);
                }
                while (plaing) Thread.Sleep(256);
                plaing = true;
                req.GetResponse().SendFile(waiter.Result);
                plaing = false;
                do Thread.Sleep(512);
                while (locker.isSet); 
                if (ts.Owner.All(c => !c.Connected))
                {
                        
                    ts.Disconnect();
                    _device.Proxy.RemoveFromTsPoos(ts);
                    //GC.Collect();
                }
                
            }
            catch (Exception ex)
            {
                P2pProxyApp.Log.Write(ex.Message, TypeMessage.Error);
                ts.Disconnect();
                _device.Proxy.RemoveFromTsPoos(ts);
                plaing = false;
            }
            
        }
Ejemplo n.º 20
0
        private void GetCurrentConnectionInfo(MyWebRequest request,
            [AliasAttribute("ConnectionID")][UpnpServiceArgument("A_ARG_TYPE_ConnectionID")] string ConnectionID)
        {
            if (ConnectionID != "0")
                throw new SoapException(402, "Invalid Args");

            MyWebResponse response = request.GetResponse();
            response.SendSoapHeadersBody("-1", "-1", string.Empty, string.Empty, "-1", "Output", "OK");
        }
Ejemplo n.º 21
0
        public override void Play(MyWebRequest req)
        {

            if (!req.Parameters.ContainsKey("id"))
                return;
            var plugpath = GetPluginFromPath(req.Url);
            var plugin = _plugins.FirstOrDefault(p => plugpath == p.Id);
            if (plugin != null)
            {
                
                var content = plugin.GetContent(req.Parameters);
                if (content == null || content is IPluginContainer)
                    return;
                var source = content.GetSourceUrl();

                if (source.Type == SourceType.ContentId || source.Type == SourceType.Torrent)
                {
                    var ts = GetContentUrl(source, req);
                    string url = ts.GetPlayTask().Result;
                    if (ts == null || string.IsNullOrEmpty(url))
                    {
                        ts.Disconnect();
                        req.GetResponse().SendText("File Not Found");
                        return;
                    }
                    TorrentStream ts1 = new TorrentStream(req.Client);
                    ts1.Connect();
                    var resp = ts1.ReadTorrent(source.Url, (TTVApi.SourceType) (byte) source.Type);
                    string file = resp.Files[req.Parameters.ContainsKey("index") ? int.Parse(req.Parameters["index"]) : 0];
                    string ext = Path.GetExtension(file);
                    ts1.Disconnect();
                    if (content.Translation == TranslationType.Broadcast)
                        SendBroadcast(url, req, ext);
                    else if (content.Translation == TranslationType.VoD)
                    {
                        for (int i = 0; i < ts.Owner.Count && ts.Owner.Count > 1; i++)
                            ts.Owner[i].Close();
                        SendFile(url, req, ext);
                    }
                    Thread.Sleep(5712);
                    if (ts.Owner.All(c => !c.Connected))
                    {
                        if (content.Translation == TranslationType.Broadcast && !_device.Proxy.Broadcaster.Contains(url) ||
                            content.Translation == TranslationType.VoD)
                        {
                            ts.Disconnect();
                            _device.Proxy.RemoveFromTsPoos(ts);
                        }
                    }
                }
                else if (source.Type == SourceType.File)
                {
                    string ext = Path.GetExtension(source.Url);
                    if (content.Translation == TranslationType.Broadcast)
                        SendBroadcast(source.Url, req, ext);
                    else if (content.Translation == TranslationType.VoD)
                        SendFile(source.Url, req, ext);
                }
            }
        }
Ejemplo n.º 22
0
 internal MyWebResponse(MyWebRequest req, NetworkStream stream)
 {
     _request = req;
     _stream  = stream;
     _headers = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
 }
Ejemplo n.º 23
0
 private void GetSortCapabilities(MyWebRequest request)
 {
     MyWebResponse response = request.GetResponse();
     response.SendSoapHeadersBody("dc:title,dc:date");
 }
Ejemplo n.º 24
0
        //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);
            }
        }
Ejemplo n.º 25
0
        public override string GetPlaylist(MyWebRequest req)
        {
            if (req.Parameters.ContainsKey("type"))
            {
                try
                {
                    UpdateTranslations(req.Parameters, req.QueryString);
                }
                catch (Exception e)
                {
                    return e.Message;
                }

                Playlist pl = Playlist.CreatePlaylist(req.Parameters["type"], req.Headers["host"], Playlist.ContentType.Channel);
                
                List<Channel> channels;
                if (req.Parameters.ContainsKey("group"))
                {
                    var groups = req.Parameters["group"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(byte.Parse).OrderBy(b => b);
                    channels = _apires.channels.Where(channel => groups.Contains(channel.group)).ToList();
                } else { channels = _apires.channels; }
                if (req.Parameters.ContainsKey("sort"))
                {
                    switch (req.Parameters["sort"])
                    {
                        case "group":
                            channels = channels.OrderBy(channel => channel.group).ToList();
                            break;
                        case "-group":
                            channels = channels.OrderByDescending(channel => channel.group).ToList();
                            break;
                        case "title":
                            channels = channels.OrderBy(channel => channel.name).ToList();
                            break;
                        case "-title":
                            channels = channels.OrderByDescending(channel => channel.name).ToList();
                            break;
                        case "id":
                            channels = channels.OrderBy(channel => channel.id).ToList();
                            break;
                        case "-id":
                            channels = channels.OrderByDescending(channel => channel.id).ToList();
                            break;
                    }
                }
                foreach (var ch in channels)
                {
                    if (!_device.Filter.Check("ttv").Check("cat" + ch.group).HasChild())
                        continue;
                    if (!_device.Filter.Check("ttv").Check("cat"+ch.group).Check("ch"+ch.id).Check())
                        pl.AddLine(ch, false, req.Parameters.ContainsKey("transcode") ? "&transcode=" + req.Parameters["transcode"] : "");
                }
                return pl.ToString();
            }
            FilterType type = req.Parameters.ContainsKey("filter") ? (FilterType)Enum.Parse(typeof(FilterType), req.Parameters["filter"], true) : FilterType.all;
            var stream = new TranslationList(type).Execute(_device.Proxy.SessionState.session, TypeResult.Xml);
            XDocument xd = XDocument.Load(stream);
            var xchs = xd.Root.Element("channels").Elements().ToArray();
            foreach (var xch in xchs)
            {
                if (_device.Filter.Check("ttv").Check("cat" + xch.Attribute("group").Value).Check() && !_device.Filter.Check("ttv").Check("cat" + xch.Attribute("group").Value).HasChild())
                    xch.Remove();
                else if (_device.Filter.Check("ttv").Check("cat" + xch.Attribute("group").Value).Check("ch" + xch.Attribute("id").Value).Check())
                    xch.Remove();

            }
            return xd.ToString();
        }
Ejemplo n.º 26
0
 private void GetProtocolInfo(MyWebRequest request)
 {
     MyWebResponse response = request.GetResponse();
     response.SendSoapHeadersBody(sourceProtocolInfo, string.Empty);
 }
Ejemplo n.º 27
0
 private void SendFile(string url, MyWebRequest req, string ext)
 {
     
     var info =
         _device.UpnpSettings.Profile.Live.Info.FirstOrDefault(i => i.FileExt.Equals(ext, StringComparison.OrdinalIgnoreCase)) ??
         _device.UpnpSettings.Profile.Live.Info[0];
     var resp = req.GetResponse();
     var mime = WebServer.GetMime(ext) ?? WebServer.GetMime(".ts");
     resp.AddHeader(HttpHeader.ContentType, mime.ToString());
     resp.AddHeader("Cache-control", "no-cache");
     resp.AddHeader("contentFeatures.dlna.org", info.DlnaType + info.Feature);
     resp.AddHeader("transferMode.dlna.org", "Streaming");
     resp.AddHeader("realTimeInfo.dlna.org", "DLNA.ORG_TLAG=*");
     resp.SendFile(url);
 }
Ejemplo n.º 28
0
 private void GetCurrentConnectionIDs(MyWebRequest request)
 {
     MyWebResponse response = request.GetResponse();
     response.SendSoapHeadersBody("0");
 }
Ejemplo n.º 29
0
        public TorrentStream GetContentUrl(SourceUrl url, MyWebRequest req)
        {
            //locker.isSet = true;
            if (url.Type == SourceType.Torrent)
                url.Url = new Uri(url.Url, UriKind.Absolute).ToString();
            var ts = _device.Proxy.GetTsClient(url.Url);
            Task<string> waiter;
            try
            {
                if (ts == null)
                {
                    if (!req.Client.Connected)
                        return null;
                    ts = new TorrentStream(req.Client);
                    ts.Connect();
                    waiter = ts.Play(url.Url, (TTVApi.SourceType)(byte)url.Type, req.Headers.ContainsKey("index") ? int.Parse(req.Headers["index"]) : 0);

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

                if (waiter != null && !waiter.IsCompleted)
                    waiter.Wait();
                else if (waiter == null)
                    throw new FileNotFoundException();
                if (string.IsNullOrEmpty(waiter.Result))
                {
                    _device.Proxy.RemoveFromTsPoos(ts);
                }
                return ts;
            }
            catch (Exception ex)
            {
                P2pProxyApp.Log.Write(ex.Message, TypeMessage.Error);
                ts.Disconnect();
                _device.Proxy.RemoveFromTsPoos(ts);
                plaing = false;
                locker.isSet = false;
                return null;
            }
        }
Ejemplo n.º 30
0
 public override string GetPlaylist(MyWebRequest req)
 {
     try
     {
         UpdatePlaylist(req);
     }
     catch (Exception e)
     {
         return e.Message;
     }
     if (req.Parameters.ContainsKey("type"))
     {
         Playlist pl = Playlist.CreatePlaylist(req.Parameters["type"], req.Headers["host"], Playlist.ContentType.Archive);
         List<Record> arcs = new List<Record>();
         arcs.AddRange(_records.records);
         if (req.Parameters.ContainsKey("sort"))
         {
             switch (req.Parameters["sort"])
             {
                 case "channel":
                     arcs = arcs.OrderBy(arc => arc.epg_id).ToList();
                     break;
                 case "-channel":
                     arcs = arcs.OrderByDescending(arc => arc.epg_id).ToList();
                     break;
                 case "title":
                     arcs = arcs.OrderBy(arc => arc.name).ToList();
                     break;
                 case "-title":
                     arcs = arcs.OrderByDescending(arc => arc.name).ToList();
                     break;
                 case "id":
                     arcs = arcs.OrderBy(arc => arc.record_id).ToList();
                     break;
                 case "-id":
                     arcs = arcs.OrderByDescending(arc => arc.record_id).ToList();
                     break;
                 case "datetime":
                     arcs = arcs.OrderBy(arc => arc.Time).ToList();
                     break;
                 case "-datetime":
                     arcs = arcs.OrderByDescending(arc => arc.Time).ToList();
                     break;
             }
         }
         _records.CastChannels(_channels.channels);
         foreach (var ch in arcs)
         {
             if (ch.Channel != null)
                 pl.AddLine(ch, append: req.Parameters.ContainsKey("transcode") ? "&transcode=" + req.Parameters["transcode"] : "");
         }
         return pl.ToString();
     }
     DateTime date = req.Parameters.ContainsKey("date") ? ParseDateTime(req.Parameters["date"]) : DateTime.Today;
     var res = new ArcRecords(req.Parameters.ContainsKey("channel_id") ? int.Parse(req.Parameters["channel_id"]) : 0, date).Execute(_device.Proxy.SessionState.session, TypeResult.Xml);
     XDocument xd = XDocument.Load(res);
     var xchs = xd.Root.Element("records").Elements().GroupBy(e => int.Parse(e.Attribute("epg_id").Value)).ToArray();
     foreach (var xch in xchs)
     {
         if (!_channels.channels.Any(c => c.epg_id == xch.Key))
             xch.Remove();
     }
     return xd.ToString();
 }
Ejemplo n.º 31
0
 private void SendBroadcast(string url, MyWebRequest req, string ext)
 {
     var broadcast = _device.Proxy.Broadcaster.GetStream(url, req.Parameters, req.Client);
     try
     {
         SendHeaders(req, ext);
         broadcast.CopyTo(req.GetResponse().GetStream());
     } finally
     {
         broadcast.Close();
     }
     //string broadcast = _device.Proxy.FindBroadcastUrl(url);
     //if (string.IsNullOrEmpty(broadcast))
     //    broadcast = _device.Proxy.StartBroadcastStream(url, req.Parameters.ContainsKey("transcode") ? req.Parameters["transcode"] : "");
     //_device.Proxy.AddVlcBroadcastClient(broadcast, req.Client);
     //req.GetResponse().SendBroadcast(broadcast, request => SendHeaders(request, ext));
     //_device.Proxy.StopBroadcast(broadcast, url);
 }
Ejemplo n.º 32
0
        private void PlayNew(MyWebRequest req, SourceUrl source)
        {
            var url = source.Url;
            if (source.Type == SourceType.Torrent)
            {
                TorrentStream ts1 = new TorrentStream(req.Client);
                ts1.Connect();
                var respData = ts1.ReadTorrent(url, TTVApi.SourceType.Torrent);
                url = ts1.GetContentId(respData);
            }

        }
Ejemplo n.º 33
0
 private void GetSystemUpdateID(MyWebRequest request)
 {
     MyWebResponse response = request.GetResponse();
     response.SendSoapHeadersBody("0");
 }
Ejemplo n.º 34
0
 public override void Play(MyWebRequest req)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 35
0
        public static MyWebRequest Create(TcpClient client)
        {
            var ret = new MyWebRequest
            {
                headers     = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase),
                urlParams   = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase),
                Client      = client,
                stream      = client.GetStream(),
                QueryString = string.Empty
            };

            StringBuilder sb = new StringBuilder(128);
            bool          isLastR = false, isFirstLine = true;
            int           iByte;

            while ((iByte = ret.stream.ReadByte()) >= 0)
            {
                if (iByte == '\n' && isLastR)
                {
                    string line = sb.ToString(0, sb.Length - 1);
                    if (line == string.Empty)
                    {
                        break;
                    }
                    sb.Clear();

                    if (isFirstLine)
                    {
                        string[] values = line.Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                        ret.method = (HttpMethod)Enum.Parse(typeof(HttpMethod), values[0], true);

                        int index = values[1].LastIndexOf(' ');
                        ret.version = values[1].Substring(index + 1);

                        values  = HttpUtility.UrlDecode(values[1].Substring(0, index)).Split(new[] { '?' }, 2, StringSplitOptions.RemoveEmptyEntries);
                        ret.url = values[0];
                        if (values.Length > 1)
                        {
                            ret.QueryString = values[1];
                        }
                        if (values.Length == 2)
                        {
                            foreach (string parameter in values[1].Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
                            {
                                string[] keyValue = parameter.Split(new[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries);
                                ret.urlParams[keyValue[0]] = (keyValue.Length == 2) ? keyValue[1] : string.Empty;
                            }
                        }

                        isFirstLine = false;
                    }
                    else
                    {
                        string[] keyValue = line.Split(new[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);
                        string   header   = keyValue[0].Trim();
                        string   values   = keyValue[1].Trim();
                        ret.headers[header] = keyValue.Length > 1 ? values : string.Empty;
                    }

                    isLastR = false;
                }
                else if (iByte == '\r')
                {
                    sb.Append((char)iByte);
                    isLastR = true;
                }
                else
                {
                    sb.Append((char)iByte);
                    isLastR = false;
                }
            }

            return(ret);
        }