Пример #1
0
        /// <summary>
        /// Determines if instant upload is possible, if a duplicate filename exists in the destination folder, 
        /// and also verifies folder permissions for non-owner uploads. This returns a 'quickkey' on successful instant upload. 
        /// Otherwise, 'new_hash' and 'duplicate_name' are returned, which can be 'yes' or 'no'. 
        /// Based on those values, the uploader performs a regular upload or resends the same pre_upload request with the desired action. 
        /// If 'path' is specified and an instant upload was not possible, the a 'folder_key' will also be returned to be used for a regular upload.
        /// </summary>
        /// <param name="FileName">
        /// Path, name and extension of the file for which the upload should be prepared
        /// </param>
        /// <param name="MakeHash">
        /// True if SHA256 hash of file should be calculated, if false, only duplicate name is checked and no resumable upload is possible.
        /// </param>
        /// <param name="Upl_FolderID">
        /// The folderkey of the folder you wish to upload your file to. If not passed, the destination folder is the root folder.
        /// </param>
        /// <param name="ActionOnDuplicate">
        /// This is used in the case where there are duplicate file names in the same upload folder. 
        /// The values are 'keep' (to keep both files with the same name, the new file will have a numeric digit added to it), 
        /// 'skip' (this will ignore the upload), and 'replace' (this will override the original file with the new file). 
        /// If not passed, then no action will be performed on duplicate names and a flag 'duplicate_name' is set to 'yes' requesting the action to be passed.
        /// </param>
        /// <param name="Resumable"> 
        /// In the circumstance of the upload being interrupted, this indicates whether this upload can be resumed.
        /// </param>
        /// <param name="Path">
        /// The path relative to 'upload_folder_key' where the file should be uploaded. Any folders specified will be created if they do not exist.
        /// </param>
        /// <returns>IPreUpload object</returns>
        public IPreUpload PreUpload(string FileName, bool MakeHash = false, string Upl_FolderID = "",
                UploadDuplicateActions ActionOnDuplicate = UploadDuplicateActions.None, bool Resumable = false, string Path = "")
        {
            //Get API base URL
            this.BaseUrl = MediaFireConfiguration.APIBaseURL;

            //Create an Authorization request and Execute it.
            var result = base.Execute(MediaFireApiHelper.Generate_PreUpload_Request(this.Token.Access_Token, FileName, MakeHash, Upl_FolderID, ActionOnDuplicate, Resumable, Path));
            var res2 = Newtonsoft.Json.JsonConvert.DeserializeObject<PreUpload>(BaseResponse.ClearResponse(result.Content));

            //Check if received Token is valid
            if (res2 == null || res2.action == null || res2.result == null || res2.action != "upload/pre_upload" || res2.result != "Success")
            {
                if (res2.result == "Error")
                {
                    throw new Exception(res2.message);
                }
                //Not valid
                return null;
            }

            return res2;
        }
Пример #2
0
 /// <summary>
 /// Upload a file through POST to the user's account. This api returns the upload key and hash when successful. 
 /// You will have to pass this key to upload/poll_upload to get the FileID.
 /// </summary>
 /// <param name="FileName">Path, name and extension of the file to be uploaded.</param>
 /// <param name="Upl_FolderID">The folderkey of the folder where to store the file. If it's not passed, then the file will be stored in the root folder.</param>
 /// <param name="FileID">If a FileID is passed, the uploaded file content will overwrite an existing file's current revision defined by the passed FileID.</param>
 /// <param name="ActionOnDuplicate">This parameter can take 'skip', 'keep', or 'replace' as values. This will be honored only if a file with the same name in the same folder already exists. This will determine whether the file should be skipped, kept (with an appended number), or replaced.</param>
 /// <param name="Path">The path relative to 'upload_folderid' where the file should be uploaded. Any folders specified will be created if they do not exist.</param>
 /// <param name="Previous_Hash">This is the hash of the last known hash to the client of the file before it's modified. This is honored only on update uploads, that is, when passing 'quickkey' to override an existing file on the cloud. If the previous hash is different than the current version on the cloud, then this is a conflict and the file will be uploaded as a new file with new quickkey and filename.</param>
 /// <returns>IUpload object with UploadKey and Hash if succesfull and Upload Result Code and Message if not.</returns>
 public Task<IUpload> UploadFileAsync(string FileName, string Upl_FolderID = "", string FileID = "",
         UploadDuplicateActions ActionOnDuplicate = UploadDuplicateActions.None, string Path = "", string Previous_Hash = "")
 {
     Task<IUpload> t = Task<IUpload>.Factory.StartNew(() =>
     {
         return UploadFile(FileName, Upl_FolderID, FileID, ActionOnDuplicate, Path, Previous_Hash);
     });
     return t;
 }
