Exemple #1
0
        public static async Task <SavesClass> UploadFilesAsync(string PathFileToUpload, string Username, ProgressBar PB, Label LBL)
        {
            string Filename = Path.GetFileName(PathFileToUpload);
            string DLink, FileSize;

            try
            {
                using (MALogin MAL = new MALogin())
                {
                    MegaApiClient client = MAL.Login();
                    INode         Folder = await Task.Run(() => ChkIfFolderAndFileExist(client, Username, Filename));

                    if (Folder != null)
                    {
                        Progress <double> ze = new Progress <double>(p => PB.Dispatcher.Invoke(DispatcherPriority.Normal,
                                                                                               new Action(() => { UpdateMessages.UploadMsg((int)p, PB, LBL); })));
                        using (FileStream stream = File.Open(@PathFileToUpload, FileMode.Open))
                        {
                            INode FileUploaded = await client.UploadAsync(stream, Filename, Folder, ze); //Uploading File from PC to Mega

                            //INode FileUploaded = await client.UploadFileAsync(PathFileToUpload, Folder, ze); //Uploading File from PC to Mega
                            if (FileUploaded != null)
                            {
                                DLink    = (await client.GetDownloadLinkAsync(FileUploaded)).ToString();
                                FileSize = (((int)(FileUploaded.Size / 1024))).ToString(); //Size in Kb
                                client.Logout();
                                GC.Collect();                                              // TENGO QUE LLAMAR ESTO O NO DEJA BORRAR EL ARCHIVO ZIP PORQUE DICE QUE AUN ESTA EN USO.
                                if (!DLink.Equals(""))
                                {
                                    SavesClass SC = new SavesClass();
                                    SC.DLink = DLink;
                                    SC.Size  = FileSize;
                                    return(SC);
                                }
                                else
                                {
                                    PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.UploadMsg(101, PB, LBL); }));
                                    return(null);
                                }
                            }
                            PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.UploadMsg(101, PB, LBL); }));
                            return(null);
                        }
                    }
                    else
                    {
                        PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.UploadMsg(101, PB, LBL); }));
                        return(null);
                    }
                }
            }
            catch
            {
                PB.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { UpdateMessages.UploadMsg(102, PB, LBL); }));
                return(null);
            }
        }
