Exemplo n.º 1
0
        private Page(Session client, Target target, FrameTree frameTree, bool ignoreHTTPSErrors, TaskQueue screenshotTaskQueue)
        {
            _client           = client;
            _target           = target;
            Keyboard          = new Keyboard(client);
            _mouse            = new Mouse(client, Keyboard);
            Touchscreen       = new Touchscreen(client, Keyboard);
            _frameManager     = new FrameManager(client, frameTree, this);
            _networkManager   = new NetworkManager(client, _frameManager);
            _emulationManager = new EmulationManager(client);
            Tracing           = new Tracing(client);
            _pageBindings     = new Dictionary <string, Func <object> >();

            _ignoreHTTPSErrors = ignoreHTTPSErrors;

            _screenshotTaskQueue = screenshotTaskQueue;

            //TODO: Do we need this bubble?
            _frameManager.FrameAttached  += (sender, e) => FrameAttached?.Invoke(this, e);
            _frameManager.FrameDetached  += (sender, e) => FrameDetached?.Invoke(this, e);
            _frameManager.FrameNavigated += (sender, e) => FrameNavigated?.Invoke(this, e);

            _networkManager.RequestCreated  += (sender, e) => RequestCreated?.Invoke(this, e);
            _networkManager.RequestFailed   += (sender, e) => RequestFailed?.Invoke(this, e);
            _networkManager.ResponseCreated += (sender, e) => ResponseCreated?.Invoke(this, e);
            _networkManager.RequestFinished += (sender, e) => RequestFinished?.Invoke(this, e);

            _client.MessageReceived += client_MessageReceived;
        }
Exemplo n.º 2
0
        private void HandleRequestRedirect(Request request, ResponsePayload responseMessage)
        {
            var response = new Response(
                _client,
                request,
                responseMessage);

            request.Response = response;
            request.RedirectChainList.Add(request);
            response.BodyLoadedTaskWrapper.TrySetException(
                new PuppeteerException("Response body is unavailable for redirect responses"));

            if (request.RequestId != null)
            {
                _requestIdToRequest.TryRemove(request.RequestId, out _);
            }

            if (request.InterceptionId != null)
            {
                _attemptedAuthentications.Remove(request.InterceptionId);
            }

            Response?.Invoke(this, new ResponseCreatedEventArgs
            {
                Response = response
            });

            RequestFinished?.Invoke(this, new RequestEventArgs
            {
                Request = request
            });
        }
Exemplo n.º 3
0
 /// <summary>
 /// Request for content (GET)
 /// </summary>
 /// <param name="url"></param>
 /// <param name="callback"></param>
 public static void DownloadString(string url, RequestFinished callback)
 {
     TaskPool.Instance.Request(
         url,
         HttpMethod.Get,
         null,
         new RequestFinished((isOk, result, errResult) => callback(isOk, result, errResult)));
 }
