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);

 

        }

5 yorum:

Kişisel Blog dedi ki...

Merhaba,

Güzel bir çalışma fakat anlaşılır olabilmesi ve bizlere faydalı olabilimesi için biraz açıklama yapabilirmisiniz. Web uygulaması olarak projeyi oluşturduğumuzda 3-4 noktada hatalar alıyoruz mesela using System.Net.Http vb. Çalışması için refernas olarak başka şeylermi gerekiyor. Mesela wetransfer den üyelik gerekiyor mu.

Teşekkürler

dinçer dedi ki...

#startup @quictransfer File Sharing Upload https://quictransfer.com https://www.youtube.com/watch?v=6hgctnqE5Sg

Unknown dedi ki...

Çalışma güzel ama maalesef uygulayamıyoruz, çünkü refernas dll'lerini bulamıyoruz ve yazınızda buna dair hiçbir açıklama yok maalesef.

Unknown dedi ki...

Merhabalar;

ClientScript için hhangi dll'i eklememiz gerekiyor.

M. Uğur Can dedi ki...

Merhabalar,

Uzun zamandır blog ile ilgilenmediğimden dolayı yazılanlara cevap veremediğim için üzgünüm.
Yazımın başında belirttiğim gibi ben belirttiğim adresten aldığım kodu değiştirerek c# a uyarladım. Bu yazıyı yazdığım günden beri api bağlantı şekilleri değişmiş olabilir. Hatta ve hatta bazı methodların çağrılma şekli yeni .net framework güncellemeleri ile kullanım dışı kalmış olabilir. O yüzden buradaki kod malesef tak kullan şeklinde çalışmamaktadır. Örneğin asp.net değilde mvc kullanıyorsanız kodu uyarlamak için baya takla atmak gerekebilir.
@Yunus Köse uygulamayı asp.net ile mi yazıyorsunuz? Kullanılan materyaller ile ilgili detay verirsen yardımcı olabilirim.

İyi çalışmalar.