Exemple #2
0
        public static async Task <bool> DownloadFilesToLocal(string DeviceIP, string SavesFTPPath, string SaveTitle, string SaveDescription, string SaveRegion, string SaveType, TextBox txtHasExtData, ProgressBar PB, Label LBL)
        {
            try
            {
                string FilesIncluded = "";
                UpdateMessages.UploadMsg(-1, PB, LBL);
                int    HasExtData     = 0;
                char   separator      = Path.DirectorySeparatorChar;
                string TempFolderPath = Constants.TempFolder + separator + "TempSaves";
                string SavesPath      = SavesFTPPath.Substring(1);
                //MessageBox.Show(SavesPath);
                string ExtDataPath = Utils.ReplaceFirstOccurrence(SavesPath, "Saves", "ExtData");
                string fullPath    = Path.GetFullPath(SavesFTPPath).TrimEnd(separator);
                string GameName    = Path.GetFileName(Path.GetDirectoryName(fullPath));
                fullPath = Utils.ReplaceLastOccurrence(fullPath, separator.ToString(), "_");
                string ZipName = Path.GetFileName(fullPath) + "_" + Constants.User + ".zip";

                List <String> SavesList   = new List <string>();
                List <String> ExtDataList = new List <string>();
                // create an FTP client
                using (FtpClient client = new FtpClient(DeviceIP))
                {
                    client.Port = 5000;
                    // if you don't specify login credentials, we use the "anonymous" user account
                    client.Credentials = new System.Net.NetworkCredential("anonymous", "anonymous");
                    // begin connecting to the server
                    client.Connect();
                    // retry up to 4 times when uploading a file (in case of file corruption)
                    client.RetryAttempts = 4;
                    // get a list of files and directories
                    foreach (FtpListItem item in await client.GetListingAsync(SavesFTPPath))
                    {
                        // if it is a file
                        if (item.Type == FtpFileSystemObjectType.File)
                        {
                            SavesPath = System.IO.Path.GetDirectoryName(item.FullName).Substring(1);
                            Dir.CreateDir(TempFolderPath, SavesPath, null);
                            // download the file
                            await client.DownloadFileAsync(@item.FullName.Substring(1), item.FullName, true, FtpVerify.Retry);

                            SavesList.Add(item.FullName);
                            FilesIncluded += item.Name + "|";
                        }
                        // if it is a folder then go deeper to fin more files
                        if (item.Type == FtpFileSystemObjectType.Directory)
                        {
                            foreach (FtpListItem itemLevel2 in await client.GetListingAsync(item.FullName))
                            {
                                SavesPath = System.IO.Path.GetDirectoryName(itemLevel2.FullName).Substring(1);
                                Dir.CreateDir(TempFolderPath, SavesPath, null);
                                await client.DownloadFileAsync(@itemLevel2.FullName.Substring(1), itemLevel2.FullName, true, FtpVerify.Retry);

                                SavesList.Add(itemLevel2.FullName);
                                FilesIncluded += itemLevel2.Name + "|";
                            }
                        }
                    }

                    string ExtDataFTP = Utils.ReplaceFirstOccurrence(SavesFTPPath, "Saves", "ExtData");
                    if (client.DirectoryExists(ExtDataFTP))
                    {
                        foreach (FtpListItem item in await client.GetListingAsync(ExtDataFTP))
                        {
                            // if it is a file
                            if (item.Type == FtpFileSystemObjectType.File)
                            {
                                ExtDataPath = System.IO.Path.GetDirectoryName(item.FullName).Substring(1);
                                Dir.CreateDir(TempFolderPath, null, ExtDataPath);
                                // download the file
                                await client.DownloadFileAsync(@item.FullName.Substring(1), item.FullName, true, FtpVerify.Retry);

                                ExtDataList.Add(item.FullName);
                                FilesIncluded += "(ExtData) " + item.Name + "|";
                            }
                            // if it is a folder then go deeper to find more files
                            if (item.Type == FtpFileSystemObjectType.Directory)
                            {
                                foreach (FtpListItem itemLevel2 in await client.GetListingAsync(item.FullName))
                                {
                                    ExtDataPath = System.IO.Path.GetDirectoryName(itemLevel2.FullName).Substring(1);
                                    Dir.CreateDir(TempFolderPath, null, ExtDataPath);
                                    await client.DownloadFileAsync(@itemLevel2.FullName.Substring(1), itemLevel2.FullName, true, FtpVerify.Retry);

                                    ExtDataList.Add(itemLevel2.FullName);
                                    FilesIncluded += "(ExtData) " + itemLevel2.Name + "|";
                                }
                            }
                        }
                    }

                    if (FilesIncluded.Length > 0)
                    {
                        FilesIncluded = FilesIncluded.Substring(0, FilesIncluded.Length - 1);
                    }

                    //Check if the saves also hast ExtData

                    if (ExtDataList.Count > 0)
                    {
                        HasExtData         = 1;
                        txtHasExtData.Text = "Yes";
                    }
                    else
                    {
                        txtHasExtData.Text = "No";
                    }

                    System.IO.Compression.ZipFile.CreateFromDirectory(@"JKSV" + separator, @TempFolderPath + separator + ZipName, System.IO.Compression.CompressionLevel.Optimal, true);

                    client.Disconnect();
                    //Uploading to mega
                    SavesClass SV = new SavesClass();
                    SV = await Mega.UploadFilesAsync(@TempFolderPath + separator + ZipName, Constants.User, PB, LBL); //Here I get DLink and FileSize

                    if (SV != null)
                    {
                        //If true then Insert/update record in DB
                        SV.IdUser        = Constants.IdUser;
                        SV.FileName      = ZipName;
                        SV.GameName      = GameName;
                        SV.SaveType      = SaveType;
                        SV.Region        = SaveRegion;
                        SV.Title         = SaveTitle;
                        SV.Description   = SaveDescription;
                        SV.FilesIncluded = FilesIncluded;
                        SV.HasExtData    = HasExtData.ToString();

                        if (SaveType != null)
                        {
                            if (await Insert.InsertNewSave(SV, PB, LBL))
                            {
                                return(true);
                            }
                        }
                        else
                        {
                            if (await Update.UpdateSaveFromFTP(SV, PB, LBL))
                            {
                                return(true);
                            }
                        }
                    }
                }
                return(false);
            }
            catch (Exception e)
            {
                MessageBox.Show("Could not complete the operation due to the following error: " + e.Message);
                return(false);
                // null;
            }
        }
        public static async Task <bool> InsertNewSave(SavesClass SV, ProgressBar PB, Label LBL)
        {
            SavesContainer SVC = new SavesContainer();

            try
            {
                string SV_obj = "";

                SV_obj = SV_obj + JsonConvert.SerializeObject(SV, Formatting.Indented);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(Constants.URL + "/api.savecentral.com/v1/files_data"));
                request.Accept      = "application/json";
                request.ContentType = "application/json";
                request.Headers.Add("authorization", Constants.ApiKey);
                request.Method = "POST";

                byte[] byteArray = Encoding.UTF8.GetBytes(SV_obj);
                request.ContentLength = byteArray.Length;
                using (Stream DataStream = await request.GetRequestStreamAsync())
                {
                    DataStream.Write(byteArray, 0, byteArray.Length);
                    DataStream.Close();

                    using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                    {
                        using (Stream ResponseStream = response.GetResponseStream())
                        {
                            using (StreamReader sr = new StreamReader(ResponseStream))
                            {
                                string ServerResponse = await sr.ReadToEndAsync();

                                SVC = JsonConvert.DeserializeObject <SavesContainer>(ServerResponse);
                                if (SVC.status.Equals("1"))
                                {
                                    //Success
                                    MessageBox.Show(SVC.message);
                                    UpdateMessages.UploadMsg(103, PB, LBL);
                                    return(true);
                                }
                                else
                                {
                                    //Fail
                                    await Delete.DeleteSelSave(SV, PB, LBL);

                                    MessageBox.Show("An error ocurred when trying to register the upload in the DB, please try again.");
                                    UpdateMessages.UploadMsg(103, PB, LBL);
                                    return(false);
                                }
                            }
                        }
                    }
                }
            }
            catch (WebException e)
            {
                await Delete.DeleteSelSave(SV, PB, LBL);

                if (e.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)e.Response)
                    {
                        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            string error = reader.ReadToEnd();
                            SVC = JsonConvert.DeserializeObject <SavesContainer>(error);
                            MessageBox.Show("The save could no be uploaded due to the following error: " + SVC.message);
                        }
                    }
                }
                UpdateMessages.UploadMsg(103, PB, LBL);
                return(false);
            }
        }