Exemplo n.º 4
0
 /// <summary>
 /// Request for content (POST)
 /// </summary>
 /// <param name="url"></param>
 /// <param name="postData"></param>
 /// <param name="callback"></param>
 public static void UploadString(string url, List<KeyValuePair<string, string>> postData, RequestFinished callback)
 {
     TaskPool.Instance.Request(
         url,
         HttpMethod.Post,
         postData,
         new RequestFinished((isOk, result, errResult) => callback(isOk, result, errResult)));
 }
        internal override void OnMessage(string method, JsonElement?serverParams)
        {
            switch (method)
            {
            case "close":
                Close?.Invoke(this, EventArgs.Empty);
                break;

            case "bindingCall":
                BindingCall?.Invoke(
                    this,
                    new() { BindingCall = serverParams?.GetProperty("binding").ToObject <BindingCallChannel>(Connection.DefaultJsonSerializerOptions).Object });
                break;

            case "route":
                var route   = serverParams?.GetProperty("route").ToObject <RouteChannel>(Connection.DefaultJsonSerializerOptions).Object;
                var request = serverParams?.GetProperty("request").ToObject <RequestChannel>(Connection.DefaultJsonSerializerOptions).Object;
                Route?.Invoke(
                    this,
                    new() { Route = route, Request = request });
                break;

            case "page":
                Page?.Invoke(
                    this,
                    new() { PageChannel = serverParams?.GetProperty("page").ToObject <PageChannel>(Connection.DefaultJsonSerializerOptions) });
                break;

            case "crBackgroundPage":
                BackgroundPage?.Invoke(
                    this,
                    new() { PageChannel = serverParams?.GetProperty("page").ToObject <PageChannel>(Connection.DefaultJsonSerializerOptions) });
                break;

            case "crServiceWorker":
                ServiceWorker?.Invoke(
                    this,
                    new() { WorkerChannel = serverParams?.GetProperty("worker").ToObject <WorkerChannel>(Connection.DefaultJsonSerializerOptions) });
                break;

            case "request":
                Request?.Invoke(this, serverParams?.ToObject <BrowserContextChannelRequestEventArgs>(Connection.DefaultJsonSerializerOptions));
                break;

            case "requestFinished":
                RequestFinished?.Invoke(this, serverParams?.ToObject <BrowserContextChannelRequestEventArgs>(Connection.DefaultJsonSerializerOptions));
                break;

            case "requestFailed":
                RequestFailed?.Invoke(this, serverParams?.ToObject <BrowserContextChannelRequestEventArgs>(Connection.DefaultJsonSerializerOptions));
                break;

            case "response":
                Response?.Invoke(this, serverParams?.ToObject <BrowserContextChannelResponseEventArgs>(Connection.DefaultJsonSerializerOptions));
                break;
            }
        }
Exemplo n.º 6
0
        public static void games(string user_id, string session_id, string game_id, RequestFinished _callback)
        {
            callback = _callback;

            WebClient wc = new WebClient();

            wc.Headers[HttpRequestHeader.Cookie] = "ap_session=" + session_id + "; ";
            wc.DownloadStringCompleted          += doneDownload;
            wc.DownloadStringAsync(new Uri(baseURL + "users/" + user_id + "/games/" + game_id));
        }
Exemplo n.º 7
0
        public static void answer(string user_id, string session_id, string game_id, JToken answer, RequestFinished _callback)
        {
            callback = _callback;

            WebClient wc = new WebClient();

            wc.Headers[HttpRequestHeader.Cookie]      = "ap_session=" + session_id + "; ";
            wc.Headers[HttpRequestHeader.ContentType] = "application/json";
            wc.UploadStringCompleted += doneUpload;
            wc.UploadStringAsync(new Uri(baseURL + "users/" + user_id + "/games/" + game_id + "/answers"), answer.ToString());
        }
Exemplo n.º 8
0
        private void HandleRequestFinished(RequestFinished m)
        {
            Console.WriteLine($"AgentActor: Request finished with status code {m.ResultCode}.");
            numberOfReturnedRequests += 1;
            Context.Child(AGGREGATION_ACTOR_NAME).Forward(m);

            if (numberOfReturnedRequests == startNewLoadTest.NumberOfRequestsPerAgent)
            {
                Context.Child(AGGREGATION_ACTOR_NAME).Tell(new ProcessAgentResults());
            }
        }
Exemplo n.º 9
0
            public void LogRequestEnding()
            {
                _requestStopwatch.Stop();
                var requestTimeElapsed = _requestStopwatch.ElapsedMilliseconds;

                var requestFinished =
                    new RequestFinished(requestTimeElapsed, _logContext, new HttpResponseContext(_context));

                _logOverheadStopwatch.Start();
                _log.Info(requestFinished);
                _logOverheadStopwatch.Stop();

                //_log.Debug($"DEBUG {DateTimeOffset.Now.ToString(Constants.DateTimeOffsetFormat)}: Request/response logging overhead {_logOverheadStopwatch.ElapsedMilliseconds} ms ({_logContext.CorrelationId})");
            }
Exemplo n.º 10
0
        public static void login(string email, string password, RequestFinished _callback)
        {
            callback = _callback;

            JObject jo = new JObject();

            jo["email"]    = email;
            jo["password"] = password;

            WebClient wc = new WebClient();

            wc.Headers[HttpRequestHeader.ContentType] = "application/json";
            wc.UploadStringCompleted += doneUpload;
            wc.UploadStringAsync(new Uri(baseURL + "login"), jo.ToString());
        }
