Upload in MediaFire with C#

745 Views Asked by At

Is there anybody who wrote codes in MediaFire? Following this link, you can take your own session (of course with your username and password). I used this code for uploading and send values through Post method.

private static string url = "HTTPS://www.mediafire.com/api/1.3/upload/simple.php?session_token=ed007dc432d5081952c15c50a  3f5c4dade894927dbcb8c44a59c6aefag6bd1d293f90434bfa  7bcd13d284069aabfa528623601a39b7026ca534acf21a6de1  0343543e271ac5a44ca&action_on_duplicate=&response_  format=json";
        try
        {
            string posturl = url;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(posturl);
            byte[] bytes;
            bytes = File.ReadAllBytes(@"G:\Untitled.jpg");


            request.Headers.Clear();
            request.Method = "POST";
            request.Headers.Add(HttpRequestHeader.AcceptLangua  ge, "en-US,en;q=0.8,fa;q=0.6");
            request.Headers.Add(HttpRequestHeader.AcceptEncodi  ng, "gzip, deflate");
            request.ContentType = "multipart/form-data";
            request.Referer = @"https://www.mediafire.com/developers/tools/api_tools";
            request.ContentLength = bytes.Length;




            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream responseStream = response.GetResponseStream();
                string responseStr = new StreamReader(responseStream).ReadToEnd();
                textBox1.Text = responseStr;
               // return responseStr;
            }
        }
        catch (Exception s)
        {
            MessageBox.Show("Session Token Error. " + s.Message);
        }

Then unfortunately I see this error,

“session token error. the server committed a protocol violation.section=ResponseStatusLine”

Any help would be greatly appreciated. Regards

1

There are 1 best solutions below

0
On

Well, according to the Error looks like the session_token value is wrong. I am also working with Mediafire API right now and I was able to get luck with most API calls (except with upload...) So, if you read the documentation, you know the first step is to create a first call where you generate a session_token with a life time of 10 minutes (after that you must renew it). To retrieve those values, here it is my code

    public int secret_key;
    public string session_token; //is a token used to authorize user specific transactions
    public string time;
    bool first_call = true;
    bool new_key = false;



        //Creating a first session token MediaFire 
        string email = "";
        string password = "";
        string app_id = "";
        string app_key = "";

        byte[] b = Encoding.UTF8.GetBytes(email + password + app_id + app_key);
        SHA1 sh = new SHA1Managed();
        byte[] b2 = sh.ComputeHash(b);
        string signature = BitConverter.ToString(b2).Replace("-", "").ToLower();
        string req_url = String.Format("https://www.mediafire.com/api/1.4/user/get_session_token.php?email={0}&password={1}&application_id={2}&signature={3}&token_version=2", email, password, app_id, signature);

        HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(req_url);
        try
        {
            WebResponse response = myReq.GetResponse();
            Stream responseStream = response.GetResponseStream();

            XElement root = XDocument.Load(responseStream).Root;

            if (root.Element("result").Value == ("Success"))
            {
                secret_key = Convert.ToInt32(root.Element("secret_key").Value);
                session_token = root.Element("session_token").Value;
                time = root.Element("time").Value;
            }
            else if (root.Element("result").Value == ("Error"))
            {
                //TODO
                //Check errors list on MediaFire API
                int error = Convert.ToInt32(root.Element("error").Value);
                string message_error = root.Element("message").Value;
            }
        }
        catch (System.Net.WebException webEx)
        {

            HttpWebResponse response = webEx.Response as HttpWebResponse;
            if (response.StatusCode == HttpStatusCode.Forbidden)
            {
                var r_error = (HttpWebResponse)webEx.Response;
                Stream receiveStream = r_error.GetResponseStream();
                StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                string s = reader.ReadToEnd().ToString();
                XElement response_body = XDocument.Parse(s).Root;
                int error = Convert.ToInt32(response_body.Element("error").Value);
                string message_error = response_body.Element("message").Value;
            }
            else if (response.StatusCode != HttpStatusCode.Forbidden)
            {
                throw;
            }


        }

Once the session_token was created with success, you are now able to do other API calls. Something I noticed on your code is that signature is missing, however is required to any (I think so, or at least most of them) API call using a token_version=2 To calculate signatures there are a few aspects. The way you will do so it will depend if it is the first call you do with current session or not. I typed this function.
sk -> secret_key
URI -> can be like /api/1.4/upload/simple.php?session_token=" + session_token
first_call -> just to determine if it is the first call with current session or not

   static public string get_signature(int sk, string time, string URI, bool first_call)
    {
        string input = "";
        if (first_call)
        {
            sk %= 256;
            input = sk + time + URI;
        }
        else
        {
            sk = neo_secretkey(sk);
            sk %= 256;
            input = sk + time + URI;
        }

        //signature = the Message-Digest (MD5) of the 'secret_key' modulo 256 + 'time' + the URI of the API call. 
        byte[] ByteData = Encoding.ASCII.GetBytes(input);
        //MD5 creating MD5 object.
        MD5 oMd5 = MD5.Create();
        //Hash 
        byte[] HashData = oMd5.ComputeHash(ByteData);

        //convert byte array to hex format
        StringBuilder oSb = new StringBuilder();

        for (int x = 0; x < HashData.Length; x++)
        {
            //hexadecimal string value
            oSb.Append(HashData[x].ToString("x2"));
        }

        return oSb.ToString();
    }

You will see the function neosecretkey(). This is necessary for second and future calls with current session.

static public int neo_secretkey(int sk)
        {
            long n_secret = (Convert.ToInt64(sk) * 16807) % 2147483647;
            return Convert.ToInt32(n_secret);
        }

Well, now make sure everything is OK with your code. The request URL has to look like this "http://www.mediafire.com/api/1.4/upload/simple.php?session_token=" + session_token + "&signature=" + signature

My code is a bit ugly, I have not too much experience with C#. Hope this helps you :)