using System; using System.Text.RegularExpressions; using System.Threading; using MahApps.RESTBase; using MahApps.Twitter; using MahApps.Twitter.Models; using MahTweets.Mango.Core.ActionResults; using MahTweets.Mango.Core.Models; using MahTweets.Mango.Core.Repositories; using WindowsPhoneEssentials.Tasks; using WindowsPhoneEssentials.Threading; using WindowsPhoneMVC; using WindowsPhoneMVC.ActionResults; using WindowsPhoneMVC.Navigation; namespace MahTweets.Extensions.Twitter.Mango.Controllers { public class TwitterController : Controller { private readonly ITaskManager _taskManager; private readonly IAccountRepository _accountRepository; private const string ConsumerKey = "NRvCz7KI8MRodk2E28Dmg"; private const string ConsumerSecret = "4Pm8OlyWRUmuWmG25t7yhbtoUW4A9V0CA4XO8tvg"; public TwitterController(ITaskManager taskManager, IAccountRepository accountRepository) { _taskManager = taskManager; _accountRepository = accountRepository; } public ActionResult NewAccount() { var twitterClient = new TwitterClient(ConsumerKey, ConsumerSecret, "http://www.mahtweets.com/mobile_oauth.html"); //Possibly think about how to create a async MVC navigation so you call NavigationComplete() to finish the navigation in a callback? var sync = new ManualResetEvent(false); string oauthUrl = null; twitterClient.BeginGetRequestUrl((request, response, url)=> { oauthUrl = url; sync.Set(); }); if (!sync.WaitOne(10000)) return this.Toast("Timeout", "Timed out getting oAuth URL"); Execute.OnUIThread(()=> _taskManager.ShowWebsiteInApp(oauthUrl, false, (uri, ns)=> { if (!uri.AbsoluteUri.Contains("mahtweets.com")) return; ns.GoBack(); NavigationContext.Navigator.NavigateTo("NewAccount", uri, twitterClient); })); return Nothing(); } public ActionResult NewAccount(Uri oAuthUri, TwitterClient twitterClient) { var r = new Regex("oauth_token=([^&.]*)&oauth_verifier=([^&.]*)"); var match = r.Match(oAuthUri.AbsoluteUri); if (!match.Success) return this.Toast("Error", "Twitter setup cancelled or failed"); Credentials tokens = null; var sync = new ManualResetEvent(false); twitterClient.BeginGetAccessToken(oAuthUri, (request, response, t) => { tokens = t; twitterClient.SetOAuthToken(t); sync.Set(); }); if (!sync.WaitOne(10000)) return this.Toast("Timeout", "Timed out getting access tokens"); sync.Reset(); object user = null; twitterClient.Account.BeginVerifyCredentials((req, res, o)=> { user = o; sync.Set(); }); if (!sync.WaitOne(10000)) return this.Toast("Timeout", "Timed out verifying credentials"); if (user is User && !string.IsNullOrEmpty(((User)user).Name)) { var u = (User)user; _accountRepository.NewAccount(new AccountCredentials { AccountName = u.ScreenName, Username = tokens.OAuthToken, Password = tokens.OAuthTokenSecret, Protocol = "twitter", AccountId = u.Id.ToString() }); return RefreshCurrentView(); } return this.Toast("Error", "Twitter setup cancelled or failed"); } } }