transferwee.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (c) 2018-2020 Leonardo Taccari
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in the
  14. # documentation and/or other materials provided with the distribution.
  15. #
  16. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  17. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  18. # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  19. # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
  20. # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  21. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  22. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  23. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  24. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  25. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  26. # POSSIBILITY OF SUCH DAMAGE.
  27. #
  28. """
  29. Download/upload files via wetransfer.com
  30. transferwee is a script/module to download/upload files via wetransfer.com.
  31. It exposes `download' and `upload' subcommands, respectively used to download
  32. files from a `we.tl' or `wetransfer.com/downloads' URLs and upload files that
  33. will be shared via emails or link.
  34. """
  35. from typing import List
  36. import os.path
  37. import re
  38. import urllib.parse
  39. import zlib
  40. import requests
  41. WETRANSFER_API_URL = 'https://wetransfer.com/api/v4/transfers'
  42. WETRANSFER_DOWNLOAD_URL = WETRANSFER_API_URL + '/{transfer_id}/download'
  43. WETRANSFER_UPLOAD_EMAIL_URL = WETRANSFER_API_URL + '/email'
  44. WETRANSFER_VERIFY_URL = WETRANSFER_API_URL + '/{transfer_id}/verify'
  45. WETRANSFER_UPLOAD_LINK_URL = WETRANSFER_API_URL + '/link'
  46. WETRANSFER_FILES_URL = WETRANSFER_API_URL + '/{transfer_id}/files'
  47. WETRANSFER_PART_PUT_URL = WETRANSFER_FILES_URL + '/{file_id}/part-put-url'
  48. WETRANSFER_FINALIZE_MPP_URL = WETRANSFER_FILES_URL + '/{file_id}/finalize-mpp'
  49. WETRANSFER_FINALIZE_URL = WETRANSFER_API_URL + '/{transfer_id}/finalize'
  50. WETRANSFER_DEFAULT_CHUNK_SIZE = 5242880
  51. WETRANSFER_EXPIRE_IN = 604800
  52. def download_url(url: str) -> str:
  53. """Given a wetransfer.com download URL download return the downloadable URL.
  54. The URL should be of the form `https://we.tl/' or
  55. `https://wetransfer.com/downloads/'. If it is a short URL (i.e. `we.tl')
  56. the redirect is followed in order to retrieve the corresponding
  57. `wetransfer.com/downloads/' URL.
  58. The following type of URLs are supported:
  59. - `https://we.tl/<short_url_id>`:
  60. received via link upload, via email to the sender and printed by
  61. `upload` action
  62. - `https://wetransfer.com/<transfer_id>/<security_hash>`:
  63. directly not shared in any ways but the short URLs actually redirect to
  64. them
  65. - `https://wetransfer.com/<transfer_id>/<recipient_id>/<security_hash>`:
  66. received via email by recipients when the files are shared via email
  67. upload
  68. Return the download URL (AKA `direct_link') as a str or None if the URL
  69. could not be parsed.
  70. """
  71. # Follow the redirect if we have a short URL
  72. if url.startswith('https://we.tl/'):
  73. r = requests.head(url, allow_redirects=True)
  74. url = r.url
  75. recipient_id = None
  76. params = urllib.parse.urlparse(url).path.split('/')[2:]
  77. if len(params) == 2:
  78. transfer_id, security_hash = params
  79. elif len(params) == 3:
  80. transfer_id, recipient_id, security_hash = params
  81. else:
  82. return None
  83. j = {
  84. "intent": "entire_transfer",
  85. "security_hash": security_hash,
  86. }
  87. if recipient_id:
  88. j["recipient_id"] = recipient_id
  89. s = _prepare_session()
  90. r = s.post(WETRANSFER_DOWNLOAD_URL.format(transfer_id=transfer_id),
  91. json=j)
  92. j = r.json()
  93. return j.get('direct_link')
  94. def _file_unquote(file: str) -> str:
  95. """Given a URL encoded file unquote it.
  96. All occurrences of `\', `/' and `../' will be ignored to avoid possible
  97. directory traversals.
  98. """
  99. return urllib.parse.unquote(file).replace('../', '').replace('/', '').replace('\\', '')
  100. def download(url: str, file: str = '') -> None:
  101. """Given a `we.tl/' or `wetransfer.com/downloads/' download it.
  102. First a direct link is retrieved (via download_url()), the filename can be
  103. provided via the optional `file' argument. If not provided the filename
  104. will be extracted to it and it will be fetched and stored on the current
  105. working directory.
  106. """
  107. dl_url = download_url(url)
  108. if not file:
  109. file = _file_unquote(urllib.parse.urlparse(dl_url).path.split('/')[-1])
  110. r = requests.get(dl_url, stream=True)
  111. with open(file, 'wb') as f:
  112. for chunk in r.iter_content(chunk_size=1024):
  113. f.write(chunk)
  114. def _file_name_and_size(file: str) -> dict:
  115. """Given a file, prepare the "name" and "size" dictionary.
  116. Return a dictionary with "name" and "size" keys.
  117. """
  118. filename = os.path.basename(file)
  119. filesize = os.path.getsize(file)
  120. return {
  121. "name": filename,
  122. "size": filesize
  123. }
  124. def _prepare_session() -> requests.Session:
  125. """Prepare a wetransfer.com session.
  126. Return a requests session that will always pass the required headers
  127. and with cookies properly populated that can be used for wetransfer
  128. requests.
  129. """
  130. s = requests.Session()
  131. r = s.get('https://wetransfer.com/')
  132. m = re.search('name="csrf-token" content="([^"]+)"', r.text)
  133. s.headers.update({
  134. 'x-csrf-token': m.group(1),
  135. 'x-requested-with': 'XMLHttpRequest',
  136. })
  137. return s
  138. def _prepare_email_upload(filenames: List[str], message: str,
  139. sender: str, recipients: List[str],
  140. session: requests.Session) -> str:
  141. """Given a list of filenames, message a sender and recipients prepare for
  142. the email upload.
  143. Return the parsed JSON response.
  144. """
  145. j = {
  146. "files": [_file_name_and_size(f) for f in filenames],
  147. "from": sender,
  148. "message": message,
  149. "recipients": recipients,
  150. "ui_language": "en",
  151. }
  152. r = session.post(WETRANSFER_UPLOAD_EMAIL_URL, json=j)
  153. return r.json()
  154. def _verify_email_upload(transfer_id: str, session: requests.Session) -> str:
  155. """Given a transfer_id, read the code from standard input.
  156. Return the parsed JSON response.
  157. """
  158. code = input('Code:')
  159. j = {
  160. "code": code,
  161. "expire_in": WETRANSFER_EXPIRE_IN,
  162. }
  163. r = session.post(WETRANSFER_VERIFY_URL.format(transfer_id=transfer_id),
  164. json=j)
  165. return r.json()
  166. def _prepare_link_upload(filenames: List[str], message: str,
  167. session: requests.Session) -> str:
  168. """Given a list of filenames and a message prepare for the link upload.
  169. Return the parsed JSON response.
  170. """
  171. j = {
  172. "files": [_file_name_and_size(f) for f in filenames],
  173. "message": message,
  174. "ui_language": "en",
  175. }
  176. r = session.post(WETRANSFER_UPLOAD_LINK_URL, json=j)
  177. return r.json()
  178. def _prepare_file_upload(transfer_id: str, file: str,
  179. session: requests.Session) -> str:
  180. """Given a transfer_id and file prepare it for the upload.
  181. Return the parsed JSON response.
  182. """
  183. j = _file_name_and_size(file)
  184. r = session.post(WETRANSFER_FILES_URL.format(transfer_id=transfer_id),
  185. json=j)
  186. return r.json()
  187. def _upload_chunks(transfer_id: str, file_id: str, file: str,
  188. session: requests.Session,
  189. default_chunk_size: int = WETRANSFER_DEFAULT_CHUNK_SIZE) -> str:
  190. """Given a transfer_id, file_id and file upload it.
  191. Return the parsed JSON response.
  192. """
  193. f = open(file, 'rb')
  194. chunk_number = 0
  195. while True:
  196. chunk = f.read(default_chunk_size)
  197. chunk_size = len(chunk)
  198. if chunk_size == 0:
  199. break
  200. chunk_number += 1
  201. j = {
  202. "chunk_crc": zlib.crc32(chunk),
  203. "chunk_number": chunk_number,
  204. "chunk_size": chunk_size,
  205. "retries": 0
  206. }
  207. r = session.post(
  208. WETRANSFER_PART_PUT_URL.format(transfer_id=transfer_id,
  209. file_id=file_id),
  210. json=j)
  211. url = r.json().get('url')
  212. requests.options(url,
  213. headers={
  214. 'Origin': 'https://wetransfer.com',
  215. 'Access-Control-Request-Method': 'PUT',
  216. })
  217. requests.put(url, data=chunk)
  218. j = {
  219. 'chunk_count': chunk_number
  220. }
  221. r = session.put(
  222. WETRANSFER_FINALIZE_MPP_URL.format(transfer_id=transfer_id,
  223. file_id=file_id),
  224. json=j)
  225. return r.json()
  226. def _finalize_upload(transfer_id: str, session: requests.Session) -> str:
  227. """Given a transfer_id finalize the upload.
  228. Return the parsed JSON response.
  229. """
  230. r = session.put(WETRANSFER_FINALIZE_URL.format(transfer_id=transfer_id))
  231. return r.json()
  232. def upload(files: List[str], message: str = '', sender: str = None,
  233. recipients: List[str] = []) -> str:
  234. """Given a list of files upload them and return the corresponding URL.
  235. Also accepts optional parameters:
  236. - `message': message used as a description of the transfer
  237. - `sender': email address used to receive an ACK if the upload is
  238. successful. For every download by the recipients an email
  239. will be also sent
  240. - `recipients': list of email addresses of recipients. When the upload
  241. succeed every recipients will receive an email with a link
  242. If both sender and recipient parameters are passed the email upload will be
  243. used. Otherwise, the link upload will be used.
  244. Return the short URL of the transfer on success.
  245. """
  246. # Check that all files exists
  247. for f in files:
  248. if not os.path.exists(f):
  249. raise FileNotFoundError(f)
  250. # Check that there are no duplicates filenames
  251. # (despite possible different dirname())
  252. filenames = [os.path.basename(f) for f in files]
  253. if len(files) != len(set(filenames)):
  254. raise FileExistsError('Duplicate filenames')
  255. transfer_id = None
  256. s = _prepare_session()
  257. if sender and recipients:
  258. # email upload
  259. transfer_id = \
  260. _prepare_email_upload(files, message, sender, recipients, s)['id']
  261. _verify_email_upload(transfer_id, s)
  262. else:
  263. # link upload
  264. transfer_id = _prepare_link_upload(files, message, s)['id']
  265. for f in files:
  266. file_id = _prepare_file_upload(transfer_id, f, s)['id']
  267. _upload_chunks(transfer_id, file_id, f, s)
  268. return _finalize_upload(transfer_id, s)['shortened_url']
  269. if __name__ == '__main__':
  270. from sys import exit
  271. import argparse
  272. ap = argparse.ArgumentParser(
  273. prog='transferwee',
  274. description='Download/upload files via wetransfer.com'
  275. )
  276. sp = ap.add_subparsers(dest='action', help='action')
  277. # download subcommand
  278. dp = sp.add_parser('download', help='download files')
  279. dp.add_argument('-g', action='store_true',
  280. help='only print the direct link (without downloading it)')
  281. dp.add_argument('-o', type=str, default='', metavar='file',
  282. help='output file to be used')
  283. dp.add_argument('url', nargs='+', type=str, metavar='url',
  284. help='URL (we.tl/... or wetransfer.com/downloads/...)')
  285. # upload subcommand
  286. up = sp.add_parser('upload', help='upload files')
  287. up.add_argument('-m', type=str, default='', metavar='message',
  288. help='message description for the transfer')
  289. up.add_argument('-f', type=str, metavar='from', help='sender email')
  290. up.add_argument('-t', nargs='+', type=str, metavar='to',
  291. help='recipient emails')
  292. up.add_argument('files', nargs='+', type=str, metavar='file',
  293. help='files to upload')
  294. args = ap.parse_args()
  295. if args.action == 'download':
  296. if args.g:
  297. for u in args.url:
  298. print(download_url(u))
  299. else:
  300. for u in args.url:
  301. download(u, args.o)
  302. exit(0)
  303. if args.action == 'upload':
  304. print(upload(args.files, args.m, args.f, args.t))
  305. exit(0)
  306. # No action selected, print help message
  307. ap.print_help()
  308. exit(1)