7 Mayıs 2015 Perşembe

C# Code for Downloading WeTransfer Files (https://www.wetransfer.com/)

I was doing an asp.net web application project and I needed to download files from WeTransfer. I have searched web but couldn't found any C# code about this topic. Then i found a Phyton code (Link: https://github.com/superalex/py-wetransfer) and convert it to C# by myself. Just dropping the dirty code here as in my project.(with some minor changes :)) You can clear and use the code as you wish.


using Newtonsoft.Json;

using Newtonsoft.Json.Linq;

using System;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.IO;

using System.Net;

using System.Net.Http;

using System.Web;

using System.Web.UI;

 

private const string DOWNLOAD_URL_PARAMS_PREFIX = "downloads/";

private const int CHUNK_SIZE = 1024;

 

protected async void btnDownloadWeTransferFile_Click(object sender, EventArgs e)

        {

            if (string.IsNullOrWhiteSpace(txtFileLink.Text))

            {

                ClientScript.RegisterClientScriptBlock(GetType(), "alertMessage", "alert(\"" + "Link is empty!" + "\");", true);

                return;

            }

 

            HttpClient client = new HttpClient();

            HttpResponseMessage response = await client.GetAsync(txtFileLink.Text);

            response.EnsureSuccessStatusCode();

            string responseUri = response.RequestMessage.RequestUri.ToString();

 

            if (!responseUri.Contains("www.wetransfer.com"))

            {

                ClientScript.RegisterClientScriptBlock(GetType(), "alertMessage", "alert(\"" + "Make sure the file link is a WeTransfer file link!" + "\");", true);

                return;

            }

 

            string fileID = "", recipientID = "", securityHash = "";

 

            if (!responseUri.Contains(DOWNLOAD_URL_PARAMS_PREFIX))

            {

                ClientScript.RegisterClientScriptBlock(GetType(), "alertMessage", "alert(\"" + "File link is in an unknown format!" + "\");", true);

                return;

            }

            else

            {

                string[] splittedLink = responseUri.Split(new string[] { DOWNLOAD_URL_PARAMS_PREFIX }, StringSplitOptions.RemoveEmptyEntries);

                if (splittedLink.Length < 2)

                {

                    ClientScript.RegisterClientScriptBlock(GetType(), "alertMessage", "alert(\"" + "File link is in an unknown format!" + "\");", true);

                    return;

                }

                else

                {

                    string[] parameters = splittedLink[1].Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                    if (parameters.Length < 2 || parameters.Length > 3)

                    {

                        ClientScript.RegisterClientScriptBlock(GetType(), "alertMessage", "alert(\"" + "File link is in an unknown format!" + "\");", true);

                        return;

                    }

                    else

                    {

                        if (parameters.Length == 2)

                        {

                            fileID = parameters[0];

                            securityHash = parameters[1];

                        }

                        else

                        {

                            fileID = parameters[0];

                            recipientID = parameters[1];

                            securityHash = parameters[2];

                        }

                    }

                }

            }

 

            string directDownloadLink = "";

 

            WebClient wc = new WebClient();

            string jsonString = wc.DownloadString(string.Format("https://www.wetransfer.com/api/v1/transfers/{0}/download?recipient_id={1}&security_hash={2}&password=&ie=false", fileID, recipientID, securityHash));

 

            var stringData = (JObject)JsonConvert.DeserializeObject(jsonString);

            byte[] data = null;

            string fileName;

 

            if (stringData.GetValue("direct_link") != null)

            {

                directDownloadLink = stringData["direct_link"].Value<string>();

                directDownloadLink = HttpUtility.UrlDecode(directDownloadLink);

 

                int oIndex = directDownloadLink.IndexOf("filename=");

                string subStr = directDownloadLink.Substring(oIndex + 9);

                fileName = directDownloadLink.Substring(oIndex + 9, subStr.IndexOf(";")).Replace("\"", "");

 

                wc.UseDefaultCredentials = true;

 

                data = wc.DownloadData(directDownloadLink);

            }

            else

            {

                fileName = stringData["fields"]["filename"].Value<string>();

                NameValueCollection myNameValueCollection = new NameValueCollection();

                Dictionary<string, string> dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(stringData.GetValue("fields").ToString());

                foreach (var kvp in dict)

                {

                    myNameValueCollection.Add(kvp.Key.ToString(), kvp.Value.ToString());

                }

                data = wc.UploadValues(stringData["formdata"]["action"].Value<string>(), myNameValueCollection);

            }

 

            string filePath =  "C:\\" + fileName;

            if (File.Exists(filePath))

            {

                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);

                string fileNameExtension = Path.GetExtension(fileName);

                fileName = fileNameWithoutExtension + DateTime.Now.ToString("yyyyMMddHHmmssfff") + fileNameExtension;

            }

 

            using (FileStream fs = new FileStream(filePath, FileMode.Create))

            {

                fs.Write(data, 0, data.Length);

            }

 

            ClientScript.RegisterClientScriptBlock(GetType(), "alertMessage", "alert(\"" + "File downloaded successfully. File Name:" + fileName + "\");", true);

 

        }