-
-
Save trydis/d20ed9daedec19dc87e8 to your computer and use it in GitHub Desktop.
using AE.Net.Mail; | |
using System.Linq; | |
using System.Text.RegularExpressions; | |
using System.Threading.Tasks; | |
using UltimateTeam.Toolkit.Exceptions; | |
using UltimateTeam.Toolkit.Services; | |
namespace UltimateTeam.Toolkit.TwoFactorCodeProviders | |
{ | |
public class ImapTwoFactorCodeProvider : ITwoFactorCodeProvider | |
{ | |
private readonly string _username; | |
private readonly string _password; | |
private readonly string _hostName; | |
private readonly int _port; | |
private readonly bool _useUseSsl; | |
public ImapTwoFactorCodeProvider(string username, string password, string hostname, int port, bool useSsl) | |
{ | |
_username = username; | |
_password = password; | |
_hostName = hostname; | |
_port = port; | |
_useUseSsl = useSsl; | |
} | |
public Task<string> GetTwoFactorCodeAsync() | |
{ | |
return Task.Run(async () => | |
{ | |
var regex = new Regex(@"(?<=<strong>)\d{6}"); | |
using (var client = new ImapClient(_hostName, _username, _password, AuthMethods.Login, _port, _useUseSsl)) | |
{ | |
for (var i = 0; i < 5; i++) | |
{ | |
var messages = client.SearchMessages(SearchCondition.Unseen().And(SearchCondition.From("Origin"))); | |
foreach (var match in messages.Select(message => regex.Match(message.Value.Body)).Where(match => match.Success)) | |
{ | |
return match.Value; | |
} | |
await Task.Delay(5000); | |
} | |
} | |
throw new FutException("Unable to find the two-factor authentication code."); | |
}); | |
} | |
} | |
} |
return Task.Run(async () => ....
I have an error:: " it cannot resolve method Run(lambda expression) "
what to do here? Any idea?
Where should this .cs file go? my new project or toolkit project ?
thanks!
The file goes wherever you wish it to go. You are perhaps just trying to compile it under wrong framework.
I believe the complication of using an async lambda is not quite necessary in this particular case.
Since Task.Run(Action) puts the specified action to a threadpool, you do not quite need to make the lambda asynchronous.
I believe the following example should solve the obvious problems you might be facing right now.
return Task.Run(() =>
{
//whatever you are doing here is being executed in a worker thread acquired from the thread pool
//and this is how you pause your worker thread in this case:
Thread.Sleep(5000);
});
This should suffice, as I believe that losing a single thread from the thread pool for 25 seconds or less will not lead to anything nasty in this particular situation.
Thanks @hacklex!
Could you please give me an example using the above code on how i set the email as seen, or better yet delete it after retrieving the code?
Also, how would i go about using the newest email if i was too get more than one result for unseen & from origin?
Hostname: imap.gmail.com
Port: 993