From a94c21fdd1e5e98c17e1bf6583dcd1d35f65ffbe Mon Sep 17 00:00:00 2001 From: vulet Date: Fri, 6 Nov 2020 21:00:38 +0800 Subject: [PATCH] refactor(fediverse): add filename to media uploads --- commands/media.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/commands/media.js b/commands/media.js index 1160ce9..15e45eb 100644 --- a/commands/media.js +++ b/commands/media.js @@ -2,20 +2,30 @@ const qs = require('qs'); const axios = require('axios'); const FormData = require('form-data'); +const getFilename = header => { + if(typeof header !== 'string') return null; + try { + const m = header.match(/inline; filename(?:=(.+)|\*=utf-8''(.+))/); + return !m ? null : m[2] && decodeURIComponent(m[2]) || m[1]; + } catch(e) { + return null; + } +}; + const mediaDownload = async (url, types) => { const media = await axios({ method: 'GET', url, responseType: 'arraybuffer' }); if (media.statusText !== 'OK' || !types.includes(media.headers['content-type'])) throw media; return { data: media.data, - //filename: //TODO, + filename: getFilename(media.headers['content-disposition']), mimetype: media.headers['content-type'] }; }; -const mediaUpload = async ({ domain, token }, { data, mimetype }) => { +const mediaUpload = async ({ domain, token }, { data, filename, mimetype }) => { const form = new FormData(); form.append('file', data, { - filename: 'upload', + filename: filename || 'upload', contentType: mimetype, }); const upload = await axios({