public Dialog_ModSync_Window() { MSLog.Log("New window", MSLog.Level.All); try { CurrSyncState = CurrentSyncState.RequestStarted; ClientInternetConnectivity = InternetConnectivity.Unchecked; closeOnClickedOutside = false; FetchRelevantMods(); string userRequest = NetworkManager.GenerateServerRequestString(_relevantMods); _userRequestStr = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(userRequest)); NetworkManager.CheckForInternetConnectionAsync( this.ClientInternetConnectivity, (InternetConnectivity clientInternetConnectivity) => { this.ClientInternetConnectivity = clientInternetConnectivity; this.OnNetworkConnectionTestCompleted(); }); } catch (Exception e) { MSLog.Log("ERROR:", MSLog.Level.All); MSLog.Log(e.Message, MSLog.Level.All); } }
public static void CheckForInternetConnectionAsync( Dialog_ModSync_Window.InternetConnectivity clientInternetConnectivity, CheckForInternetConnectionAsyncCallback callback) { new Thread(() => { MSLog.Log("Checking for network async", MSLog.Level.All); try { //user.OnNetworkConnectionTestCompleted(); var request = WebRequest.Create("http://www.google.com"); request.Timeout = 5000; request.BeginGetResponse((IAsyncResult result) => { MSLog.Log("CheckForInternetConnectionAsyncCallback:", MSLog.Level.All); var httpWebRequest = result.AsyncState as HttpWebRequest; try { // Request finished clientInternetConnectivity = (httpWebRequest == null || !httpWebRequest.HaveResponse) ? Dialog_ModSync_Window.InternetConnectivity.Offline : Dialog_ModSync_Window.InternetConnectivity.Online; // Perform callback callback(clientInternetConnectivity); } catch { MSLog.Log("failed to assign network check response, client probably closed window", MSLog.Level.All); } }, request); // assume time out try { Thread.Sleep(5000); request.Abort(); MSLog.Log("Connection test request closed with connectivity state: " + clientInternetConnectivity, MSLog.Level.All); if (clientInternetConnectivity != Dialog_ModSync_Window.InternetConnectivity.Online) { clientInternetConnectivity = Dialog_ModSync_Window.InternetConnectivity.Offline; // Perform callback callback(clientInternetConnectivity); } } catch { MSLog.Log("network check timed out", MSLog.Level.All); } } catch { MSLog.Log("network check failed", MSLog.Level.All); } }).Start(); }
private static bool OpenXmlFromAboutDir(DirectoryInfo rootDir, string xmlFileToOpen, FileAccess fileAccess, OpenXmlFromAboutDirCallback callback) { if (callback == null) { throw new Exception("callback cannot be null"); } DirectoryInfo aboutDir = rootDir.GetDirectories(ABOUT_DIRECTORY).FirstOrDefault(); if (aboutDir == null) { return(false); } FileInfo xmlFile = aboutDir.GetFiles(MOD_SYNC_XML).FirstOrDefault(); if (xmlFile == null) { return(false); } try { using (FileStream fs = xmlFile.Open(FileMode.Open, fileAccess)) { XDocument xml = null; using (StreamReader sr = new StreamReader(fs)) { xml = XDocument.Parse(sr.ReadToEnd()); if (!xml.Elements().Any()) { throw new Exception("Invalid markup, null elements"); } string rootElement = (ABOUT_XML.Equals(xmlFileToOpen)) ? ABOUT_ROOT_ELEMENT : MODSYNC_NINJA_ROOT_ELEMENT; XElement root = xml.Element(rootElement); if (root == null) { throw new Exception("Invalid markup, missing root"); } callback.Invoke(root); } if (xml != null && (fileAccess == FileAccess.ReadWrite || fileAccess == FileAccess.Write)) { xml.Save(xmlFile.FullName); } } return(true); } catch (Exception e) { MSLog.Log(xmlFileToOpen + ": " + e.Message, MSLog.Level.All, true); return(false); } }
public override void PreOpen() { base.PreOpen(); // Initialize UpdateModRequest this.about = FileUtil.GetAboutFileText(this.ModToUpdate.RootDir); if (String.IsNullOrEmpty(this.about)) { MSLog.Log("Unable to find About.xml for " + this.ModToUpdate.Name, MSLog.Level.All, true); this.Close(); } this.modId = FileUtil.GetModSyncId(this.ModToUpdate.RootDir); this.modKey = String.Empty; this.publishedField = FileUtil.GetSteamPublishedField(this.ModToUpdate.RootDir); this.version = this.LocalVersion; }
public void OnNetworkConnectionTestCompleted() { // load data from server MSLog.Log("OnNetworkConnectionTestCompleted", MSLog.Level.All); if (ClientInternetConnectivity == InternetConnectivity.Online) { NetworkManager.CreateRequestHttpRequest( _userRequestStr, (CurrentSyncState syncState) => this.CurrSyncState = syncState, (string responseStr, bool success, string errorCode) => this.OnRequestFromServerResponse(responseStr, success, errorCode)); } else { CurrSyncState = CurrentSyncState.ClientOffline; } }
public static void CreateRequestHttpRequest(string userRequestStr, CreateHttpRequestSyncStateCallback syncStateCallback, CreateHttpRequestFinishedCallback finishedCallback) { new Thread(() => { Thread.CurrentThread.IsBackground = true; HttpWebResponse response = null; try { if (syncStateCallback != null) { syncStateCallback.Invoke(Dialog_ModSync_Window.CurrentSyncState.RequestStarted); } // Create a request using a URL that can receive a post. WebRequest request = WebRequest.Create(API); // Set the Method property of the request to POST. request.Method = "POST"; request.Timeout = 20000; // Create POST data and convert it to a byte array. string postData = userRequestStr; MSLog.Log("Sending request to server: " + postData); byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. request.ContentType = "application/json; charset=utf-8"; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. response = (HttpWebResponse)request.GetResponse(); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); responseFromServer = responseFromServer.Trim('\"'); reader.Close(); dataStream.Close(); MSLog.Log("Connection closed with response:" + responseFromServer); // 3 is the length of our error codes, since base64 length is base 4, no valid response will have a length of 3 if (!String.IsNullOrEmpty(responseFromServer) && responseFromServer.Length.Equals(3)) { MSLog.Log("ModSync Ninja has encountered an error with your request if this error repeats, feel free to submit the error below to the forums", MSLog.Level.User); MSLog.Log("Your request: " + userRequestStr, MSLog.Level.User); MSLog.Log("Response Error: " + responseFromServer, MSLog.Level.User); if (finishedCallback != null) { finishedCallback.Invoke(String.Empty, false, responseFromServer); } } else if (finishedCallback != null) { finishedCallback.Invoke(responseFromServer, true); } } catch (WebException e) { bool showErrorWindow = true; if (e.Status == WebExceptionStatus.ConnectFailure || e.Status == WebExceptionStatus.Timeout || e.Status == WebExceptionStatus.ConnectionClosed) { syncStateCallback(Dialog_ModSync_Window.CurrentSyncState.ModSyncOffline); showErrorWindow = false; } MSLog.Log("ModSync Ninja has encountered an error with your request if this error repeats, feel free to submit the error below to the forums", MSLog.Level.User); MSLog.Log("Your request: " + userRequestStr, MSLog.Level.User); if (e.Status == WebExceptionStatus.ProtocolError) { response = (HttpWebResponse)e.Response; MSLog.Log("Response Errorcode: " + (int)response.StatusCode, MSLog.Level.User); if (finishedCallback != null) { finishedCallback.Invoke(String.Empty, false, response.StatusCode.ToString()); } } else { MSLog.Log("Response error: " + e.Status, MSLog.Level.User); if (finishedCallback != null) { finishedCallback.Invoke(String.Empty, false, e.Status.ToString()); } } if (showErrorWindow) { MSLog.ShowErrorScreen(); } } finally { if (response != null) { response.Close(); } } }).Start(); }
public void OnRequestFromServerResponse(string responseStr, bool success, string errorCode = "") { MSLog.Log("OnRequestFromServerResponse, GOT: response:" + responseStr + "\nSuccess: " + success + "\nErrorCode: " + errorCode); if (!success) { // server not offline, this is a real error if (CurrSyncState != CurrentSyncState.ModSyncOffline) { CurrSyncState = CurrentSyncState.ModSyncError; _errorCode = errorCode; } } else { // clear previous errors _errorCode = String.Empty; // empty response if (responseStr.Length == 0) { CurrSyncState = CurrentSyncState.Done; return; } string responseData; ModDetailsResponse[] responseDataObj; try { responseData = Encoding.UTF8.GetString(Convert.FromBase64String(responseStr)); } catch (Exception e) { // Failed to parse BASE 64 MSLog.Log("Failed to parse BASE 64"); MSLog.Log(e.Message); CurrSyncState = CurrentSyncState.ModSyncError; _errorCode = "151"; return; } try { MSLog.Log("Response data BASE 64 set: " + responseData); string[] rows = Regex.Split(responseData.Trim('\"'), "{%}"); if (rows.Length == 0) { CurrSyncState = CurrentSyncState.Done; return; } MSLog.Log("Trying to parse data rows"); try { foreach (string row in rows) { string rowData = Encoding.UTF8.GetString(Convert.FromBase64String(row)); MSLog.Log("Raw row data: " + rowData); ModDetailsResponse rowDataParsed = JsonUtility.FromJson <ModDetailsResponse>(rowData); if (rowDataParsed != null) { MSLog.Log("MF:" + rowDataParsed.MF + " V:" + rowDataParsed.V + " S" + rowDataParsed.S + " SB" + rowDataParsed.SB); var modData = _relevantMods.FirstOrDefault(x => x.ModDirName.ToUpper().Equals(rowDataParsed.MF.ToUpper())); if (modData == null) { continue; } modData.RemoteData = new RemoteModData(); modData.IsModSyncMod = true; modData.RemoteData.IsModSyncMod = true; modData.RemoteData.Version = rowDataParsed.V; modData.RemoteData.DownloadUrl = rowDataParsed.S; modData.RemoteData.IsSaveBreaking = rowDataParsed.SB; modData.ServerLoadedModData = true; } else { MSLog.Log("Received invalid row, ignoring."); } } } catch (Exception e) { MSLog.Log("Exception:"); MSLog.Log(e.Message); CurrSyncState = CurrentSyncState.ModSyncError; _errorCode = "152"; } MSLog.Log("Finished reading json"); } catch (Exception e) { // failed to parse JSON MSLog.Log("Failed to parse JSON"); MSLog.Log(e.Message); CurrSyncState = CurrentSyncState.ModSyncError; _errorCode = "153"; return; } //CurrSyncState = CurrentSyncState.RequestStarted; CurrSyncState = CurrentSyncState.Done; } }