public static GoogleDocsRequestToken GetGoogleDocsRequestToken(GoogleDocsConfiguration configuration, String consumerKey, String consumerSecret) { var consumerContext = new OAuthConsumerContext(consumerKey, consumerSecret); var serviceContext = new OAuthServiceContext(GetRequestTokenUrl(configuration), configuration.OAuthAuthorizeTokenUrl.ToString(), configuration.AuthorizationCallBack.ToString(), GetAccessTokenUrl(configuration, null)); var service = new OAuthService(); var token = service.GetRequestToken(serviceContext, consumerContext); return token != null ? new GoogleDocsRequestToken(token) : null; }
public static ICloudStorageAccessToken ExchangeGoogleDocsRequestTokenIntoAccessToken(GoogleDocsConfiguration configuration, String consumerKey, String consumerSecret, GoogleDocsRequestToken requestToken, String oAuthVerifier) { var consumerContext = new OAuthConsumerContext(consumerKey, consumerSecret); var serviceContext = new OAuthServiceContext(configuration.OAuthGetRequestTokenUrl.ToString(), configuration.OAuthAuthorizeTokenUrl.ToString(), configuration.AuthorizationCallBack.ToString(), GetAccessTokenUrl(configuration, oAuthVerifier)); var service = new OAuthService(); var accessToken = service.GetAccessToken(serviceContext, consumerContext, requestToken.RealToken); if (accessToken == null) throw new UnauthorizedAccessException(); return new GoogleDocsToken(accessToken, consumerKey, consumerSecret); }
/// <summary> /// This method retrieves a new request token from the dropbox server /// </summary> /// <param name="configuration"></param> /// <param name="ConsumerKey"></param> /// <param name="ConsumerSecret"></param> /// <returns></returns> public static DropBoxRequestToken GetDropBoxRequestToken(DropBoxConfiguration configuration, String ConsumerKey, String ConsumerSecret) { // build the consumer context var consumerContext = new OAuthConsumerContext(ConsumerKey, ConsumerSecret); // build up the oauth session var serviceContext = new OAuthServiceContext(configuration.RequestTokenUrl.ToString(), configuration.AuthorizationTokenUrl.ToString(), configuration.AuthorizationCallBack.ToString(), configuration.AccessTokenUrl.ToString()); // get a request token from the provider var svc = new OAuthService(); var oauthToken = svc.GetRequestToken(serviceContext, consumerContext); return oauthToken != null ? new DropBoxRequestToken(oauthToken) : null; }
public static String RequestResourceByUrl(String url, Dictionary<String, String> parameters, IStorageProviderService service, IStorageProviderSession session, out int netErrorCode) { // cast the dropbox session var dropBoxSession = session as DropBoxStorageProviderSession; // instance the oAuthServer var svc = new OAuthService(); var urlhash = new KeyValuePair<string, string>(); if (!string.IsNullOrEmpty(url) && url.Contains("/metadata/")) { //Add the hash attr if any urlhash = SessionHashStorage.Get(session.SessionToken.ToString(), url, () => new KeyValuePair<string, string>()); } if (!string.IsNullOrEmpty(urlhash.Key) && !string.IsNullOrEmpty(urlhash.Value)) { //Add params if (parameters == null) parameters = new Dictionary<string, string>(); parameters.Add("hash", urlhash.Key); } // build the webrequest to protected resource var request = svc.CreateWebRequest(url, WebRequestMethodsEx.Http.Get, null, null, dropBoxSession.Context, (DropBoxToken) dropBoxSession.SessionToken, parameters); // get the error code WebException ex; // perform a simple webrequest using (Stream s = svc.PerformWebRequest(request, null, out netErrorCode, out ex, (code) => !string.IsNullOrEmpty(urlhash.Key) && !string.IsNullOrEmpty(urlhash.Value) && code == 304)/*to check code without downloading*/) { if (!string.IsNullOrEmpty(urlhash.Key) && !string.IsNullOrEmpty(urlhash.Value) && netErrorCode == 304) { return urlhash.Value; } if (s == null) return ""; // read the memory stream and convert to string var response = new StreamReader(s).ReadToEnd(); return response; } }
public override Uri GetFileSystemObjectUrl(string path, ICloudDirectoryEntry parent) { // get the filesystem var entry = GetFileSystemObject(path, parent); // get the download url var url = DropBoxStorageProviderService.GetDownloadFileUrlInternal(this._Session, entry); // get the right session var session = (DropBoxStorageProviderSession) _Session; // generate the oauth url var svc = new OAuthService(); url = svc.GetProtectedResourceUrl(url, session.Context, session.SessionToken as DropBoxToken, null, WebRequestMethodsEx.Http.Get); // go ahead return new Uri(url); }
/// <summary> /// This method is able to exchange the request token into an access token which can be used in /// sharpbox. It is necessary that the user validated the request via authorization url otherwise /// this call wil results in an unauthorized exception! /// </summary> /// <param name="configuration"></param> /// <param name="ConsumerKey"></param> /// <param name="ConsumerSecret"></param> /// <param name="DropBoxRequestToken"></param> /// <returns></returns> public static ICloudStorageAccessToken ExchangeDropBoxRequestTokenIntoAccessToken(DropBoxConfiguration configuration, String ConsumerKey, String ConsumerSecret, DropBoxRequestToken DropBoxRequestToken) { // build the consumer context var consumerContext = new OAuthConsumerContext(ConsumerKey, ConsumerSecret); // build up the oauth session var serviceContext = new OAuthServiceContext(configuration.RequestTokenUrl.ToString(), configuration.AuthorizationTokenUrl.ToString(), configuration.AuthorizationCallBack.ToString(), configuration.AccessTokenUrl.ToString()); // build the access token var svc = new OAuthService(); var accessToken = svc.GetAccessToken(serviceContext, consumerContext, DropBoxRequestToken.RealToken); if (accessToken == null) throw new UnauthorizedAccessException(); // create the access token return new DropBoxToken(accessToken, new DropBoxBaseTokenInformation { ConsumerKey = ConsumerKey, ConsumerSecret = ConsumerSecret }); }
public void CommitUploadSession(IStorageProviderSession session, IResumableUploadSession uploadSession) { if (uploadSession.Status == ResumableUploadSessionStatus.Started) { var requestService = new OAuthService(); var request = requestService.CreateWebRequest(GetCommitUploadSessionUrl(session, uploadSession), "POST", null, null, ((DropBoxStorageProviderSession)session).Context, (DropBoxToken)session.SessionToken, new Dictionary<string, string> {{"upload_id", uploadSession.GetItem<string>("UploadId")}}); int httpStatusCode; WebException httpException; requestService.PerformWebRequest(request, null, out httpStatusCode, out httpException); if (httpStatusCode != (int)HttpStatusCode.OK) SharpBoxException.ThrowSharpBoxExceptionBasedOnHttpErrorCode((HttpWebRequest)request, (HttpStatusCode)httpStatusCode, httpException); var file = (BaseFileEntry)uploadSession.File; file.Length = uploadSession.BytesToTransfer; file.Id = file.ParentID != "/" ? file.ParentID + "/" + file.Name : file.Name; var parent = file.Parent as BaseDirectoryEntry; if (parent != null) { parent.RemoveChildById(file.Name); parent.AddChild(file); } ((ResumableUploadSession)uploadSession).Status = ResumableUploadSessionStatus.Completed; } }
public override void UploadChunk(IStorageProviderSession session, IResumableUploadSession uploadSession, Stream stream, long chunkLength) { if (uploadSession.Status == ResumableUploadSessionStatus.Completed || uploadSession.Status == ResumableUploadSessionStatus.Aborted) throw new InvalidOperationException("Upload session was either completed or aborted."); if (stream == null) throw new ArgumentNullException("stream"); var requestParams = new Dictionary<string, string>(); if (uploadSession.Status == ResumableUploadSessionStatus.Started) { requestParams.Add("upload_id", uploadSession.GetItem<string>("UploadId")); requestParams.Add("offset", uploadSession.BytesTransfered.ToString()); } var request = new OAuthService().CreateWebRequest(GetUrlString(DropBoxChunkedUpload, session.ServiceConfiguration), "PUT", null, null, ((DropBoxStorageProviderSession)session).Context, (DropBoxToken)session.SessionToken, requestParams); request.ContentLength = chunkLength; using (var requestStream = request.GetRequestStream()) { stream.CopyTo(requestStream); } using (var response = request.GetResponse()) using (var responseStream = response.GetResponseStream()) { if (responseStream == null) return; var json = new JsonHelper(); json.ParseJsonMessage(new StreamReader(responseStream).ReadToEnd()); var uplSession = (ResumableUploadSession)uploadSession; uplSession["UploadId"] = json.GetProperty("upload_id"); uplSession["Expired"] = json.GetDateTimeProperty("expired"); uplSession.BytesTransfered += chunkLength; uplSession.Status = ResumableUploadSessionStatus.Started; if (uplSession.BytesToTransfer == uploadSession.BytesTransfered) { CommitUploadSession(session, uploadSession); } } }
public override Stream CreateUploadStream(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, long uploadSize) { // build the url var url = GetDownloadFileUrlInternal(session, fileSystemEntry.Parent); // get the session var dbSession = session as DropBoxStorageProviderSession; // build service var svc = new OAuthService(); // encode the filename var fileName = fileSystemEntry.Name; // build oAuth parameter var param = new Dictionary<string, string>(); param.Add("file", fileName); // sign the url var signedUrl = svc.GetSignedUrl(url, dbSession.Context, dbSession.SessionToken as DropBoxToken, param); // build upload web request var uploadRequest = svc.CreateWebRequestMultiPartUpload(signedUrl, null); // get the network stream var ws = svc.GetRequestStreamMultiPartUpload(uploadRequest, fileName, uploadSize); // register the post dispose opp ws.PushPostDisposeOperation(CommitUploadStream, svc, uploadRequest, uploadSize, fileSystemEntry, ws); // go ahead return ws; }
public override Stream CreateDownloadStream(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry) { // build the url var url = GetDownloadFileUrlInternal(session, fileSystemEntry); // build the service var svc = new OAuthService(); // get the dropbox session var dropBoxSession = session as DropBoxStorageProviderSession; // create webrequst var requestProtected = svc.CreateWebRequest(url, WebRequestMethodsEx.Http.Get, null, null, dropBoxSession.Context, (DropBoxToken) dropBoxSession.SessionToken, null); // get the response var response = svc.GetWebResponse(requestProtected); // get the data stream var orgStream = svc.GetResponseStream(response); // build the download stream var dStream = new BaseFileEntryDownloadStream(orgStream, fileSystemEntry); // put the disposable on the stack dStream._DisposableObjects.Push(response); // go ahead return dStream; }
public override string GetResourceUrl(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, String additionalPath) { var dbSession = session as DropBoxStorageProviderSession; String path = DropBoxResourceIDHelpers.GetResourcePath(fileSystemEntry, additionalPath); String url = GetResourceUrlInternal(session, path); // generate the oauth url var svc = new OAuthService(); return svc.GetProtectedResourceUrl(url, dbSession.Context, dbSession.SessionToken as DropBoxToken, null, WebRequestMethodsEx.Http.Get); }
/// <summary> /// This method offers the mobile login api of dropbox for users who are migrating from version 0 of the /// dropbox API because version 1 supports token based logins only /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="appkey"></param> /// <param name="appsecret"></param> /// <returns></returns> public static ICloudStorageAccessToken LoginWithMobileAPI(String username, String password, String appkey, String appsecret) { // get the configuration var configuration = DropBoxConfiguration.GetStandardConfiguration(); // build the consumer context var consumerContext = new OAuthConsumerContext(appkey, appsecret); // build up the oauth session var serviceContext = new OAuthServiceContext(configuration.RequestTokenUrl.ToString(), configuration.AuthorizationTokenUrl.ToString(), configuration.AuthorizationCallBack.ToString(), configuration.AccessTokenUrl.ToString()); // get a request token from the provider var svc = new OAuthService(); var oAuthRequestToken = svc.GetRequestToken(serviceContext, consumerContext); if (oAuthRequestToken == null) { throw new SharpBoxException(SharpBoxErrorCodes.ErrorInvalidConsumerKeySecret); } var DropBoxRequestToken = new DropBoxToken(oAuthRequestToken, new DropBoxBaseTokenInformation {ConsumerKey = appkey, ConsumerSecret = appsecret}); // generate the dropbox service var service = new DropBoxStorageProviderService(); // build up a request Token Session var requestSession = new DropBoxStorageProviderSession(DropBoxRequestToken, configuration, consumerContext, service); // build up the parameters var param = new Dictionary<String, String> { {"email", username}, {"password", password} }; // call the mobile login api var result = ""; try { int code; result = DropBoxRequestParser.RequestResourceByUrl(DropBoxMobileLogin, param, service, requestSession, out code); if (result.Length == 0) throw new UnauthorizedAccessException(); } #if MONOTOUCH || WINDOWS_PHONE || MONODROID catch (Exception ex) { if (ex is UnauthorizedAccessException) throw ex; else throw new SharpBoxException(SharpBoxErrorCodes.ErrorCouldNotContactStorageService, ex); } #else catch (System.Web.HttpException netex) { throw new SharpBoxException(SharpBoxErrorCodes.ErrorCouldNotContactStorageService, netex); } #endif // exchange a request token for an access token var accessToken = new DropBoxToken(result); // adjust the token if (accessToken.BaseTokenInformation == null) { accessToken.BaseTokenInformation = new DropBoxBaseTokenInformation { ConsumerKey = appkey, ConsumerSecret = appsecret }; } // go ahead return accessToken; }