Exemple #4
0
        //Here I'm only updating the TextBox and Combobox info (DLink is the same)
        public static async Task <bool> UpdateSaveInfo(SavesClass SV, ProgressBar PB, Label LBL)
        {
            UpdateMessages.UpdateMsg(10, PB, LBL);
            SavesContainer SVC = new SavesContainer();

            try
            {
                SV.IsUpdate = "1"; //Stupid free server don't like PUT and DELETE methods so I have to force this part.
                string SV_obj = "";
                SV_obj = SV_obj + JsonConvert.SerializeObject(SV, Formatting.Indented);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(Constants.URL + "/api.savecentral.com/v1/files_data/" + WebUtility.UrlEncode(SV.FileName)));
                request.Accept      = "application/json";
                request.ContentType = "application/json";
                request.Headers.Add("authorization", Constants.ApiKey);
                request.Method    = "POST";
                request.KeepAlive = true;
                byte[] byteArray = Encoding.UTF8.GetBytes(SV_obj);
                request.ContentLength = byteArray.Length;
                using (Stream DataStream = await request.GetRequestStreamAsync())
                {
                    DataStream.Write(byteArray, 0, byteArray.Length);
                    DataStream.Close();

                    using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                    {
                        using (Stream ResponseStream = response.GetResponseStream())
                        {
                            using (StreamReader sr = new StreamReader(ResponseStream))
                            {
                                string ServerResponse = await sr.ReadToEndAsync();

                                SVC = JsonConvert.DeserializeObject <SavesContainer>(ServerResponse);
                                if (SVC.status.Equals("1"))
                                {
                                    //Success
                                    UpdateMessages.UpdateMsg(100, PB, LBL);
                                    MessageBox.Show(SVC.message);
                                    UpdateMessages.UpdateMsg(103, PB, LBL);
                                    return(true);
                                }
                                else
                                {
                                    //Fail
                                    UpdateMessages.UpdateMsg(101, PB, LBL);
                                    MessageBox.Show(SVC.message);
                                    UpdateMessages.UpdateMsg(103, PB, LBL);
                                    return(false);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                UpdateMessages.UpdateMsg(102, PB, LBL);
                MessageBox.Show("The save info could no be updated due to the following error: " + e.Message);
                UpdateMessages.UploadMsg(103, PB, LBL);
                return(false);
            }
        }