|
| 1 | +namespace AngleSharp.Io.Network |
| 2 | +{ |
| 3 | + using AngleSharp.Network; |
| 4 | + using System; |
| 5 | + using System.Collections.Generic; |
| 6 | + using System.Threading; |
| 7 | + using System.Threading.Tasks; |
| 8 | + |
| 9 | + /// <summary> |
| 10 | + /// Requester to perform about:// requests. |
| 11 | + /// </summary> |
| 12 | + public class AboutRequester : IRequester |
| 13 | + { |
| 14 | + private readonly Dictionary<String, Func<IRequest, CancellationToken, Task<IResponse>>> _routes; |
| 15 | + |
| 16 | + /// <summary> |
| 17 | + /// Creates a new about requester. |
| 18 | + /// </summary> |
| 19 | + public AboutRequester() |
| 20 | + { |
| 21 | + _routes = new Dictionary<String, Func<IRequest, CancellationToken, Task<IResponse>>>(); |
| 22 | + } |
| 23 | + |
| 24 | + /// <summary> |
| 25 | + /// Sets the route for the given address. |
| 26 | + /// </summary> |
| 27 | + /// <param name="address">The address of the route.</param> |
| 28 | + /// <param name="route">The route to use.</param> |
| 29 | + public void SetRoute(String address, Func<IRequest, CancellationToken, Task<IResponse>> route) |
| 30 | + { |
| 31 | + _routes[address] = route; |
| 32 | + } |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Gets the route for the given address, if any. |
| 36 | + /// </summary> |
| 37 | + /// <param name="address">The address of the route to obtain.</param> |
| 38 | + /// <returns>The route, if any.</returns> |
| 39 | + public Func<IRequest, CancellationToken, Task<IResponse>> GetRoute(String address) |
| 40 | + { |
| 41 | + var route = default(Func<IRequest, CancellationToken, Task<IResponse>>); |
| 42 | + _routes.TryGetValue(address, out route); |
| 43 | + return route; |
| 44 | + } |
| 45 | + |
| 46 | + /// <summary> |
| 47 | + /// Performs an asynchronous request that can be cancelled. |
| 48 | + /// </summary> |
| 49 | + /// <param name="request">The options to consider.</param> |
| 50 | + /// <param name="cancel">The token for cancelling the task.</param> |
| 51 | + /// <returns>The task that will eventually give the response data.</returns> |
| 52 | + public Task<IResponse> RequestAsync(IRequest request, CancellationToken cancel) |
| 53 | + { |
| 54 | + var route = GetRoute(request.Address.Data); |
| 55 | + |
| 56 | + if (route != null) |
| 57 | + { |
| 58 | + return route.Invoke(request, cancel); |
| 59 | + } |
| 60 | + |
| 61 | + return Task.FromResult(default(IResponse)); |
| 62 | + } |
| 63 | + |
| 64 | + /// <summary> |
| 65 | + /// Checks if the given protocol is supported. |
| 66 | + /// </summary> |
| 67 | + /// <param name="protocol">The protocol to check for, e.g. file.</param> |
| 68 | + /// <returns>True if the protocol is supported, otherwise false.</returns> |
| 69 | + public Boolean SupportsProtocol(String protocol) |
| 70 | + { |
| 71 | + return !String.IsNullOrEmpty(protocol) && protocol.Equals("about"); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments