Ejemplo n.º 1
0
        public ErrorPromise <RegisterationErrorResultStatus> Register(string username, string password)
        {
            IDispatcher dispatcher = GameDispatcher.Dispatcher;
            ErrorDeferred <RegisterationErrorResultStatus> deferred = new ErrorDeferred <RegisterationErrorResultStatus>();
            string authenticationId = InfoResolver.Resolve <BacktoryInfo>().AuthenticationId;
            string url = "https://api.backtory.com/auth/users";

            ThreadPool.QueueUserWorkItem(state =>
            {
                try
                {
                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
                    webRequest.KeepAlive      = true;
                    webRequest.Method         = "POST";
                    webRequest.ContentType    = "application/json; charset=utf-8";
                    webRequest.Headers.Add("X-Backtory-Authentication-Id", authenticationId);

                    string body              = JsonConvert.SerializeObject(new { username, password });
                    byte[] resoponse         = Encoding.UTF8.GetBytes(body);
                    webRequest.ContentLength = resoponse.Length;
                    using (System.IO.Stream requestStream = webRequest.GetRequestStream())
                    {
                        requestStream.Write(resoponse, 0, resoponse.Length);
                    }
                    using (WebResponse webResponse = webRequest.GetResponse())
                    {
                        using (System.IO.Stream responseStream = webResponse.GetResponseStream())
                        {
                            using (StreamReader reader = new StreamReader(responseStream))
                            {
                                reader.ReadToEnd();
                            }
                        }
                    }
                    dispatcher.Dispach(() =>
                    {
                        deferred.Resolve();
                    });
                }
                catch (WebException we)
                {
                    dispatcher.Dispach(() =>
                    {
                        HttpWebResponse httpWebResponse = we.Response as HttpWebResponse;
                        if (httpWebResponse != null)
                        {
                            if (httpWebResponse.StatusCode == HttpStatusCode.Conflict)
                            {
                                deferred.Reject(RegisterationErrorResultStatus.UsernameIsInUse);
                                return;
                            }
                        }
                        deferred.Reject(RegisterationErrorResultStatus.CannotConnectToServer);
                    });
                }
            });

            return(deferred.Promise());
        }
Ejemplo n.º 2
0
        public Promise Relogin()
        {
            IDispatcher dispatcher = GameDispatcher.Dispatcher;
            Deferred    deferred   = new Deferred();

            if (!IsReloginCapable())
            {
                throw new Exception("Relogin is not capable.No saved refresh token found");
            }
            string authenticationId        = InfoResolver.Resolve <BacktoryInfo>().AuthenticationId;
            string authenticationClientKey = InfoResolver.Resolve <BacktoryInfo>().AuthenticationClientKey;
            string url = "https://api.backtory.com/auth/login";

            ThreadPool.QueueUserWorkItem(state =>
            {
                try
                {
                    BacktoryAccessData backtoryAccessData = ServiceLocator.Resolve <IStorageService>().ResolveData <BacktoryAccessData>();
                    string result = MultiPartCall(url, new Dictionary <string, string>
                    {
                        { "refresh_token", backtoryAccessData.RefreshToken },
                    }, new Dictionary <string, string>
                    {
                        { "X-Backtory-Authentication-Id", authenticationId },
                        { "X-Backtory-Authentication-Key", authenticationClientKey },
                        { "X-Backtory-Authentication-Refresh", "1" }
                    });
                    LoginResponse loginResponse = JsonConvert.DeserializeObject <LoginResponse>(result);
                    dispatcher.Dispach(() =>
                    {
                        if (string.IsNullOrEmpty(loginResponse.AccessToken))
                        {
                            deferred.Reject();
                        }
                        else
                        {
                            backtoryAccessData              = ServiceLocator.Resolve <IStorageService>().ResolveData <BacktoryAccessData>();
                            backtoryAccessData.AccessToken  = loginResponse.AccessToken;
                            backtoryAccessData.RefreshToken = loginResponse.RefreshToken;
                            backtoryAccessData.TokenType    = loginResponse.TokenType;
                            ServiceLocator.Resolve <IStorageService>().UpdateData(backtoryAccessData);
                            deferred.Resolve();
                        }
                    });
                }
                catch (Exception)
                {
                    dispatcher.Dispach(() =>
                    {
                        deferred.Reject();
                    });
                }
            });
            return(deferred.Promise());
        }
Ejemplo n.º 3
0
        public Promise Login(string username, string password)
        {
            IDispatcher dispatcher = GameDispatcher.Dispatcher;
            Deferred    deferred   = new Deferred();

            string authenticationId        = InfoResolver.Resolve <BacktoryInfo>().AuthenticationId;
            string authenticationClientKey = InfoResolver.Resolve <BacktoryInfo>().AuthenticationClientKey;
            string url = "https://api.backtory.com/auth/login";

            ThreadPool.QueueUserWorkItem(state =>
            {
                try
                {
                    string result = MultiPartCall(url, new Dictionary <string, string>
                    {
                        { "username", username },
                        { "password", password }
                    }, new Dictionary <string, string>
                    {
                        { "X-Backtory-Authentication-Id", authenticationId },
                        { "X-Backtory-Authentication-Key", authenticationClientKey }
                    });
                    LoginResponse loginResponse = JsonConvert.DeserializeObject <LoginResponse>(result);
                    dispatcher.Dispach(() =>
                    {
                        if (string.IsNullOrEmpty(loginResponse.AccessToken))
                        {
                            deferred.Reject();
                        }
                        else
                        {
                            BacktoryAccessData backtoryAccessData = ServiceLocator.Resolve <IStorageService>().ResolveData <BacktoryAccessData>() ?? new BacktoryAccessData();
                            backtoryAccessData.AccessToken        = loginResponse.AccessToken;
                            backtoryAccessData.RefreshToken       = loginResponse.RefreshToken;
                            backtoryAccessData.TokenType          = loginResponse.TokenType;
                            ServiceLocator.Resolve <IStorageService>().UpdateData(backtoryAccessData);
                            deferred.Resolve();
                        }
                    });
                }
                catch (Exception)
                {
                    dispatcher.Dispach(() =>
                    {
                        deferred.Reject();
                    });
                }
            });
            return(deferred.Promise());
        }
Ejemplo n.º 4
0
/*        private string GetServerStoragePath(string localPath)
 *      {
 *          return Base64Decode(Path.GetFileName(localPath));
 *      }*/
        public ComplitionPromise <string> LoadFromStorage(Uri uri, Action <DownloadProgress> progress)
        {
            ComplitionDeferred <string> deferred = new ComplitionDeferred <string>();
            IDispatcher      dispatcher          = GameDispatcher.Dispatcher;
            string           localFileName       = GetLocalStoragePath(uri.ToString());
            string           localPath           = Path.GetDirectoryName(localFileName);
            StorageSavedData savedData           = ServiceLocator.Resolve <IStorageService>().ResolveData <StorageSavedData>() ?? new StorageSavedData();

            if (savedData.Cache.ContainsKey(uri.ToString()))
            {
                savedData.Cache.Remove(uri.ToString());
            }
            ServiceLocator.Resolve <IStorageService>().UpdateData(savedData);
            ThreadPool.QueueUserWorkItem(state =>
            {
                try
                {
                    if (!Directory.Exists(localPath))
                    {
                        Directory.CreateDirectory(localPath);
                    }
                    using (FileStream file = File.Create(localFileName))
                    {
                        WebRequest request = WebRequest.Create(uri);
                        request.Method     = "GET";
                        using (WebResponse webResponse = request.GetResponse())
                        {
                            using (System.IO.Stream responseStream = webResponse.GetResponseStream())
                            {
                                int bytesRead;
                                byte[] buffer  = new byte[2048];
                                long wroteSize = 0;
                                while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    file.Write(buffer, 0, bytesRead);
                                    wroteSize += bytesRead;
                                    long dispatchWroteSize     = wroteSize;
                                    long dispatchContentLength = webResponse.ContentLength;
                                    dispatcher.Dispach(() =>
                                    {
                                        progress(new DownloadProgress(dispatchContentLength, dispatchWroteSize));
                                    });
                                }
                            }
                        }
                    }

                    dispatcher.Dispach(() =>
                    {
                        StorageSavedData storageSavedData      = ServiceLocator.Resolve <IStorageService>().ResolveData <StorageSavedData>() ?? new StorageSavedData();
                        storageSavedData.Cache[uri.ToString()] = localFileName;
                        ServiceLocator.Resolve <IStorageService>().UpdateData(storageSavedData);
                        deferred.Resolve(localFileName);
                    });
                }
                catch (Exception e)
                {
                    try
                    {
                        File.Delete(localFileName);
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                    dispatcher.Dispach(() =>
                    {
                        Debug.LogException(e);
                        deferred.Reject();
                    });
                }
            });

            return(deferred.Promise());
        }
Ejemplo n.º 5
0
        public Promise <T, ICallError> Call <T>(string methodName, object requestBody)
        {
            IDispatcher dispatcher            = GameDispatcher.Dispatcher;
            Deferred <T, ICallError> deferred = new Deferred <T, ICallError>();
            string url = string.Format("https://api.backtory.com/cloud-code/{0}/{1}", InfoResolver.Resolve <BacktoryInfo>().CloudId, methodName);

            if (!string.IsNullOrEmpty(BacktoryCloudUrl.Url))
            {
                url = new Uri(new Uri(BacktoryCloudUrl.Url), new Uri(string.Format("/{0}", methodName))).ToString();
            }
            string authorization = string.Empty;

            if (ServiceLocator.Resolve <IStorageService>().ContainsData <BacktoryAccessData>())
            {
                BacktoryAccessData backtoryAccessData =
                    ServiceLocator.Resolve <IStorageService>().ResolveData <BacktoryAccessData>();
                authorization = string.Format("{0} {1}", backtoryAccessData.TokenType, backtoryAccessData.AccessToken);
            }
            string body = JsonConvert.SerializeObject(requestBody);

            if (body == "null")
            {
                body = "{}";
            }
            ThreadPool.QueueUserWorkItem(state =>
            {
                try
                {
                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
                    webRequest.KeepAlive      = true;
                    webRequest.Method         = "POST";
                    webRequest.ContentType    = "application/json; charset=utf-8";
                    if (!string.IsNullOrEmpty(authorization))
                    {
                        webRequest.Headers.Add("Authorization", authorization);
                    }


                    byte[] resoponse         = Encoding.UTF8.GetBytes(body);
                    webRequest.ContentLength = resoponse.Length;
                    using (System.IO.Stream requestStream = webRequest.GetRequestStream())
                    {
                        requestStream.Write(resoponse, 0, resoponse.Length);
                    }
                    using (WebResponse webResponse = webRequest.GetResponse())
                    {
                        using (System.IO.Stream responseStream = webResponse.GetResponseStream())
                        {
                            using (StreamReader reader = new StreamReader(responseStream))
                            {
                                string readToEnd = reader.ReadToEnd();
                                dispatcher.Dispach(() =>
                                {
                                    try
                                    {
                                        T result = JsonConvert.DeserializeObject <T>(readToEnd);
                                        deferred.Resolve(result);
                                    }
                                    catch (Exception)
                                    {
                                        deferred.Reject(new BactkoryCallError(HttpStatusCode.Continue, CallErrorType.MethodConversionFailed));
                                    }
                                });
                            }
                        }
                    }
                    dispatcher.Dispach(() =>
                    {
                        deferred.Resolve(default(T));
                    });
                }
                catch (WebException we)
                {
                    dispatcher.Dispach(() =>
                    {
                        HttpWebResponse httpWebResponse = we.Response as HttpWebResponse;
                        if (httpWebResponse != null)
                        {
                            deferred.Reject(new BactkoryCallError(httpWebResponse.StatusCode, CallErrorType.Other));
                        }
                        deferred.Reject(new BactkoryCallError(HttpStatusCode.Continue, CallErrorType.Other));
                    });
                }
                catch (Exception)
                {
                    deferred.Reject(new BactkoryCallError(HttpStatusCode.Continue, CallErrorType.Other));
                }
            });

            return(deferred.Promise());
        }
Ejemplo n.º 6
0
        public Promise <T, ICallError> Call <T>(string methodName, object requestBody)
        {
            Deferred <T, ICallError> deferred = new Deferred <T, ICallError>();
            IDispatcher dispatcher            = EditorDispatcher.Dispatcher;
            string      url = string.Format("https://api.backtory.com/cloud-code/{0}/{1}", InfoResolver.Resolve <BacktoryInfo>().CloudId, methodName);

            if (!string.IsNullOrEmpty(BacktoryCloudUrl.Url))
            {
                url = new Uri(new Uri(BacktoryCloudUrl.Url), new Uri(string.Format("/{0}", methodName), UriKind.Relative)).ToString();
            }
            string authenticationId        = InfoResolver.Resolve <BacktoryInfo>().AuthenticationId;
            string authenticationMasterKey = EditorInfoResolver.Resolve <BacktoryEditorInfo>().AuthenticationMasterKey;
            string body = JsonConvert.SerializeObject(requestBody);

            if (body == "null")
            {
                body = "{}";
            }
            ThreadPool.QueueUserWorkItem(state =>
            {
                MasterLogin(authenticationId, authenticationMasterKey).Then(response =>
                {
                    string authorization = string.Format("{0} {1}", response.TokenType, response.AccessToken);
                    try
                    {
                        string iUrl = url;
                        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(iUrl));
                        webRequest.KeepAlive      = true;
                        webRequest.Method         = "POST";
                        webRequest.ContentType    = "application/json; charset=utf-8";
                        if (!string.IsNullOrEmpty(authorization))
                        {
                            webRequest.Headers.Add("Authorization", authorization);
                        }


                        byte[] resoponse         = Encoding.UTF8.GetBytes(body);
                        webRequest.ContentLength = resoponse.Length;
                        using (System.IO.Stream requestStream = webRequest.GetRequestStream())
                        {
                            requestStream.Write(resoponse, 0, resoponse.Length);
                        }
                        using (WebResponse webResponse = webRequest.GetResponse())
                        {
                            using (System.IO.Stream responseStream = webResponse.GetResponseStream())
                            {
                                using (StreamReader reader = new StreamReader(responseStream))
                                {
                                    string readToEnd = reader.ReadToEnd();
                                    dispatcher.Dispach(() =>
                                    {
                                        try
                                        {
                                            T result = JsonConvert.DeserializeObject <T>(readToEnd);
                                            deferred.Resolve(result);
                                        }
                                        catch (Exception)
                                        {
                                            deferred.Reject(new BactkoryCallError(HttpStatusCode.Continue,
                                                                                  CallErrorType.MethodConversionFailed));
                                        }
                                    });
                                }
                            }
                        }
                    }
                    catch (WebException we)
                    {
                        Debug.LogException(we);
                        dispatcher.Dispach(() =>
                        {
                            HttpWebResponse httpWebResponse = we.Response as HttpWebResponse;
                            if (httpWebResponse != null)
                            {
                                deferred.Reject(new BacktoryEditorCallError(CallErrorType.Other, false,
                                                                            httpWebResponse.StatusCode));
                            }
                            deferred.Reject(new BacktoryEditorCallError(CallErrorType.Other, false,
                                                                        HttpStatusCode.Continue));
                        });
                    }
                    catch (Exception)
                    {
                        deferred.Reject(new BacktoryEditorCallError(CallErrorType.Other, false, HttpStatusCode.Continue));
                    }
                }, () =>
                {
                    dispatcher.Dispach(() =>
                    {
                        deferred.Reject(new BacktoryEditorCallError(CallErrorType.Other, true, HttpStatusCode.Continue));
                    });
                });
            });
            return(deferred.Promise());
        }
Ejemplo n.º 7
0
        public ComplitionPromise <string[]> SendFilesToStorage(StorageFile[] storageFiles, Action <float> progress)
        {
            ComplitionDeferred <string[]> deferred = new ComplitionDeferred <string[]>();

            if (storageFiles.Length == 0)
            {
                deferred.Resolve(new string[0]);
                return(deferred.Promise());
            }
            string boundary = "----WebKitFormBoundaryS3pOJgmMVoMmQZ9Y";
            MultiPartFormDataStream dataStream = new MultiPartFormDataStream(boundary, storageFiles.Select((file, i) =>
            {
                MultiPartParameter[] multiPartParameters = new MultiPartParameter[4];
                multiPartParameters[0] = new StreamMultiPartParameter(boundary, string.Format("fileItems[{0}].fileToUpload", i), file.FileName, file.Stream);
                multiPartParameters[1] = new StringMultiPartParameter(boundary, string.Format("fileItems[{0}].path", i), file.Path);
                multiPartParameters[2] = new StringMultiPartParameter(boundary, string.Format("fileItems[{0}].replacing", i), "true");
                multiPartParameters[3] = new StringMultiPartParameter(boundary, string.Format("fileItems[{0}].extract", i), "false");
                return(multiPartParameters);
            }).SelectMany(parameters => parameters).ToArray());

/*            using (FileStream test = File.Create(@"d:\1.log"))
 *          {
 *              dataStream.CopyTo(test);
 *
 *          }
 *          return null;*/
            string      authenticationId        = InfoResolver.Resolve <BacktoryInfo>().AuthenticationId;
            string      authenticationMasterKey = EditorInfoResolver.Resolve <BacktoryEditorInfo>().AuthenticationMasterKey;
            string      storageId  = EditorInfoResolver.Resolve <BacktoryEditorInfo>().StorageId;
            string      url        = "https://storage.backtory.com/files";
            IDispatcher dispatcher = EditorDispatcher.Dispatcher;

            ThreadPool.QueueUserWorkItem(state =>
            {
                MasterLogin(authenticationId, authenticationMasterKey).Then(response =>
                {
                    try
                    {
                        string authorization      = string.Format("{0} {1}", response.TokenType, response.AccessToken);
                        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
                        webRequest.KeepAlive      = true;
                        webRequest.Method         = "POST";

                        webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                        webRequest.Headers.Add("x-backtory-storage-id", storageId);
                        webRequest.Headers.Add("Authorization", authorization);
                        webRequest.ContentLength = dataStream.Length;
                        using (System.IO.Stream requestStream = webRequest.GetRequestStream())
                        {
                            int bytesRead;
                            byte[] buffer  = new byte[2048];
                            long wroteSize = 0;
                            while ((bytesRead = dataStream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                requestStream.Write(buffer, 0, bytesRead);
                                wroteSize           += bytesRead;
                                float normalPosition = (float)wroteSize / dataStream.Length;
                                dispatcher.Dispach(() =>
                                {
                                    progress(normalPosition);
                                });
                            }
                            using (WebResponse webResponse = webRequest.GetResponse())
                            {
                                using (System.IO.Stream responseStream = webResponse.GetResponseStream())
                                {
                                    using (StreamReader reader = new StreamReader(responseStream))
                                    {
                                        string readToEnd = reader.ReadToEnd();
                                        BacktoryStorageResoponce backtoryStorageResoponce = JsonConvert.DeserializeObject <BacktoryStorageResoponce>(readToEnd);
                                        foreach (StorageFile storageFile in storageFiles)
                                        {
                                            storageFile.Stream.Close();
                                        }
                                        dispatcher.Dispach(() => deferred.Resolve(backtoryStorageResoponce.SavedFilesUrls));
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        foreach (StorageFile storageFile in storageFiles)
                        {
                            storageFile.Stream.Close();
                        }
                        Debug.LogException(e);
                        dispatcher.Dispach(() => deferred.Reject());
                    }
                }, () =>
                {
                    foreach (StorageFile storageFile in storageFiles)
                    {
                        storageFile.Stream.Close();
                    }
                    dispatcher.Dispach(() => deferred.Reject());
                });
            });
            return(deferred.Promise());
        }