forked from hardkoded/puppeteer-sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LifecycleWatcher.cs
194 lines (162 loc) · 7 KB
/
LifecycleWatcher.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using PuppeteerSharp.Helpers;
namespace PuppeteerSharp
{
internal sealed class LifecycleWatcher : IDisposable
{
private static readonly Dictionary<WaitUntilNavigation, string> _puppeteerToProtocolLifecycle =
new()
{
[WaitUntilNavigation.Load] = "load",
[WaitUntilNavigation.DOMContentLoaded] = "DOMContentLoaded",
[WaitUntilNavigation.Networkidle0] = "networkIdle",
[WaitUntilNavigation.Networkidle2] = "networkAlmostIdle",
};
private static readonly WaitUntilNavigation[] _defaultWaitUntil = { WaitUntilNavigation.Load };
private readonly FrameManager _frameManager;
private readonly Frame _frame;
private readonly IEnumerable<string> _expectedLifecycle;
private readonly int _timeout;
private readonly string _initialLoaderId;
private readonly TaskCompletionSource<bool> _newDocumentNavigationTaskWrapper = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<bool> _sameDocumentNavigationTaskWrapper = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<bool> _lifecycleTaskWrapper = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<bool> _terminationTaskWrapper = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly CancellationTokenSource _terminationCancellationToken = new();
private IRequest _navigationRequest;
private bool _hasSameDocumentNavigation;
private bool _swapped;
public LifecycleWatcher(
FrameManager frameManager,
Frame frame,
WaitUntilNavigation[] waitUntil,
int timeout)
{
_expectedLifecycle = (waitUntil ?? _defaultWaitUntil).Select(w =>
{
var protocolEvent = _puppeteerToProtocolLifecycle.GetValueOrDefault(w);
Contract.Assert(protocolEvent != null, $"Unknown value for options.waitUntil: {w}");
return protocolEvent;
});
_frameManager = frameManager;
_frame = frame;
_initialLoaderId = frame.LoaderId;
_timeout = timeout;
_hasSameDocumentNavigation = false;
frameManager.LifecycleEvent += FrameManager_LifecycleEvent;
frameManager.FrameNavigatedWithinDocument += NavigatedWithinDocument;
frameManager.FrameNavigated += Navigated;
frameManager.FrameDetached += OnFrameDetached;
frameManager.NetworkManager.Request += OnRequest;
frameManager.Client.Disconnected += OnClientDisconnected;
frameManager.FrameSwapped += FrameManager_FrameSwapped;
CheckLifecycleComplete();
}
public Task<bool> SameDocumentNavigationTask => _sameDocumentNavigationTaskWrapper.Task;
public Task<bool> NewDocumentNavigationTask => _newDocumentNavigationTaskWrapper.Task;
public Response NavigationResponse => (Response)_navigationRequest?.Response;
public Task TimeoutOrTerminationTask => _terminationTaskWrapper.Task.WithTimeout(_timeout, cancellationToken: _terminationCancellationToken.Token);
public Task LifecycleTask => _lifecycleTaskWrapper.Task;
public void Dispose()
{
_frameManager.LifecycleEvent -= FrameManager_LifecycleEvent;
_frameManager.FrameNavigatedWithinDocument -= NavigatedWithinDocument;
_frameManager.FrameNavigated -= Navigated;
_frameManager.FrameDetached -= OnFrameDetached;
_frameManager.NetworkManager.Request -= OnRequest;
_frameManager.Client.Disconnected -= OnClientDisconnected;
_frameManager.FrameSwapped -= FrameManager_FrameSwapped;
_terminationCancellationToken.Cancel();
_terminationCancellationToken.Dispose();
}
private void OnClientDisconnected(object sender, EventArgs e)
=> Terminate(new TargetClosedException("Navigation failed because browser has disconnected!", _frameManager.Client.CloseReason));
private void Navigated(object sender, FrameEventArgs e)
{
if (e.Frame != _frame)
{
return;
}
CheckLifecycleComplete();
}
private void FrameManager_LifecycleEvent(object sender, FrameEventArgs e) => CheckLifecycleComplete();
private void FrameManager_FrameSwapped(object sender, FrameEventArgs e)
{
if (e.Frame != _frame)
{
return;
}
_swapped = true;
CheckLifecycleComplete();
}
private void OnFrameDetached(object sender, FrameEventArgs e)
{
var frame = e.Frame;
if (_frame == frame)
{
Terminate(new PuppeteerException("Navigating frame was detached"));
return;
}
CheckLifecycleComplete();
}
private void CheckLifecycleComplete()
{
// We expect navigation to commit.
if (!CheckLifecycle(_frame, _expectedLifecycle))
{
return;
}
_lifecycleTaskWrapper.TrySetResult(true);
if (_hasSameDocumentNavigation)
{
_sameDocumentNavigationTaskWrapper.TrySetResult(true);
}
if (_swapped || _frame.LoaderId != _initialLoaderId)
{
_newDocumentNavigationTaskWrapper.TrySetResult(true);
}
}
private void Terminate(PuppeteerException ex) => _terminationTaskWrapper.TrySetException(ex);
private void OnRequest(object sender, RequestEventArgs e)
{
if (e.Request.Frame != _frame || !e.Request.IsNavigationRequest)
{
return;
}
_navigationRequest = e.Request;
}
private void NavigatedWithinDocument(object sender, FrameEventArgs e)
{
if (e.Frame != _frame)
{
return;
}
_hasSameDocumentNavigation = true;
CheckLifecycleComplete();
}
private bool CheckLifecycle(Frame frame, IEnumerable<string> expectedLifecycle)
{
foreach (var item in expectedLifecycle)
{
if (!frame.LifecycleEvents.Contains(item))
{
return false;
}
}
foreach (Frame child in frame.ChildFrames)
{
if (child.HasStartedLoading && !CheckLifecycle(child, expectedLifecycle))
{
return false;
}
}
return true;
}
}
}