using ElectronNET.API.Entities; using ElectronNET.API.Serialization; using System; using System.Text.Json; using System.Threading.Tasks; namespace ElectronNET.API { /// /// Query and modify a session's cookies. /// public class Cookies { /// /// Gets the identifier. /// /// /// The identifier. /// public int Id { get; private set; } internal Cookies(int id) { Id = id; } /// /// Emitted when a cookie is changed because it was added, edited, removed, or expired. /// public event Action OnChanged { add { if (_changed == null) { BridgeConnector.Socket.On("webContents-session-cookies-changed" + Id, (args) => { var e = args.EnumerateArray().GetEnumerator(); e.MoveNext(); var cookie = e.Current.Deserialize(ElectronJson.Options); e.MoveNext(); var cause = e.Current.Deserialize(ElectronJson.Options); e.MoveNext(); var removed = e.Current.GetBoolean(); _changed(cookie, cause, removed); }); BridgeConnector.Socket.Emit("register-webContents-session-cookies-changed", Id); } _changed += value; } remove { _changed -= value; if (_changed == null) { BridgeConnector.Socket.Off("webContents-session-cookies-changed" + Id); } } } private event Action _changed; /// /// Sends a request to get all cookies matching filter, and resolves a callack with the response. /// /// /// /// A task which resolves an array of cookie objects. public Task GetAsync(CookieFilter filter) { var tcs = new TaskCompletionSource(); var guid = Guid.NewGuid().ToString(); BridgeConnector.Socket.Once("webContents-session-cookies-get-completed" + guid, tcs.SetResult); BridgeConnector.Socket.Emit("webContents-session-cookies-get", Id, filter, guid); return tcs.Task; } /// /// /// /// /// public Task SetAsync(CookieDetails details) { var tcs = new TaskCompletionSource(); var guid = Guid.NewGuid().ToString(); BridgeConnector.Socket.Once("webContents-session-cookies-set-completed" + guid, tcs.SetResult); BridgeConnector.Socket.Emit("webContents-session-cookies-set", Id, details, guid); return tcs.Task; } /// /// Removes the cookies matching url and name /// /// The URL associated with the cookie. /// The name of cookie to remove. /// A task which resolves when the cookie has been removed public Task RemoveAsync(string url, string name) { var tcs = new TaskCompletionSource(); var guid = Guid.NewGuid().ToString(); BridgeConnector.Socket.Once("webContents-session-cookies-remove-completed" + guid, tcs.SetResult); BridgeConnector.Socket.Emit("webContents-session-cookies-remove", Id, url, name, guid); return tcs.Task; } /// /// Writes any unwritten cookies data to disk. /// /// A task which resolves when the cookie store has been flushed public Task FlushStoreAsync() { var tcs = new TaskCompletionSource(); var guid = Guid.NewGuid().ToString(); BridgeConnector.Socket.Once("webContents-session-cookies-flushStore-completed" + guid, tcs.SetResult); BridgeConnector.Socket.Emit("webContents-session-cookies-flushStore", Id, guid); return tcs.Task; } } }