Пример #3
0
        /// <summary>
        /// Upload a file through POST to the user's account. This api returns the upload key and hash when successful. 
        /// You will have to pass this key to upload/poll_upload to get the FileID.
        /// </summary>
        /// <param name="FileName">Path, name and extension of the file to be uploaded.</param>
        /// <param name="Upl_FolderID">The folderkey of the folder where to store the file. If it's not passed, then the file will be stored in the root folder.</param>
        /// <param name="FileID">If a FileID is passed, the uploaded file content will overwrite an existing file's current revision defined by the passed FileID.</param>
        /// <param name="ActionOnDuplicate">This parameter can take 'skip', 'keep', or 'replace' as values. This will be honored only if a file with the same name in the same folder already exists. This will determine whether the file should be skipped, kept (with an appended number), or replaced.</param>
        /// <param name="Path">The path relative to 'upload_folderid' where the file should be uploaded. Any folders specified will be created if they do not exist.</param>
        /// <param name="Previous_Hash">This is the hash of the last known hash to the client of the file before it's modified. This is honored only on update uploads, that is, when passing 'quickkey' to override an existing file on the cloud. If the previous hash is different than the current version on the cloud, then this is a conflict and the file will be uploaded as a new file with new quickkey and filename.</param>
        /// <returns>IUpload object with UploadKey and Hash if succesfull and Upload Result Code and Message if not.</returns>
        public IUpload UploadFile(string FileName, string Upl_FolderID = "", string FileID = "",
                UploadDuplicateActions ActionOnDuplicate = UploadDuplicateActions.None, string Path = "", string Previous_Hash = "")
        {
            var req = MediaFireApiHelper.Generate_Upload_Request(this.Token.Access_Token, MediaFireConfiguration.BaseURL, FileName,
                    Upl_FolderID, FileID, ActionOnDuplicate, Path, Previous_Hash);

            var res = req.GetResponse();

            var res2 = Newtonsoft.Json.JsonConvert.DeserializeObject<Upload>(BaseResponse.ClearResponse(MediaFireApiHelper.GetResponseContent(res)));

            //Check if received Token is valid
            if (res2 == null || res2.action == null || res2.result == null || res2.action != "upload/upload.php" || res2.result != "Success")
            {
                if (res2.result == "Error")
                {
                    throw new Exception(res2.message);
                }
                //Not valid
                return null;
            }

            res2.Hash = req.Headers["X-Filehash"];

            return res2;
        }
Пример #4
0
        /// <summary>
        /// DO NOT WORK - API RETURNS ALWAYS PROBLEM WITH HASH WHERE IT IS OK. USE UPLOADFILE()
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="Upl_FolderID"></param>
        /// <param name="ActionOnDuplicate"></param>
        /// <param name="Path"></param>
        /// <returns></returns>
        public IUpload ResumableUppload(string FileName, string Upl_FolderID="", UploadDuplicateActions ActionOnDuplicate = UploadDuplicateActions.None, string Path="")
        {
            IPreUpload preUploadResult = PreUpload(FileName, MakeHash: true, Upl_FolderID: Upl_FolderID, ActionOnDuplicate: ActionOnDuplicate, Resumable: true, Path: Path);

            if (!string.IsNullOrEmpty(preUploadResult.FileID))
            {
                return new Upload()
                {
                    upload_key = preUploadResult.FileID,
                    result = "Success",
                    message = "UploadKey contains FileID"
                };
            }

            if (preUploadResult.Resumable_upload == null)
            {
                return null; // error
            }

            if (preUploadResult.Resumable_upload.Number_of_units == 1)
            {
                //Normal Upload
                return UploadFile(FileName, Upl_FolderID, ActionOnDuplicate: ActionOnDuplicate, Path: Path);
            }

            int Unit_Size = preUploadResult.Resumable_upload.Unit_size;
            int Nb_Units = preUploadResult.Resumable_upload.Number_of_units;
            var bitmap = MediaFireApiHelper.decodeBitmap(preUploadResult.Resumable_upload.UploadBitmap);

            if (bitmap.Count != Nb_Units)
            {
                //Error
            }

            System.IO.FileInfo fi = new System.IO.FileInfo(FileName);
            using (System.IO.FileStream file = fi.OpenRead())
            {
                byte[] buffer = new byte[Unit_Size];
                for (int i = 0; i < Nb_Units - 1; i++)
                {
                    if (!bitmap[i])
                    {
                        file.Read(buffer, 0, Unit_Size);
                        IUpload result = UploadFilePart(FileName, buffer, i, Upl_FolderID);
                    }
                }

                if (!bitmap[bitmap.Count - 1])
                {
                    buffer = new byte[fi.Length - ((Nb_Units - 1) * Unit_Size)];
                    file.Read(buffer, 0, buffer.Length);
                    IUpload result = UploadFilePart(FileName, buffer, Nb_Units-1, Upl_FolderID);
                }
            }

            return null;
        }
Пример #5
0
        public static System.Net.HttpWebRequest Generate_Upload_Request(string SessionToken, string BaseUrl, string FileName, string Upl_FolderID = "", string FileID = "",
                UploadDuplicateActions ActionOnDuplicate = UploadDuplicateActions.None, string Path = "", string Previous_Hash = "")
        {
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(FileName);
            //Get API base URL

            if (BaseUrl.Last() != '/') BaseUrl += "/";
            StringBuilder uploadAddress = new StringBuilder(BaseUrl).Append(MediaFireConfiguration.Upload).Append("&session_token=").Append(SessionToken);
            if (!string.IsNullOrEmpty(Upl_FolderID))
            {
                uploadAddress.Append("&upload_key=").Append(Upl_FolderID);
            }
            else
            {
                uploadAddress.Append("&upload_key=").Append("myfiles");
            }
            uploadAddress.Append("&filenum=0&uploader=0&response_format=json");

            if (!string.IsNullOrEmpty(FileID))
            {
                uploadAddress.Append("&quick_key=").Append(FileID);
            }

            switch (ActionOnDuplicate)
            {
                case UploadDuplicateActions.Keep:
                    uploadAddress.Append("&action_on_duplicate=").Append("keep");
                    break;
                case UploadDuplicateActions.Skip:
                    uploadAddress.Append("&action_on_duplicate=").Append("skip");
                    break;
                case UploadDuplicateActions.Replace:
                    uploadAddress.Append("&action_on_duplicate=").Append("replace");
                    break;
            }

            if (!string.IsNullOrEmpty(Path))
            {
                uploadAddress.Append("&path=").Append(Path);
            }

            if (!string.IsNullOrEmpty(Previous_Hash))
            {
                uploadAddress.Append("&previous_hash=").Append(Previous_Hash);
            }

            var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uploadAddress.ToString());
            req.Accept = "*/*";
            req.ContentType = "application/octet-stream";
            req.Method = "POST";
            req.SendChunked = false;
            req.Referer = "https://www.mediafire.com/apps/myfiles/?shared=0&multikeys=0";
            req.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.72 Safari/537.36";
            req.Headers.Add("Origin", "https://www.mediafire.com");
            req.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            req.Headers.Add("Accept-Language", "en-US,en;q=0.8,de;q=0.6,pl;q=0.4");
            req.Headers.Add("X-Filename", fileInfo.Name);
            req.Headers.Add("X-Filesize", fileInfo.Length.ToString());
            req.ContentLength = fileInfo.Length;
            req.Headers.Add("X-Filetype", "text/plain");

            using (System.IO.FileStream fs = fileInfo.OpenRead())
            {
                fs.Position = 0;

                System.Security.Cryptography.SHA256 mySHA = System.Security.Cryptography.SHA256Managed.Create();
                byte[] hashValue = mySHA.ComputeHash(fs);
                req.Headers.Add("X-Filehash", BitConverter.ToString(hashValue).Replace("-", ""));
            }

            using (var rs = req.GetRequestStream())
            {
                rs.Write(System.IO.File.ReadAllBytes(FileName), 0, System.IO.File.ReadAllBytes(FileName).Length);
            }

            return req;
        }
Пример #6
0
        public static RestSharp.RestRequest Generate_PreUpload_Request(string SessionToken, string FileName, bool MakeHash = false, string Upl_FolderID = "",
                UploadDuplicateActions ActionOnDuplicate = UploadDuplicateActions.None, bool Resumable = false, string Path = "")
        {
            RestRequest rr = new RestRequest(MediaFireConfiguration.PreUpload, Method.POST);
            rr.RequestFormat = DataFormat.Json;
            rr.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            rr.AddParameter("session_token", SessionToken);

            if (!System.IO.File.Exists(FileName))
            {
                throw new System.IO.FileNotFoundException("The file " + FileName + " was not found");
            }

            rr.AddParameter("filename", new System.IO.FileInfo(FileName).Name);

            if (MakeHash)
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(FileName, System.IO.FileMode.Open))
                {
                    fs.Position = 0;

                    SHA256 mySHA = SHA256Managed.Create();
                    byte[] hashValue = mySHA.ComputeHash(fs);
                    rr.AddParameter("hash", BitConverter.ToString(hashValue).Replace("-", ""));
                }
                rr.AddParameter("size", new System.IO.FileInfo(FileName).Length);
            }

            if (!string.IsNullOrEmpty(Upl_FolderID))
            {
                rr.AddParameter("upload_folder_key", Upl_FolderID);
            }

            if (!string.IsNullOrEmpty(Path))
            {
                rr.AddParameter("path", Path);
            }

            switch (ActionOnDuplicate)
            {
                case UploadDuplicateActions.Keep:
                    rr.AddParameter("action_on_duplicate", "keep");
                    break;
                case UploadDuplicateActions.Skip:
                    rr.AddParameter("action_on_duplicate", "skip");
                    break;
                case UploadDuplicateActions.Replace:
                    rr.AddParameter("action_on_duplicate", "replace");
                    break;
            }

            if (Resumable)
            {
                if (!MakeHash) throw new ArgumentNullException("If you want to create resumable pre upload hash must be calculated");
                rr.AddParameter("resumable", "yes");
            }
            else
            {
                rr.AddParameter("resumable", "no");
            }

            rr.AddParameter("response_format", "json");

            return rr;
        }