diff --git a/lib/PuppeteerSharp/Browser.cs b/lib/PuppeteerSharp/Browser.cs index 7b8af6b14..fe776bef0 100644 --- a/lib/PuppeteerSharp/Browser.cs +++ b/lib/PuppeteerSharp/Browser.cs @@ -220,7 +220,7 @@ public async Task PagesAsync() public async Task GetVersionAsync() { var version = await Connection.SendAsync("Browser.getVersion").ConfigureAwait(false); - return version[Constants.PRODUCT].AsString(); + return version[MessageKeys.Product].AsString(); } /// @@ -233,7 +233,7 @@ public async Task GetVersionAsync() public async Task GetUserAgentAsync() { var version = await Connection.SendAsync("Browser.getVersion").ConfigureAwait(false); - return version[Constants.USER_AGENT].AsString(); + return version[MessageKeys.UserAgent].AsString(); } /// @@ -300,12 +300,12 @@ internal void ChangeTarget(Target target) internal async Task CreatePageInContextAsync(string contextId) { - var args = new Dictionary { [Constants.URL] = "about:blank" }; + var args = new Dictionary { [MessageKeys.Url] = "about:blank" }; if (contextId != null) { - args[Constants.BROWSER_CONTEXT_ID] = contextId; + args[MessageKeys.BrowserContextId] = contextId; } - string targetId = (await Connection.SendAsync("Target.createTarget", args))[Constants.TARGET_ID].AsString(); + string targetId = (await Connection.SendAsync("Target.createTarget", args))[MessageKeys.TargetId].AsString(); var target = TargetsMap[targetId]; await target.InitializedTask; diff --git a/lib/PuppeteerSharp/CDPSession.cs b/lib/PuppeteerSharp/CDPSession.cs index 133ac1bd0..b2a64b01c 100755 --- a/lib/PuppeteerSharp/CDPSession.cs +++ b/lib/PuppeteerSharp/CDPSession.cs @@ -1,10 +1,12 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Newtonsoft.Json; -using System.Collections.Generic; using Newtonsoft.Json.Linq; -using Microsoft.Extensions.Logging; +using PuppeteerSharp.Helpers; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp { @@ -121,9 +123,9 @@ public async Task SendAsync(string method, dynamic args = null) var id = ++_lastId; var message = JsonConvert.SerializeObject(new Dictionary { - { Constants.ID, id }, - { Constants.METHOD, method }, - { Constants.PARAMS, args } + { MessageKeys.Id, id }, + { MessageKeys.Method, method }, + { MessageKeys.Params, args } }); _logger.LogTrace("Send ► {Id} Method {Method} Params {@Params}", id, method, (object)args); @@ -138,8 +140,8 @@ public async Task SendAsync(string method, dynamic args = null) { await Connection.SendAsync("Target.sendMessageToTarget", new Dictionary { - { Constants.SESSION_ID, SessionId }, - { Constants.MESSAGE, message } + { MessageKeys.SessionId, SessionId }, + { MessageKeys.Message, message } }).ConfigureAwait(false); } catch (Exception ex) @@ -180,47 +182,46 @@ internal void OnMessage(string message) catch (JsonException exc) { _logger.LogError(exc, "Failed to deserialize message", message); - return; } - var id = obj[Constants.ID]?.Value(); + var id = obj[MessageKeys.Id]?.Value(); if (id.HasValue && _callbacks.TryGetValue(id.Value, out var callback) && _callbacks.Remove(id.Value)) { - if (obj[Constants.ERROR] != null) + if (obj[MessageKeys.Error] != null) { callback.TaskWrapper.TrySetException(new MessageException(callback, obj)); } else { - callback.TaskWrapper.TrySetResult(obj[Constants.RESULT].Value()); + callback.TaskWrapper.TrySetResult(obj[MessageKeys.Result].Value()); } } else { - var method = obj[Constants.METHOD].AsString(); - var param = obj[Constants.PARAMS]; + var method = obj[MessageKeys.Method].AsString(); + var param = obj[MessageKeys.Params]; if (method == "Tracing.tracingComplete") { TracingComplete?.Invoke(this, new TracingCompleteEventArgs { - Stream = param[Constants.STREAM].AsString() + Stream = param[MessageKeys.Stream].AsString() }); } else if (method == "Target.receivedMessageFromTarget") { - var sessionId = param[Constants.SESSION_ID].AsString(); + var sessionId = param[MessageKeys.SessionId].AsString(); if (_sessions.TryGetValue(sessionId, out var session)) { - session.OnMessage(param[Constants.MESSAGE].AsString()); + session.OnMessage(param[MessageKeys.Message].AsString()); } } else if (method == "Target.detachedFromTarget") { - var sessionId = param[Constants.SESSION_ID].AsString(); + var sessionId = param[MessageKeys.SessionId].AsString(); if (_sessions.TryGetValue(sessionId, out var session) && _sessions.Remove(sessionId)) { diff --git a/lib/PuppeteerSharp/Connection.cs b/lib/PuppeteerSharp/Connection.cs index ba8afc58a..f41ca4f57 100644 --- a/lib/PuppeteerSharp/Connection.cs +++ b/lib/PuppeteerSharp/Connection.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net.WebSockets; @@ -10,6 +9,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using PuppeteerSharp.Helpers; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp { @@ -94,9 +94,9 @@ internal async Task SendAsync(string method, dynamic args = null) var id = ++_lastId; var message = JsonConvert.SerializeObject(new Dictionary { - { Constants.ID, id }, - { Constants.METHOD, method }, - { Constants.PARAMS, args } + { MessageKeys.Id, id }, + { MessageKeys.Method, method }, + { MessageKeys.Params, args } }); _logger.LogTrace("Send ► {Id} Method {Method} Params {@Params}", id, method, (object)args); @@ -126,7 +126,7 @@ internal async Task CreateSessionAsync(TargetInfo targetInfo) var sessionId = (await SendAsync("Target.attachToTarget", new { targetId = targetInfo.TargetId - }).ConfigureAwait(false))[Constants.SESSION_ID].AsString(); + }).ConfigureAwait(false))[MessageKeys.SessionId].AsString(); var session = new CDPSession(this, targetInfo.Type, sessionId); _sessions.Add(sessionId, session); return session; @@ -238,13 +238,12 @@ private void ProcessResponse(string response) catch (JsonException exc) { _logger.LogError(exc, "Failed to deserialize response", response); - return; } _logger.LogTrace("◀ Receive {Message}", response); - var id = obj[Constants.ID]?.Value(); + var id = obj[MessageKeys.Id]?.Value(); if (id.HasValue) { @@ -252,32 +251,32 @@ private void ProcessResponse(string response) //if not we add this to the list, sooner or later some one will come for it if (_callbacks.TryGetValue(id.Value, out var callback) && _callbacks.Remove(id.Value)) { - if (obj[Constants.ERROR] != null) + if (obj[MessageKeys.Error] != null) { callback.TaskWrapper.TrySetException(new MessageException(callback, obj)); } else { - callback.TaskWrapper.TrySetResult(obj[Constants.RESULT].Value()); + callback.TaskWrapper.TrySetResult(obj[MessageKeys.Result].Value()); } } } else { - var method = obj[Constants.METHOD].AsString(); - var param = obj[Constants.PARAMS]; + var method = obj[MessageKeys.Method].AsString(); + var param = obj[MessageKeys.Params]; if (method == "Target.receivedMessageFromTarget") { - var sessionId = param[Constants.SESSION_ID].AsString(); + var sessionId = param[MessageKeys.SessionId].AsString(); if (_sessions.TryGetValue(sessionId, out var session)) { - session.OnMessage(param[Constants.MESSAGE].AsString()); + session.OnMessage(param[MessageKeys.Message].AsString()); } } else if (method == "Target.detachedFromTarget") { - var sessionId = param[Constants.SESSION_ID].AsString(); + var sessionId = param[MessageKeys.SessionId].AsString(); if (_sessions.TryGetValue(sessionId, out var session) && _sessions.Remove(sessionId) && !session.IsClosed) { session.OnClosed(); diff --git a/lib/PuppeteerSharp/Constants.cs b/lib/PuppeteerSharp/Constants.cs deleted file mode 100644 index 993ed6612..000000000 --- a/lib/PuppeteerSharp/Constants.cs +++ /dev/null @@ -1,78 +0,0 @@ -namespace PuppeteerSharp -{ - /// - /// Constants common to devtools API interaction - /// - internal class Constants - { - public const string ID = "id"; - public const string ERROR = "error"; - public const string RESULT = "result"; - public const string METHOD = "method"; - public const string STREAM = "stream"; - public const string PARAMS = "params"; - public const string MESSAGE = "message"; - public const string SESSION_ID = "sessionId"; - public const string EXCEPTION_DETAILS = "exceptionDetails"; - public const string CONTEXT = "context"; - public const string REFERER = "referer"; - public const string ACCEPT = "accept"; - public const string COOKIES = "cookies"; - public const string PROMPT_TEXT = "promptText"; - public const string ENUMERABLE = "enumerable"; - public const string DATA = "data"; - public const string OBJECTS = "objects"; - public const string NAME = "name"; - public const string VALUE = "value"; - public const string TEXT = "text"; - public const string TARGET_ID = "targetId"; - public const string SCRIPT_SOURCE = "scriptSource"; - public const string OBJECT_ID = "objectId"; - public const string SUBTYPE = "subtype"; - public const string TYPE = "type"; - public const string UNSERIALIZABLE_VALUE = "unserializableValue"; - public const string PRODUCT = "product"; - public const string USER_AGENT = "userAgent"; - public const string FRAME = "frame"; - public const string PARENT_ID = "parentId"; - public const string URL = "url"; - public const string URLS = "urls"; - public const string CHILD_FRAMES = "childFrames"; - public const string FRAME_TREE = "frameTree"; - public const string CONTENT_SIZE = "contentSize"; - public const string WIDTH = "width"; - public const string HEIGHT = "height"; - public const string FRAME_ID = "frameId"; - public const string EXECUTION_CONTEXT_ID = "executionContextId"; - public const string ARGS = "args"; - public const string EVENT_ID = "eventId"; - public const string BROWSER_CONTEXT_ID = "browserContextId"; - public const string REQUEST_ID = "requestId"; - public const string INTERCEPTION_ID = "interceptionId"; - public const string HEADERS = "headers"; - public const string TARGET_INFO = "targetInfo"; - public const string POST_DATA = "postData"; - public const string MODIFIERS = "modifiers"; - public const string WINDOWS_VIRTUAL_KEY_CODE = "windowsVirtualKeyCode"; - public const string CODE = "code"; - public const string KEY = "key"; - public const string UNMODIFIED_TEXT = "unmodifiedText"; - public const string AUTO_REPEAT = "autoRepeat"; - public const string LOCATION = "location"; - public const string IS_KEYPAD = "isKeypad"; - public const string BUTTON = "button"; - public const string CLICK_COUNT = "clickCount"; - public const string OFFLINE = "offline"; - public const string LATENCY = "latency"; - public const string DOWNLOAD_THROUGHPUT = "downloadThroughput"; - public const string UPLOAD_THROUGHPUT = "uploadThroughput"; - public const string AUTH_CHALLENGE_RESPONSE = "authChallengeResponse"; - public const string CACHING_DISABLED = "cacheDisabled"; - public const string PATTERNS = "patterns"; - public const string ACTION = "action"; - public const string RAW_RESPONSE = "rawResponse"; - public const string ERROR_REASON = "errorReason"; - public const string X = "x"; - public const string Y = "y"; - } -} diff --git a/lib/PuppeteerSharp/Dialog.cs b/lib/PuppeteerSharp/Dialog.cs index b87356bc6..c1ceee30a 100755 --- a/lib/PuppeteerSharp/Dialog.cs +++ b/lib/PuppeteerSharp/Dialog.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Threading.Tasks; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp { @@ -60,8 +61,8 @@ public Task Accept(string promptText = "") { return _client.SendAsync("Page.handleJavaScriptDialog", new Dictionary { - { Constants.ACCEPT, true }, - { Constants.PROMPT_TEXT, promptText } + { MessageKeys.Accept, true }, + { MessageKeys.PromptText, promptText } }); } @@ -73,7 +74,7 @@ public Task Dismiss() { return _client.SendAsync("Page.handleJavaScriptDialog", new Dictionary { - { Constants.ACCEPT, false } + { MessageKeys.Accept, false } }); } } diff --git a/lib/PuppeteerSharp/ElementHandle.cs b/lib/PuppeteerSharp/ElementHandle.cs index 6d2b8bcc3..0c0d1aea0 100755 --- a/lib/PuppeteerSharp/ElementHandle.cs +++ b/lib/PuppeteerSharp/ElementHandle.cs @@ -198,7 +198,7 @@ public async Task ClickAsync(ClickOptions options = null) public Task UploadFileAsync(params string[] filePaths) { var files = filePaths.Select(Path.GetFullPath).ToArray(); - var objectId = RemoteObject[Constants.OBJECT_ID].AsString(); + var objectId = RemoteObject[MessageKeys.ObjectId].AsString(); return Client.SendAsync("DOM.setFileInputFiles", new { objectId, files }); } @@ -386,7 +386,7 @@ public async Task ContentFrameAsync() { var nodeInfo = await Client.SendAsync("DOM.describeNode", new Dictionary { - { Constants.OBJECT_ID, RemoteObject[Constants.OBJECT_ID] } + { MessageKeys.ObjectId, RemoteObject[MessageKeys.ObjectId] } }).ConfigureAwait(false); return string.IsNullOrEmpty(nodeInfo.Node.FrameId) ? null : _frameManager.Frames[nodeInfo.Node.FrameId]; @@ -419,7 +419,7 @@ private async Task<(decimal x, decimal y)> ClickablePointAsync() { result = await Client.SendAsync("DOM.getContentQuads", new Dictionary { - { Constants.OBJECT_ID, RemoteObject[Constants.OBJECT_ID] } + { MessageKeys.ObjectId, RemoteObject[MessageKeys.ObjectId] } }); } catch (Exception ex) @@ -491,7 +491,7 @@ private async Task GetBoxModelAsync() { return await Client.SendAsync("DOM.getBoxModel", new { - objectId = RemoteObject[Constants.OBJECT_ID].AsString() + objectId = RemoteObject[MessageKeys.ObjectId].AsString() }).ConfigureAwait(false); } catch (PuppeteerException ex) diff --git a/lib/PuppeteerSharp/ExecutionContext.cs b/lib/PuppeteerSharp/ExecutionContext.cs index 4f888e498..f47b8f6e4 100755 --- a/lib/PuppeteerSharp/ExecutionContext.cs +++ b/lib/PuppeteerSharp/ExecutionContext.cs @@ -1,9 +1,10 @@ using System; using System.Collections.Generic; -using System.Threading.Tasks; using System.Linq; -using Newtonsoft.Json.Linq; using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Newtonsoft.Json.Linq; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp { @@ -62,7 +63,7 @@ public async Task EvaluateExpressionAsync(string script) } /// - /// Executes a script in browser contextF + /// Executes a script in browser context /// /// The type to deserialize the result to /// Script to be evaluated in browser context @@ -128,7 +129,7 @@ public async Task QueryObjectsAsync(JSHandle prototypeHandle) throw new PuppeteerException("Prototype JSHandle is disposed!"); } - if (!((JObject)prototypeHandle.RemoteObject).TryGetValue(Constants.OBJECT_ID, out var objectId)) + if (!((JObject)prototypeHandle.RemoteObject).TryGetValue(MessageKeys.ObjectId, out var objectId)) { throw new PuppeteerException("Prototype JSHandle must not be referencing primitive value"); } @@ -138,7 +139,7 @@ public async Task QueryObjectsAsync(JSHandle prototypeHandle) {"prototypeObjectId", objectId.ToString()} }).ConfigureAwait(false); - return CreateJSHandle(response[Constants.OBJECTS]); + return CreateJSHandle(response[MessageKeys.Objects]); } internal async Task EvaluateExpressionHandleAsync(string script) @@ -177,7 +178,7 @@ internal async Task EvaluateFunctionHandleAsync(string script, params return await EvaluateHandleAsync("Runtime.callFunctionOn", new Dictionary { ["functionDeclaration"] = $"{script}\n{EvaluationScriptSuffix}\n", - [Constants.EXECUTION_CONTEXT_ID] = _contextId, + [MessageKeys.ExecutionContextId] = _contextId, ["arguments"] = args.Select(FormatArgument).ToArray(), ["returnByValue"] = false, ["awaitPromise"] = true, @@ -222,7 +223,7 @@ private async Task EvaluateHandleAsync(string method, dynamic args) { var response = await _client.SendAsync(method, args).ConfigureAwait(false); - var exceptionDetails = response[Constants.EXCEPTION_DETAILS]; + var exceptionDetails = response[MessageKeys.ExceptionDetails]; if (exceptionDetails != null) { diff --git a/lib/PuppeteerSharp/FrameManager.cs b/lib/PuppeteerSharp/FrameManager.cs index 47cfcbfcb..a0639d8e7 100644 --- a/lib/PuppeteerSharp/FrameManager.cs +++ b/lib/PuppeteerSharp/FrameManager.cs @@ -61,12 +61,12 @@ private void _client_MessageReceived(object sender, MessageEventArgs e) { case "Page.frameAttached": OnFrameAttached( - e.MessageData.SelectToken(Constants.FRAME_ID).ToObject(), + e.MessageData.SelectToken(MessageKeys.FrameId).ToObject(), e.MessageData.SelectToken("parentFrameId").ToObject()); break; case "Page.frameNavigated": - OnFrameNavigated(e.MessageData.SelectToken(Constants.FRAME).ToObject()); + OnFrameNavigated(e.MessageData.SelectToken(MessageKeys.Frame).ToObject()); break; case "Page.navigatedWithinDocument": @@ -82,11 +82,11 @@ private void _client_MessageReceived(object sender, MessageEventArgs e) break; case "Runtime.executionContextCreated": - OnExecutionContextCreated(e.MessageData.SelectToken(Constants.CONTEXT).ToObject()); + OnExecutionContextCreated(e.MessageData.SelectToken(MessageKeys.Context).ToObject()); break; case "Runtime.executionContextDestroyed": - OnExecutionContextDestroyed(e.MessageData.SelectToken(Constants.EXECUTION_CONTEXT_ID).ToObject()); + OnExecutionContextDestroyed(e.MessageData.SelectToken(MessageKeys.ExecutionContextId).ToObject()); break; case "Runtime.executionContextsCleared": OnExecutionContextsCleared(); diff --git a/lib/PuppeteerSharp/FrameTree.cs b/lib/PuppeteerSharp/FrameTree.cs index c0d86b8b3..28dafd473 100644 --- a/lib/PuppeteerSharp/FrameTree.cs +++ b/lib/PuppeteerSharp/FrameTree.cs @@ -1,6 +1,7 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using Newtonsoft.Json.Linq; +using PuppeteerSharp.Helpers; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp { @@ -13,14 +14,14 @@ internal FrameTree() internal FrameTree(JToken frameTree) { - var frame = frameTree[Constants.FRAME]; + var frame = frameTree[MessageKeys.Frame]; Frame = new FramePayload { - Id = frame[Constants.ID].AsString(), - ParentId = frame[Constants.PARENT_ID].AsString(), - Name = frame[Constants.NAME].AsString(), - Url = frame[Constants.URL].AsString() + Id = frame[MessageKeys.Id].AsString(), + ParentId = frame[MessageKeys.ParentId].AsString(), + Name = frame[MessageKeys.Name].AsString(), + Url = frame[MessageKeys.Url].AsString() }; Childs = new List(); @@ -36,25 +37,25 @@ internal FrameTree(JToken frameTree) private void LoadChilds(FrameTree frame, JToken frameTree) { - var childFrames = frameTree[Constants.CHILD_FRAMES]; + var childFrames = frameTree[MessageKeys.ChildFrames]; if (childFrames != null) { foreach (var item in childFrames) { - var childFrame = item[Constants.FRAME]; + var childFrame = item[MessageKeys.Frame]; var newFrame = new FrameTree { Frame = new FramePayload { - Id = childFrame[Constants.ID].AsString(), - ParentId = childFrame[Constants.PARENT_ID].AsString(), - Url = childFrame[Constants.URL].AsString() + Id = childFrame[MessageKeys.Id].AsString(), + ParentId = childFrame[MessageKeys.ParentId].AsString(), + Url = childFrame[MessageKeys.Url].AsString() } }; - if ((item as JObject)[Constants.CHILD_FRAMES] != null) + if ((item as JObject)[MessageKeys.ChildFrames] != null) { LoadChilds(newFrame, item); } diff --git a/lib/PuppeteerSharp/JTokenExtensions.cs b/lib/PuppeteerSharp/Helpers/JTokenExtensions.cs similarity index 94% rename from lib/PuppeteerSharp/JTokenExtensions.cs rename to lib/PuppeteerSharp/Helpers/JTokenExtensions.cs index caba9735a..edf34af0e 100644 --- a/lib/PuppeteerSharp/JTokenExtensions.cs +++ b/lib/PuppeteerSharp/Helpers/JTokenExtensions.cs @@ -1,6 +1,6 @@ using Newtonsoft.Json.Linq; -namespace PuppeteerSharp +namespace PuppeteerSharp.Helpers { /// /// A set of extension methods for JToken diff --git a/lib/PuppeteerSharp/Helpers/RemoteObjectHelper.cs b/lib/PuppeteerSharp/Helpers/RemoteObjectHelper.cs index 40792c2ca..ec337ab25 100755 --- a/lib/PuppeteerSharp/Helpers/RemoteObjectHelper.cs +++ b/lib/PuppeteerSharp/Helpers/RemoteObjectHelper.cs @@ -1,9 +1,8 @@ -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System; -using System.Linq; +using System; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json.Linq; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp.Helpers { @@ -11,7 +10,7 @@ internal class RemoteObjectHelper { internal static object ValueFromRemoteObject(JToken remoteObject) { - var unserializableValue = remoteObject[Constants.UNSERIALIZABLE_VALUE]?.AsString(); + var unserializableValue = remoteObject[MessageKeys.UnserializableValue]?.AsString(); if (unserializableValue != null) { @@ -30,7 +29,7 @@ internal static object ValueFromRemoteObject(JToken remoteObject) } } - var value = remoteObject[Constants.VALUE]; + var value = remoteObject[MessageKeys.Value]; if (value == null) { @@ -38,7 +37,7 @@ internal static object ValueFromRemoteObject(JToken remoteObject) } // https://chromedevtools.github.io/devtools-protocol/tot/Runtime#type-RemoteObject - var objectType = remoteObject[Constants.TYPE].AsString(); + var objectType = remoteObject[MessageKeys.Type].AsString(); switch (objectType) { @@ -59,7 +58,7 @@ internal static object ValueFromRemoteObject(JToken remoteObject) internal static async Task ReleaseObject(CDPSession client, JToken remoteObject, ILogger logger) { - var objectId = remoteObject[Constants.OBJECT_ID]?.AsString(); + var objectId = remoteObject[MessageKeys.ObjectId]?.AsString(); if (objectId == null) { diff --git a/lib/PuppeteerSharp/Input/Keyboard.cs b/lib/PuppeteerSharp/Input/Keyboard.cs index 783182e8c..4eb0e805d 100755 --- a/lib/PuppeteerSharp/Input/Keyboard.cs +++ b/lib/PuppeteerSharp/Input/Keyboard.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp.Input { @@ -44,16 +45,16 @@ public Task DownAsync(string key, DownOptions options = null) return _client.SendAsync("Input.dispatchKeyEvent", new Dictionary { - { Constants.TYPE, text != null ? "keyDown" : "rawKeyDown" }, - { Constants.MODIFIERS, Modifiers }, - { Constants.WINDOWS_VIRTUAL_KEY_CODE, description.KeyCode }, - { Constants.CODE, description.Code }, - { Constants.KEY, description.Key }, - { Constants.TEXT, text }, - { Constants.UNMODIFIED_TEXT, text }, - { Constants.AUTO_REPEAT, autoRepeat }, - { Constants.LOCATION, description.Location }, - { Constants.IS_KEYPAD, description.Location == 3 } + { MessageKeys.Type, text != null ? "keyDown" : "rawKeyDown" }, + { MessageKeys.Modifiers, Modifiers }, + { MessageKeys.WindowsVirtualKeyCode, description.KeyCode }, + { MessageKeys.Code, description.Code }, + { MessageKeys.Key, description.Key }, + { MessageKeys.Text, text }, + { MessageKeys.UnmodifiedText, text }, + { MessageKeys.AutoRepeat, autoRepeat }, + { MessageKeys.Location, description.Location }, + { MessageKeys.IsKeypad, description.Location == 3 } }); } @@ -71,12 +72,12 @@ public Task UpAsync(string key) return _client.SendAsync("Input.dispatchKeyEvent", new Dictionary { - { Constants.TYPE, "keyUp" }, - { Constants.MODIFIERS, Modifiers }, - { Constants.KEY, description.Key }, - { Constants.WINDOWS_VIRTUAL_KEY_CODE, description.KeyCode }, - { Constants.CODE, description.Code }, - { Constants.LOCATION, description.Location } + { MessageKeys.Type, "keyUp" }, + { MessageKeys.Modifiers, Modifiers }, + { MessageKeys.Key, description.Key }, + { MessageKeys.WindowsVirtualKeyCode, description.KeyCode }, + { MessageKeys.Code, description.Code }, + { MessageKeys.Location, description.Location } }); } @@ -86,7 +87,7 @@ public Task UpAsync(string key) /// Character to send into the page /// Task public Task SendCharacterAsync(string charText) - => _client.SendAsync("Input.insertText", new Dictionary { [Constants.TEXT] = charText }); + => _client.SendAsync("Input.insertText", new Dictionary { [MessageKeys.Text] = charText }); /// /// Sends a keydown, keypress/input, and keyup event for each character in the text. diff --git a/lib/PuppeteerSharp/Input/Mouse.cs b/lib/PuppeteerSharp/Input/Mouse.cs index 4d42a6de6..02089670f 100755 --- a/lib/PuppeteerSharp/Input/Mouse.cs +++ b/lib/PuppeteerSharp/Input/Mouse.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Threading.Tasks; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp.Input { @@ -47,11 +48,11 @@ public async Task MoveAsync(decimal x, decimal y, MoveOptions options = null) { await _client.SendAsync("Input.dispatchMouseEvent", new Dictionary() { - { Constants.TYPE, "mouseMoved" }, - { Constants.BUTTON, _button }, - { Constants.X, fromX + ((_x - fromX) * ((decimal)i / steps)) }, - { Constants.Y, fromY + ((_y - fromY) * ((decimal)i / steps)) }, - { Constants.MODIFIERS, _keyboard.Modifiers} + { MessageKeys.Type, "mouseMoved" }, + { MessageKeys.Button, _button }, + { MessageKeys.X, fromX + ((_x - fromX) * ((decimal)i / steps)) }, + { MessageKeys.Y, fromY + ((_y - fromY) * ((decimal)i / steps)) }, + { MessageKeys.Modifiers, _keyboard.Modifiers} }).ConfigureAwait(false); } } @@ -90,12 +91,12 @@ public Task DownAsync(ClickOptions options = null) return _client.SendAsync("Input.dispatchMouseEvent", new Dictionary() { - { Constants.TYPE, "mousePressed" }, - { Constants.BUTTON, _button }, - { Constants.X, _x }, - { Constants.Y, _y }, - { Constants.MODIFIERS, _keyboard.Modifiers }, - { Constants.CLICK_COUNT, options.ClickCount } + { MessageKeys.Type, "mousePressed" }, + { MessageKeys.Button, _button }, + { MessageKeys.X, _x }, + { MessageKeys.Y, _y }, + { MessageKeys.Modifiers, _keyboard.Modifiers }, + { MessageKeys.ClickCount, options.ClickCount } }); } @@ -112,12 +113,12 @@ public Task UpAsync(ClickOptions options = null) return _client.SendAsync("Input.dispatchMouseEvent", new Dictionary() { - { Constants.TYPE, "mouseReleased" }, - { Constants.BUTTON, options.Button }, - { Constants.X, _x }, - { Constants.Y, _y }, - { Constants.MODIFIERS, _keyboard.Modifiers }, - { Constants.CLICK_COUNT, options.ClickCount } + { MessageKeys.Type, "mouseReleased" }, + { MessageKeys.Button, options.Button }, + { MessageKeys.X, _x }, + { MessageKeys.Y, _y }, + { MessageKeys.Modifiers, _keyboard.Modifiers }, + { MessageKeys.ClickCount, options.ClickCount } }); } } diff --git a/lib/PuppeteerSharp/JSHandle.cs b/lib/PuppeteerSharp/JSHandle.cs index a2dd3a8b9..615a8f3ae 100755 --- a/lib/PuppeteerSharp/JSHandle.cs +++ b/lib/PuppeteerSharp/JSHandle.cs @@ -1,9 +1,9 @@ -using Microsoft.Extensions.Logging; +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using PuppeteerSharp.Helpers; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp { @@ -81,20 +81,20 @@ public async Task GetPropertyAsync(string propertyName) { var response = await Client.SendAsync("Runtime.getProperties", new { - objectId = RemoteObject[Constants.OBJECT_ID].AsString(), + objectId = RemoteObject[MessageKeys.ObjectId].AsString(), ownProperties = true }).ConfigureAwait(false); var result = new Dictionary(); - foreach (var property in response[Constants.RESULT]) + foreach (var property in response[MessageKeys.Result]) { - if (property[Constants.ENUMERABLE] == null) + if (property[MessageKeys.Enumerable] == null) { continue; } - result.Add(property[Constants.NAME].AsString(), ExecutionContext.CreateJSHandle(property[Constants.VALUE])); + result.Add(property[MessageKeys.Name].AsString(), ExecutionContext.CreateJSHandle(property[MessageKeys.Value])); } return result; } @@ -118,18 +118,18 @@ public async Task GetPropertyAsync(string propertyName) /// public async Task JsonValueAsync() { - var objectId = RemoteObject[Constants.OBJECT_ID]; + var objectId = RemoteObject[MessageKeys.ObjectId]; if (objectId != null) { var response = await Client.SendAsync("Runtime.callFunctionOn", new Dictionary { ["functionDeclaration"] = "function() { return this; }", - [Constants.OBJECT_ID] = objectId, + [MessageKeys.ObjectId] = objectId, ["returnByValue"] = true, ["awaitPromise"] = true }).ConfigureAwait(false); - return (T)RemoteObjectHelper.ValueFromRemoteObject(response[Constants.RESULT]); + return (T)RemoteObjectHelper.ValueFromRemoteObject(response[MessageKeys.Result]); } return (T)RemoteObjectHelper.ValueFromRemoteObject(RemoteObject); @@ -153,9 +153,9 @@ public async Task DisposeAsync() /// public override string ToString() { - if ((RemoteObject)[Constants.OBJECT_ID] != null) + if ((RemoteObject)[MessageKeys.ObjectId] != null) { - var type = RemoteObject[Constants.SUBTYPE] ?? RemoteObject[Constants.TYPE]; + var type = RemoteObject[MessageKeys.Subtype] ?? RemoteObject[MessageKeys.Type]; return "JSHandle@" + type; } @@ -174,21 +174,21 @@ internal object FormatArgument(ExecutionContext context) throw new PuppeteerException("JSHandle is disposed!"); } - var unserializableValue = RemoteObject[Constants.UNSERIALIZABLE_VALUE]; + var unserializableValue = RemoteObject[MessageKeys.UnserializableValue]; if (unserializableValue != null) { return unserializableValue; } - if (RemoteObject[Constants.OBJECT_ID] == null) + if (RemoteObject[MessageKeys.ObjectId] == null) { - var value = RemoteObject[Constants.VALUE]; + var value = RemoteObject[MessageKeys.Value]; return new { value }; } - var objectId = RemoteObject[Constants.OBJECT_ID]; + var objectId = RemoteObject[MessageKeys.ObjectId]; return new { objectId }; } diff --git a/lib/PuppeteerSharp/MessageException.cs b/lib/PuppeteerSharp/MessageException.cs index 2cc8c845c..30bd9fd7c 100644 --- a/lib/PuppeteerSharp/MessageException.cs +++ b/lib/PuppeteerSharp/MessageException.cs @@ -1,5 +1,6 @@ using System; using Newtonsoft.Json.Linq; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp { @@ -30,15 +31,15 @@ internal MessageException(MessageTask callback, JObject obj) : base(GetCallbackM internal static string GetCallbackMessage(MessageTask callback, JObject obj) { - var error = obj.SelectToken(Constants.ERROR); - var message = $"Protocol error ({callback.Method}): {error[Constants.MESSAGE]}"; + var error = obj.SelectToken(MessageKeys.Error); + var message = $"Protocol error ({callback.Method}): {error[MessageKeys.Message]}"; - if (error[Constants.DATA] != null) + if (error[MessageKeys.Data] != null) { - message += $" {error[Constants.DATA]}"; + message += $" {error[MessageKeys.Data]}"; } - return !string.IsNullOrEmpty(error[Constants.MESSAGE].ToString()) ? RewriteErrorMeesage(message) : string.Empty; + return !string.IsNullOrEmpty(error[MessageKeys.Message].ToString()) ? RewriteErrorMeesage(message) : string.Empty; } } } \ No newline at end of file diff --git a/lib/PuppeteerSharp/Messaging/MessageKeys.cs b/lib/PuppeteerSharp/Messaging/MessageKeys.cs new file mode 100644 index 000000000..3d46db68a --- /dev/null +++ b/lib/PuppeteerSharp/Messaging/MessageKeys.cs @@ -0,0 +1,78 @@ +namespace PuppeteerSharp.Messaging +{ + /// + /// Keys used in messages + /// + internal class MessageKeys + { + public const string Id = "id"; + public const string Error = "error"; + public const string Result = "result"; + public const string Method = "method"; + public const string Stream = "stream"; + public const string Params = "params"; + public const string Message = "message"; + public const string SessionId = "sessionId"; + public const string ExceptionDetails = "exceptionDetails"; + public const string Context = "context"; + public const string Referer = "referer"; + public const string Accept = "accept"; + public const string Cookies = "cookies"; + public const string PromptText = "promptText"; + public const string Enumerable = "enumerable"; + public const string Data = "data"; + public const string Objects = "objects"; + public const string Name = "name"; + public const string Value = "value"; + public const string Text = "text"; + public const string TargetId = "targetId"; + public const string ScriptSource = "scriptSource"; + public const string ObjectId = "objectId"; + public const string Subtype = "subtype"; + public const string Type = "type"; + public const string UnserializableValue = "unserializableValue"; + public const string Product = "product"; + public const string UserAgent = "userAgent"; + public const string Frame = "frame"; + public const string ParentId = "parentId"; + public const string Url = "url"; + public const string Urls = "urls"; + public const string ChildFrames = "childFrames"; + public const string FrameTree = "frameTree"; + public const string ContentSize = "contentSize"; + public const string Width = "width"; + public const string Height = "height"; + public const string FrameId = "frameId"; + public const string ExecutionContextId = "executionContextId"; + public const string Args = "args"; + public const string EventId = "eventId"; + public const string BrowserContextId = "browserContextId"; + public const string RequestId = "requestId"; + public const string InterceptionId = "interceptionId"; + public const string Headers = "headers"; + public const string TargetInfo = "targetInfo"; + public const string PostData = "postData"; + public const string Modifiers = "modifiers"; + public const string WindowsVirtualKeyCode = "windowsVirtualKeyCode"; + public const string Code = "code"; + public const string Key = "key"; + public const string UnmodifiedText = "unmodifiedText"; + public const string AutoRepeat = "autoRepeat"; + public const string Location = "location"; + public const string IsKeypad = "isKeypad"; + public const string Button = "button"; + public const string ClickCount = "clickCount"; + public const string Offline = "offline"; + public const string Latency = "latency"; + public const string DownloadThroughput = "downloadThroughput"; + public const string UploadThroughput = "uploadThroughput"; + public const string AuthChallengeResponse = "authChallengeResponse"; + public const string CachingDisabled = "cacheDisabled"; + public const string Patterns = "patterns"; + public const string Action = "action"; + public const string RawResponse = "rawResponse"; + public const string ErrorReason = "errorReason"; + public const string X = "x"; + public const string Y = "y"; + } +} diff --git a/lib/PuppeteerSharp/NetworkManager.cs b/lib/PuppeteerSharp/NetworkManager.cs index 4944555d8..4a0e552bf 100644 --- a/lib/PuppeteerSharp/NetworkManager.cs +++ b/lib/PuppeteerSharp/NetworkManager.cs @@ -63,7 +63,7 @@ internal Task SetExtraHTTPHeadersAsync(Dictionary extraHTTPHeade } return _client.SendAsync("Network.setExtraHTTPHeaders", new Dictionary { - { Constants.HEADERS, _extraHTTPHeaders } + { MessageKeys.Headers, _extraHTTPHeaders } }); } @@ -75,10 +75,10 @@ internal async Task SetOfflineModeAsync(bool value) await _client.SendAsync("Network.emulateNetworkConditions", new Dictionary { - { Constants.OFFLINE, value}, - { Constants.LATENCY, 0}, - { Constants.DOWNLOAD_THROUGHPUT, -1}, - { Constants.UPLOAD_THROUGHPUT, -1} + { MessageKeys.Offline, value}, + { MessageKeys.Latency, 0}, + { MessageKeys.DownloadThroughput, -1}, + { MessageKeys.UploadThroughput, -1} }).ConfigureAwait(false); } } @@ -86,7 +86,7 @@ internal async Task SetOfflineModeAsync(bool value) internal Task SetUserAgentAsync(string userAgent) => _client.SendAsync("Network.setUserAgentOverride", new Dictionary { - { Constants.USER_AGENT, userAgent } + { MessageKeys.UserAgent, userAgent } }); internal Task SetRequestInterceptionAsync(bool value) @@ -205,8 +205,8 @@ private async Task OnRequestInterceptedAsync(RequestInterceptedResponse e) { await _client.SendAsync("Network.continueInterceptedRequest", new Dictionary { - { Constants.INTERCEPTION_ID, e.InterceptionId }, - { Constants.AUTH_CHALLENGE_RESPONSE, new + { MessageKeys.InterceptionId, e.InterceptionId }, + { MessageKeys.AuthChallengeResponse, new { response, username = credentials.Username, @@ -227,7 +227,7 @@ private async Task OnRequestInterceptedAsync(RequestInterceptedResponse e) { await _client.SendAsync("Network.continueInterceptedRequest", new Dictionary { - { Constants.INTERCEPTION_ID, e.InterceptionId } + { MessageKeys.InterceptionId, e.InterceptionId } }).ConfigureAwait(false); } catch (PuppeteerException ex) @@ -364,11 +364,11 @@ private async Task UpdateProtocolRequestInterceptionAsync() await Task.WhenAll( _client.SendAsync("Network.setCacheDisabled", new Dictionary { - { Constants.CACHING_DISABLED, enabled} + { MessageKeys.CachingDisabled, enabled} }), _client.SendAsync("Network.setRequestInterception", new Dictionary { - { Constants.PATTERNS, patterns} + { MessageKeys.Patterns, patterns} }) ).ConfigureAwait(false); } diff --git a/lib/PuppeteerSharp/Page.cs b/lib/PuppeteerSharp/Page.cs index b381d101f..2cc539d4e 100644 --- a/lib/PuppeteerSharp/Page.cs +++ b/lib/PuppeteerSharp/Page.cs @@ -479,10 +479,10 @@ public async Task GetCookiesAsync(params string[] urls) { var response = await Client.SendAsync("Network.getCookies", new Dictionary { - { Constants.URLS, urls.Length > 0 ? urls : new string[] { Url } } + { MessageKeys.Urls, urls.Length > 0 ? urls : new string[] { Url } } }).ConfigureAwait(false); - return response[Constants.COOKIES].ToObject(); + return response[MessageKeys.Cookies].ToObject(); } /// @@ -510,7 +510,7 @@ public async Task SetCookieAsync(params CookieParam[] cookies) { await Client.SendAsync("Network.setCookies", new Dictionary { - { Constants.COOKIES, cookies } + { MessageKeys.Cookies, cookies } }).ConfigureAwait(false); } } @@ -698,7 +698,7 @@ public Task ExposeFunctionAsync(string name, Func puppeteerFun /// public async Task GoToAsync(string url, NavigationOptions options) { - var referrer = _networkManager.ExtraHTTPHeaders?.GetValueOrDefault(Constants.REFERER); + var referrer = _networkManager.ExtraHTTPHeaders?.GetValueOrDefault(MessageKeys.Referer); var requests = new Dictionary(); void createRequestEventListener(object sender, RequestEventArgs e) @@ -884,7 +884,7 @@ public async Task PdfDataAsync(PdfOptions options) preferCSSPageSize = options.PreferCSSPageSize }).ConfigureAwait(false); - var buffer = Convert.FromBase64String(result.GetValue(Constants.DATA).AsString()); + var buffer = Convert.FromBase64String(result.GetValue(MessageKeys.Data).AsString()); return buffer; } @@ -1584,7 +1584,7 @@ void responseEventListener(object sender, ResponseCreatedEventArgs e) { await client.SendAsync("Page.enable", null).ConfigureAwait(false); var result = await client.SendAsync("Page.getFrameTree").ConfigureAwait(false); - var page = new Page(client, target, new FrameTree(result[Constants.FRAME_TREE]), ignoreHTTPSErrors, screenshotTaskQueue); + var page = new Page(client, target, new FrameTree(result[MessageKeys.FrameTree]), ignoreHTTPSErrors, screenshotTaskQueue); await Task.WhenAll( client.SendAsync("Target.setAutoAttach", new { autoAttach = true, waitForDebuggerOnStart = false }), @@ -1665,10 +1665,10 @@ private async Task PerformScreenshot(ScreenshotType type, ScreenshotOpti if (options != null && options.FullPage) { var metrics = await Client.SendAsync("Page.getLayoutMetrics").ConfigureAwait(false); - var contentSize = metrics[Constants.CONTENT_SIZE]; + var contentSize = metrics[MessageKeys.ContentSize]; - var width = Convert.ToInt32(Math.Ceiling(contentSize[Constants.WIDTH].Value())); - var height = Convert.ToInt32(Math.Ceiling(contentSize[Constants.HEIGHT].Value())); + var width = Convert.ToInt32(Math.Ceiling(contentSize[MessageKeys.Width].Value())); + var height = Convert.ToInt32(Math.Ceiling(contentSize[MessageKeys.Height].Value())); // Overwrite clip for full page at all times. clip = new Clip @@ -1745,7 +1745,7 @@ private async Task PerformScreenshot(ScreenshotType type, ScreenshotOpti await SetViewportAsync(Viewport).ConfigureAwait(false); } - return result.GetValue(Constants.DATA).AsString(); + return result.GetValue(MessageKeys.Data).AsString(); } private decimal ConvertPrintParameterToInches(object parameter) @@ -1809,7 +1809,7 @@ private async void Client_MessageReceived(object sender, MessageEventArgs e) OnDialog(e.MessageData.ToObject()); break; case "Runtime.exceptionThrown": - HandleException(e.MessageData.SelectToken(Constants.EXCEPTION_DETAILS).ToObject()); + HandleException(e.MessageData.SelectToken(MessageKeys.ExceptionDetails).ToObject()); break; case "Security.certificateError": await OnCertificateError(e.MessageData.ToObject()).ConfigureAwait(false); @@ -1858,7 +1858,7 @@ private async Task ExecuteBinding(BindingCalledResponse e) var binding = _pageBindings[e.Payload.Name]; var methodParams = binding.Method.GetParameters().Select(parameter => parameter.ParameterType).ToArray(); - var args = e.Payload.JsonObject.GetValue(Constants.ARGS).Select((token, i) => token.ToObject(methodParams[i])).ToArray(); + var args = e.Payload.JsonObject.GetValue(MessageKeys.Args).Select((token, i) => token.ToObject(methodParams[i])).ToArray(); result = binding.DynamicInvoke(args); if (result is Task taskResult) @@ -1877,7 +1877,7 @@ private async Task ExecuteBinding(BindingCalledResponse e) private void OnDetachedFromTarget(MessageEventArgs e) { - var sessionId = e.MessageData.SelectToken(Constants.SESSION_ID).AsString(); + var sessionId = e.MessageData.SelectToken(MessageKeys.SessionId).AsString(); if (_workers.TryGetValue(sessionId, out var worker)) { WorkerDestroyed?.Invoke(this, new WorkerEventArgs(worker)); @@ -1887,8 +1887,8 @@ private void OnDetachedFromTarget(MessageEventArgs e) private async Task OnAttachedToTarget(MessageEventArgs e) { - var targetInfo = e.MessageData.SelectToken(Constants.TARGET_INFO).ToObject(); - var sessionId = e.MessageData.SelectToken(Constants.SESSION_ID).ToObject(); + var targetInfo = e.MessageData.SelectToken(MessageKeys.TargetInfo).ToObject(); + var sessionId = e.MessageData.SelectToken(MessageKeys.SessionId).ToObject(); if (targetInfo.Type != TargetType.Worker) { try @@ -1943,8 +1943,8 @@ private async Task OnCertificateError(CertificateErrorResponse e) { await Client.SendAsync("Security.handleCertificateError", new Dictionary { - { Constants.EVENT_ID, e.EventId }, - { Constants.ACTION, "continue"} + { MessageKeys.EventId, e.EventId }, + { MessageKeys.Action, "continue"} }).ConfigureAwait(false); } catch (PuppeteerException ex) @@ -2001,7 +2001,7 @@ private async Task AddConsoleMessage(ConsoleType type, JSHandle[] values) return; } - var tokens = values.Select(i => i.RemoteObject[Constants.OBJECT_ID] != null + var tokens = values.Select(i => i.RemoteObject[MessageKeys.ObjectId] != null ? i.ToString() : RemoteObjectHelper.ValueFromRemoteObject(i.RemoteObject)); diff --git a/lib/PuppeteerSharp/PageCoverage/CSSCoverage.cs b/lib/PuppeteerSharp/PageCoverage/CSSCoverage.cs index b7b1f4b12..94d8bf57e 100755 --- a/lib/PuppeteerSharp/PageCoverage/CSSCoverage.cs +++ b/lib/PuppeteerSharp/PageCoverage/CSSCoverage.cs @@ -1,9 +1,9 @@ -using Microsoft.Extensions.Logging; -using Newtonsoft.Json.Linq; -using PuppeteerSharp.Messaging; -using System; +using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using PuppeteerSharp.Helpers; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp.PageCoverage { @@ -127,7 +127,7 @@ private async Task OnStyleSheetAdded(CSSStyleSheetAddedResponse styleSheetAddedR }).ConfigureAwait(false); _stylesheetURLs.Add(styleSheetAddedResponse.Header.StyleSheetId, styleSheetAddedResponse.Header.SourceURL); - _stylesheetSources.Add(styleSheetAddedResponse.Header.StyleSheetId, response[Constants.TEXT].AsString()); + _stylesheetSources.Add(styleSheetAddedResponse.Header.StyleSheetId, response[MessageKeys.Text].AsString()); } catch (Exception ex) { diff --git a/lib/PuppeteerSharp/PageCoverage/JSCoverage.cs b/lib/PuppeteerSharp/PageCoverage/JSCoverage.cs index 8a64fac30..bbbc8cd1a 100755 --- a/lib/PuppeteerSharp/PageCoverage/JSCoverage.cs +++ b/lib/PuppeteerSharp/PageCoverage/JSCoverage.cs @@ -1,10 +1,10 @@ -using PuppeteerSharp.Messaging; -using System; -using System.Linq; +using System; using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Newtonsoft.Json.Linq; +using PuppeteerSharp.Helpers; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp.PageCoverage { @@ -121,7 +121,7 @@ private async Task OnScriptParsed(DebuggerScriptParsedResponse scriptParseRespon { var response = await _client.SendAsync("Debugger.getScriptSource", new { scriptId = scriptParseResponse.ScriptId }).ConfigureAwait(false); _scriptURLs.Add(scriptParseResponse.ScriptId, scriptParseResponse.Url); - _scriptSources.Add(scriptParseResponse.ScriptId, response[Constants.SCRIPT_SOURCE].AsString()); + _scriptSources.Add(scriptParseResponse.ScriptId, response[MessageKeys.ScriptSource].AsString()); } catch (Exception ex) { diff --git a/lib/PuppeteerSharp/Request.cs b/lib/PuppeteerSharp/Request.cs index 5cc544a46..22e9fba7b 100755 --- a/lib/PuppeteerSharp/Request.cs +++ b/lib/PuppeteerSharp/Request.cs @@ -1,11 +1,11 @@ -using Microsoft.Extensions.Logging; -using PuppeteerSharp.Messaging; -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using PuppeteerSharp.Messaging; namespace PuppeteerSharp { @@ -166,25 +166,25 @@ public async Task ContinueAsync(Payload overrides = null) try { - var requestData = new Dictionary { [Constants.INTERCEPTION_ID] = InterceptionId }; + var requestData = new Dictionary { [MessageKeys.InterceptionId] = InterceptionId }; if (overrides?.Url != null) { - requestData[Constants.URL] = overrides.Url; + requestData[MessageKeys.Url] = overrides.Url; } if (overrides?.Method != null) { - requestData[Constants.METHOD] = overrides.Method.ToString(); + requestData[MessageKeys.Method] = overrides.Method.ToString(); } if (overrides?.PostData != null) { - requestData[Constants.POST_DATA] = overrides.PostData; + requestData[MessageKeys.PostData] = overrides.PostData; } if (overrides?.Headers?.Count > 0) { - requestData[Constants.HEADERS] = overrides.Headers; + requestData[MessageKeys.Headers] = overrides.Headers; } await _client.SendAsync("Network.continueInterceptedRequest", requestData).ConfigureAwait(false); @@ -265,8 +265,8 @@ public async Task RespondAsync(ResponseData response) { await _client.SendAsync("Network.continueInterceptedRequest", new Dictionary { - { Constants.INTERCEPTION_ID, InterceptionId }, - { Constants.RAW_RESPONSE, Convert.ToBase64String(responseData) } + { MessageKeys.InterceptionId, InterceptionId }, + { MessageKeys.RawResponse, Convert.ToBase64String(responseData) } }).ConfigureAwait(false); } catch (PuppeteerException ex) @@ -302,8 +302,8 @@ public async Task AbortAsync(RequestAbortErrorCode errorCode = RequestAbortError { await _client.SendAsync("Network.continueInterceptedRequest", new Dictionary { - { Constants.INTERCEPTION_ID, InterceptionId }, - { Constants.ERROR_REASON, errorReason } + { MessageKeys.InterceptionId, InterceptionId }, + { MessageKeys.ErrorReason, errorReason } }).ConfigureAwait(false); } catch (PuppeteerException ex) diff --git a/lib/PuppeteerSharp/Response.cs b/lib/PuppeteerSharp/Response.cs index 317a40e7c..75a91b05f 100755 --- a/lib/PuppeteerSharp/Response.cs +++ b/lib/PuppeteerSharp/Response.cs @@ -107,7 +107,7 @@ public async ValueTask BufferAsync() { var response = await _client.SendAsync("Network.getResponseBody", new Dictionary { - { Constants.REQUEST_ID, Request.RequestId } + { MessageKeys.RequestId, Request.RequestId } }).ConfigureAwait(false); _buffer = response.Base64Encoded diff --git a/lib/PuppeteerSharp/Worker.cs b/lib/PuppeteerSharp/Worker.cs index 427fae41e..d515ca565 100644 --- a/lib/PuppeteerSharp/Worker.cs +++ b/lib/PuppeteerSharp/Worker.cs @@ -113,7 +113,7 @@ internal async void OnMessageReceived(object sender, MessageEventArgs e) } private void OnExceptionThrown(MessageEventArgs e) - => _exceptionThrown(e.MessageData.SelectToken(Constants.EXCEPTION_DETAILS).ToObject()); + => _exceptionThrown(e.MessageData.SelectToken(MessageKeys.ExceptionDetails).ToObject()); private async Task OnConsoleAPICalled(MessageEventArgs e) { @@ -130,7 +130,7 @@ private void OnExecutionContextCreated(MessageEventArgs e) _jsHandleFactory = (ctx, remoteObject) => new JSHandle(ctx, _client, remoteObject); _executionContext = new ExecutionContext( _client, - e.MessageData.SelectToken(Constants.CONTEXT).ToObject(), + e.MessageData.SelectToken(MessageKeys.Context).ToObject(), null); _executionContextCallback.TrySetResult(_executionContext); }