Exemplo n.º 11
0
        public HouseManagement()
        {
            _requests = new Queue <Request>();

            _departments = CreateDepartments();
            _departments.Subscribe((request, employee) => RequestFinished?.Invoke(request, employee));

            _committee = new RequestCommittee(_requests);
            _committee.RequestAdded += request => RequestAdded?.Invoke(request);

            _dispatcher = new Dispatcher(_departments, _requests);
            _dispatcher.RequestProcessed   += request => RequestProcessed?.Invoke(request);
            _dispatcher.RequestPostponed   += request => RequestPostponed?.Invoke(request);
            _dispatcher.SimulationFinished += () => SimulationFinished?.Invoke();
        }
Exemplo n.º 12
0
        private void OnLoadingFinished(LoadingFinishedResponse e)
        {
            // For certain requestIds we never receive requestWillBeSent event.
            // @see https://crbug.com/750469
            if (_requestIdToRequest.TryGetValue(e.RequestId, out var request))
            {
                request.Response?.BodyLoadedTaskWrapper.TrySetResult(true);

                ForgetRequest(request, true);

                RequestFinished?.Invoke(this, new RequestEventArgs
                {
                    Request = request
                });
            }
        }
Exemplo n.º 13
0
        private void OnLoadingFinished(LoadingFinishedResponse e)
        {
            // For certain requestIds we never receive requestWillBeSent event.
            // @see https://crbug.com/750469
            if (_requestIdToRequest.TryGetValue(e.RequestId, out var request))
            {
                request.Response?.BodyLoadedTaskWrapper.TrySetResult(true);
                _requestIdToRequest.TryRemove(request.RequestId, out _);

                if (request.InterceptionId != null)
                {
                    _attemptedAuthentications.Remove(request.InterceptionId);
                }

                RequestFinished?.Invoke(this, new RequestEventArgs
                {
                    Request = request
                });
            }
        }
Exemplo n.º 14
0
        private void OnLoadingFinished(MessageEventArgs e)
        {
            // For certain requestIds we never receive requestWillBeSent event.
            // @see https://crbug.com/750469
            if (_requestIdToRequest.ContainsKey(e.MessageData.requestId.ToString()))
            {
                var request = _requestIdToRequest[e.MessageData.requestId.ToString()];

                request.CompleteTaskWrapper.SetResult(true);
                _requestIdToRequest.Remove(request.RequestId);

                if (request.InterceptionId != null)
                {
                    _interceptionIdToRequest.Remove(request.InterceptionId);
                    _attemptedAuthentications.Remove(request.InterceptionId);
                }

                RequestFinished?.Invoke(this, new RequestEventArgs()
                {
                    Request = request
                });
            }
        }
Exemplo n.º 15
0
        private void HandleRequestRedirect(Request request, ResponsePayload responseMessage)
        {
            var response = new Response(
                _client,
                request,
                responseMessage);

            request.Response = response;
            request.RedirectChainList.Add(request);
            response.BodyLoadedTaskWrapper.TrySetException(
                new PuppeteerException("Response body is unavailable for redirect responses"));

            ForgetRequest(request, false);

            Response?.Invoke(this, new ResponseCreatedEventArgs
            {
                Response = response
            });

            RequestFinished?.Invoke(this, new RequestEventArgs
            {
                Request = request
            });
        }
Exemplo n.º 16
0
        /// <summary>
        /// Startet die eigentlich Aufzeichnung in einer abgesicherten Umgebung.
        /// </summary>
        private void Run()
        {
            // Be fully safe
            try
            {
                // Create raw environment
                var coreEnvironment =
                    new Dictionary <string, string>
                {
                    { "%wakeupprofile%", ProfileState.WakeUpRequired ? "1" : "0" },
                    { "%dvbnetprofile%", ProfileName },
                };

                // Be fully safe
                try
                {
                    // Log it
                    VCRServer.Log(LoggingLevel.Schedules, Properties.Resources.RecordingStarted, TypeName);

                    // Report
                    Tools.ExtendedLogging("Started Recording Control Thread for {0}", ProfileName);

                    // Fire all extensions
                    Tools.RunSynchronousExtensions("BeforeProfileAccess", coreEnvironment);

                    // Use it
                    using (Server = CreateCardServerProxy())
                    {
                        // Check mode
                        var mustWakeUp = ProfileState.WakeUpRequired;
                        if (mustWakeUp)
                        {
                            // Log
                            VCRServer.Log(LoggingLevel.Full, Properties.Resources.RestartMessage);

                            // Report
                            Tools.ExtendedLogging("Will restart Hardware for {0} if Restart Device is configured in Profile", ProfileName);
                        }

                        // Start synchronously
                        ServerImplementation.EndRequest(
                            Server.BeginSetProfile
                            (
                                ProfileName,
                                mustWakeUp,
                                VCRConfiguration.Current.DisablePCRFromH264Generation,
                                VCRConfiguration.Current.DisablePCRFromMPEG2Generation
                            ));

                        // Report
                        Tools.ExtendedLogging("Card Server is up and running");

                        // Remember time
                        Representative.PhysicalStart = DateTime.UtcNow;

                        // Create fresh environment and fire extensions - with no files so far
                        FireRecordingStartedExtensions(ExtensionEnvironment = Representative.GetReplacementPatterns());

                        // Time to allow derived class to start up
                        OnStart();

                        // Process idle loop - done every second if not interrupted earlier
                        for (IAsyncResult <ServerInformation> stateRequest = null; ; m_wakeUp.WaitOne(m_running ? 1000 : 100))
                        {
                            // First check for state request
                            if (stateRequest != null)
                            {
                                // No yet done
                                if (!stateRequest.IsCompleted)
                                {
                                    continue;
                                }

                                // Process the state
                                OnNewStateAvailable(m_state = stateRequest.Result);

                                // No longer waiting for the next state
                                stateRequest = null;
                            }

                            // See if we are busy in the derived class
                            if (HasPendingServerRequest)
                            {
                                continue;
                            }

                            // Process actions - no asynchronous operations allowed in current version
                            ProcessActions();

                            // Make sure that scheduler knows we accepted the request
                            ConfirmPendingRequest();

                            // If we are still idle fire a new state request
                            if (!HasPendingServerRequest)
                            {
                                if (m_running)
                                {
                                    stateRequest = Server.BeginGetState();
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }

                        // Time to let derived class shut down properly
                        OnStop();

                        // Run final state update before protocol entry is created
                        if (m_state != null)
                        {
                            OnNewStateAvailable(m_state);
                        }

                        // Update recording data for the very last time
                        var info = CreateFullInformation(true);
                        if (info != null)
                        {
                            Representative = info.Recording;
                        }

                        // Set real send
                        Representative.EndsAt = DateTime.UtcNow;

                        // Set end state
                        ExtensionEnvironment["%Aborted%"] = m_aborted ? "1" : "0";

                        // Process extensions
                        FireRecordingFinishedExtensions(ExtensionEnvironment);

                        // No need for further wakeups
                        ProfileState.WakeUpRequired = false;
                    }
                }
                catch (Exception e)
                {
                    // Report
                    VCRServer.Log(e);

                    // Try to make sure that job is not restarted
                    try
                    {
                        // Update
                        SetRestartThreshold(null);
                    }
                    catch (Exception ex)
                    {
                        // Report
                        VCRServer.Log(ex);
                    }
                }
                finally
                {
                    // Detach from server - is already disposed and shut down
                    Server = null;

                    // Fire all extensions
                    Tools.RunSynchronousExtensions("AfterProfileAccess", coreEnvironment);

                    // Detach from profile
                    ProfileState.EndRequest(this);

                    // Write recording
                    ProfileState.Server.JobManager.CreateLogEntry(Representative);

                    // May go to sleep after job is finished
                    ProfileState.Server.ReportRecordingDone(Representative.DisableHibernation, IsRealRecording);

                    // Check for next job on all profiles
                    ProfileState.Collection.BeginNewPlan();

                    // Report
                    Tools.ExtendedLogging("Recording finished for {0}", ProfileName);

                    // Log it
                    VCRServer.Log(LoggingLevel.Schedules, Properties.Resources.RecordingFinished, TypeName);
                }
            }
            catch (Exception e)
            {
                // Report
                VCRServer.Log(e);
            }
            finally
            {
                // Make sure that even in case of error we do a full notification
                ConfirmPendingRequest(true);

                // Always fire event
                RequestFinished.Set();
            }
        }
Exemplo n.º 17
0
 private void HandleRequestFinished(RequestFinished requestFinished)
 {
     FinishedRequests.Add(new RequestResultDto(requestFinished.ResultCode, requestFinished.RequestDuration, requestFinished.SenderId));
 }
Exemplo n.º 18
0
 /// <summary>
 /// get web content
 /// </summary>
 /// <param name="url">requested url</param>
 /// <param name="action">callback when finished</param>
 public void Request(string url, HttpMethod method, List<KeyValuePair<string, string>> httpPostData, RequestFinished action)
 {
     QueueItem item = new QueueItem() { Action = action, Url = url, Method = method, PostData = httpPostData };
     AddQueueItem(item);
 }
Exemplo n.º 19
0
 /// <summary>
 /// upload a file
 /// </summary>
 /// <param name="url">requested url</param>
 /// <param name="httpPostData">post data</param>
 /// <param name="fileUploadData">file data</param>
 /// <param name="fileFieldName">file name in header</param>
 /// <param name="fileName">file name</param>
 /// <param name="action">callback when finished</param>
 public void RequestUploadFile(string url, List<KeyValuePair<string, string>> httpPostData, byte[] fileUploadData, string fileFieldName, string fileName, RequestFinished action)
 {
     QueueItem item = new QueueItem()
     {
         Method = HttpMethod.Post,
         Action = action,
         Url = url,
         PostData = httpPostData
     };
     AddQueueItem(item);
 }
Exemplo n.º 20
0
        /// <summary>
        /// 启动异步请求
        /// </summary>
        /// <param name="Method"></param>
        /// <param name="Data"></param>
        /// <returns></returns>
        public async Task <Object> SendRequestAsync(RequestMethod?Method = null, object Data = null)
        {
            int retry_count = 1;

            do
            {
                try
                {
                    Method = Method ?? ReqMethod;
                    Data   = Data ?? ReqObject;

                    byte[] Body = null;
                    if (Data != null)
                    {
                        Body = Processor.ObjectToData(Data);
                    }
                    BaseRequest.Method            = Enum.GetName(typeof(RequestMethod), Method);
                    BaseRequest.AllowAutoRedirect = AllowRedirect;
                    BaseRequest.Expect            = null;
                    if (BaseRequest.CookieContainer == null)
                    {
                        // 初始化Cookies容器以获取返回的Cookie
                        BaseRequest.CookieContainer = new CookieContainer();
                    }
                    BaseRequest.ServicePoint.Expect100Continue = false;
                    BaseRequest.CachePolicy = new System.Net.Cache.HttpRequestCachePolicy(System.Net.Cache.HttpRequestCacheLevel.NoCacheNoStore);
                    if (Body != null)
                    {
                        using (Stream RequestStream = BaseRequest.GetRequestStream())
                        {
                            await RequestStream.WriteAsync(Body, 0, Body.Length);
                        }
                    }
                    HttpWebResponse Response = (HttpWebResponse)BaseRequest.GetResponse();
                    LastResponse    = Response;
                    ResponseCookie  = Response.Cookies;
                    ResponseHeaders = new NameValueCollection();
                    for (int i = 0; i < Response.Headers.Count; i++)
                    {
                        ResponseHeaders.Add(Response.Headers.Keys[i], Response.Headers[i]);
                    }
                    using (var ResponseStream = Response.GetResponseStream())
                    {
                        using (var Buffer = new MemoryStream())
                        {
                            int    ReadLen = 0;
                            byte[] Part    = new byte[4096];
                            while (true)
                            {
                                ReadLen = await ResponseStream.ReadAsync(Part, 0, 4096);

                                if (ReadLen == 0)
                                {
                                    break;
                                }
                                await Buffer.WriteAsync(Part, 0, ReadLen);
                            }

                            byte[] ResponseData = Buffer.ToArray();

                            ResponseObject = Processor.DataToObject(ResponseData);
                            LastError      = null;
                            RequestFinished?.Invoke(this);
                            return(ResponseObject);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LastError       = "网络错误";
                    ResponseHeaders = null;
                    ResponseObject  = null;
                    await Task <Object> .Delay(500);
                }
            } while (retry_count++ <= Retry);

            return(null);
        }
Exemplo n.º 21
0
 public virtual void OnRequestFinished(WebEventArgs e)
 {
     RequestFinished?.Invoke(e.Context, e);
 }
Exemplo n.º 22
0
        internal override void OnMessage(string method, JsonElement?serverParams)
        {
            switch (method)
            {
            case "close":
                Closed?.Invoke(this, EventArgs.Empty);
                break;

            case "crash":
                Crashed?.Invoke(this, EventArgs.Empty);
                break;

            case "domcontentloaded":
                DOMContentLoaded?.Invoke(this, EventArgs.Empty);
                break;

            case "load":
                Load?.Invoke(this, EventArgs.Empty);
                break;

            case "bindingCall":
                BindingCall?.Invoke(
                    this,
                    new BindingCallEventArgs
                {
                    BidingCall = serverParams?.GetProperty("binding").ToObject <BindingCallChannel>(Connection.GetDefaultJsonSerializerOptions()).Object,
                });
                break;

            case "route":
                Route?.Invoke(
                    this,
                    new RouteEventArgs
                {
                    Route   = serverParams?.GetProperty("route").ToObject <RouteChannel>(Connection.GetDefaultJsonSerializerOptions()).Object,
                    Request = serverParams?.GetProperty("request").ToObject <RequestChannel>(Connection.GetDefaultJsonSerializerOptions()).Object,
                });
                break;

            case "popup":
                Popup?.Invoke(this, new PageChannelPopupEventArgs
                {
                    Page = serverParams?.GetProperty("page").ToObject <PageChannel>(Connection.GetDefaultJsonSerializerOptions()).Object,
                });
                break;

            case "pageError":
                PageError?.Invoke(this, serverParams?.GetProperty("error").GetProperty("error").ToObject <PageErrorEventArgs>(Connection.GetDefaultJsonSerializerOptions()));
                break;

            case "fileChooser":
                FileChooser?.Invoke(this, serverParams?.ToObject <FileChooserChannelEventArgs>(Connection.GetDefaultJsonSerializerOptions()));
                break;

            case "frameAttached":
                FrameAttached?.Invoke(this, new FrameEventArgs(serverParams?.GetProperty("frame").ToObject <FrameChannel>(Connection.GetDefaultJsonSerializerOptions()).Object));
                break;

            case "frameDetached":
                FrameDetached?.Invoke(this, new FrameEventArgs(serverParams?.GetProperty("frame").ToObject <FrameChannel>(Connection.GetDefaultJsonSerializerOptions()).Object));
                break;

            case "dialog":
                Dialog?.Invoke(this, new DialogEventArgs(serverParams?.GetProperty("dialog").ToObject <DialogChannel>(Connection.GetDefaultJsonSerializerOptions()).Object));
                break;

            case "console":
                Console?.Invoke(this, new ConsoleEventArgs(serverParams?.GetProperty("message").ToObject <ConsoleMessage>(Connection.GetDefaultJsonSerializerOptions())));
                break;

            case "request":
                Request?.Invoke(this, new RequestEventArgs {
                    Request = serverParams?.GetProperty("request").ToObject <RequestChannel>(Connection.GetDefaultJsonSerializerOptions()).Object
                });
                break;

            case "requestFinished":
                RequestFinished?.Invoke(this, new RequestEventArgs {
                    Request = serverParams?.GetProperty("request").ToObject <RequestChannel>(Connection.GetDefaultJsonSerializerOptions()).Object
                });
                break;

            case "requestFailed":
                RequestFailed?.Invoke(this, serverParams?.ToObject <PageChannelRequestFailedEventArgs>(Connection.GetDefaultJsonSerializerOptions()));
                break;

            case "response":
                Response?.Invoke(this, new ResponseEventArgs {
                    Response = serverParams?.GetProperty("response").ToObject <ResponseChannel>(Connection.GetDefaultJsonSerializerOptions()).Object
                });
                break;

            case "download":
                Download?.Invoke(this, new DownloadEventArgs()
                {
                    Download = serverParams?.GetProperty("download").ToObject <DownloadChannel>(Connection.GetDefaultJsonSerializerOptions()).Object
                });
                break;

            case "worker":
                Worker?.Invoke(
                    this,
                    new WorkerChannelEventArgs
                {
                    WorkerChannel = serverParams?.GetProperty("worker").ToObject <WorkerChannel>(Connection.GetDefaultJsonSerializerOptions()),
                });
                break;
            }
        }
Exemplo n.º 23
0
 protected Department()
 {
     Employee = CreateEmployee();
     Employee.RequestFinished += (request, employee) => RequestFinished?.Invoke(request, employee);
 }
Exemplo n.º 24
0
        public RequestResult RequestVoice(string text, string name)
        {
            RequestResult result;       //Result는 요청 결과 값

            if (text.Length <= 0)
            {
                result = new RequestResult()
                {
                    IsSuccessed = false,
                    Message     = "No Text"
                };
                RequestFinished?.Invoke(text, result);

                return(result);
            }       //텍스트가 없으면 내부 오류로 처리

            string resultPath = TargetDirectory + Regex.Replace(name, @"[^a-zA-Z0-9가-힣]", "_");

            //확장자 불포함 파일 경로

            if (history.TryGetValue(text, out string path))
            {
                try
                {
                    File.Copy(path, TargetDirectory + name + "_cpy.mp3");
                    Debug.WriteLine("Voice File Copied in " + TargetDirectory);
                    result = new RequestResult()
                    {
                        IsSuccessed = true,
                        Message     = "File Copied",
                        ResultPath  = resultPath + "_cpy.mp3"
                    };
                    RequestFinished?.Invoke(text, result);

                    return(result);      //이미 history.bin에 기록이 있는 경우 파일을 복사
                }
                catch (FileNotFoundException e)
                {
                    history.Remove(text);
                    Debug.WriteLine(e);
                }
            }

            string         url     = "https://naveropenapi.apigw.ntruss.com/voice-premium/v1/tts";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Headers.Add(CLIENT_ID_NAME, ClientID);
            request.Headers.Add(CLIENT_SECRET_NAME, ClientSecret);
            request.Method = "POST";
            byte[] byteDataParams = Encoding.UTF8.GetBytes("speaker=nara&volume=0&speed=0&pitch=0&emotion=0&format=mp3&text=" + text);
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = byteDataParams.Length;
            Stream st = request.GetRequestStream();

            st.Write(byteDataParams, 0, byteDataParams.Length);
            st.Close();
            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                System.Windows.MessageBox.Show("Error Occured(" + e.Status + ")\n\n" + e.Message, "Web Exception",
                                               System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                result = new RequestResult()
                {
                    IsSuccessed = false,
                    Message     = e.Message
                };
                RequestFinished?.Invoke(text, result);

                return(result);
            }

            string status = response.StatusCode.ToString();

            Debug.Write("status=" + status + " --> ");
            using (Stream output = File.OpenWrite(resultPath + ".mp3"))
                using (Stream input = response.GetResponseStream())
                    input.CopyTo(output);

            response.Dispose();

            if (history.ContainsKey(text) == false)
            {
                history.Add(text, resultPath + ".mp3");
            }

            //---- 네이버 클라우드 서버에 CPV 요청 및 파일 반환 완료 ----//

            Debug.WriteLine("Voice File Created in " + resultPath + ".mp3");

            result = new RequestResult()
            {
                IsSuccessed = true,
                Message     = "File Created",
                ResultPath  = resultPath + ".mp3"
            };
            RequestFinished?.Invoke(text, result);

            return(result);
        }