|
1 | | -import { ConfigurationError } from "@pipedream/platform"; |
| 1 | +import { |
| 2 | + ConfigurationError, axios, |
| 3 | +} from "@pipedream/platform"; |
2 | 4 | import fs from "fs"; |
| 5 | +import FormData from "form-data"; |
3 | 6 | import slack from "../../slack.app.mjs"; |
4 | 7 |
|
5 | 8 | export default { |
6 | 9 | key: "slack-upload-file", |
7 | 10 | name: "Upload File", |
8 | | - description: "Upload a file. [See the documentation](https://api.slack.com/methods/files.upload)", |
| 11 | + description: "Upload a file. [See the documentation](https://api.slack.com/messaging/files#uploading_files)", |
9 | 12 | version: "0.0.27", |
10 | 13 | type: "action", |
11 | 14 | props: { |
@@ -35,13 +38,54 @@ export default { |
35 | 38 | if (!fs.existsSync(this.content)) { |
36 | 39 | throw new ConfigurationError(`\`${this.content}\` not found, a valid \`/tmp\` path is needed`); |
37 | 40 | } |
38 | | - const response = await this.slack.uploadFile({ |
39 | | - file: fs.createReadStream(this.content), |
| 41 | + |
| 42 | + const filename = this.content.split("/").pop(); |
| 43 | + |
| 44 | + // Get an upload URL from Slack |
| 45 | + const getUploadUrlResponse = await this.slack.getUploadUrl({ |
| 46 | + filename, |
| 47 | + length: fs.statSync(this.content).size, |
| 48 | + }); |
| 49 | + |
| 50 | + if (!getUploadUrlResponse.ok) { |
| 51 | + throw new ConfigurationError(`Error getting upload URL: ${JSON.stringify(getUploadUrlResponse)}`); |
| 52 | + } |
| 53 | + |
| 54 | + const { |
| 55 | + upload_url: uploadUrl, file_id: fileId, |
| 56 | + } = getUploadUrlResponse; |
| 57 | + |
| 58 | + // Upload the file to the provided URL |
| 59 | + const formData = new FormData(); |
| 60 | + formData.append("file", fs.createReadStream(this.content)); |
| 61 | + formData.append("filename", filename); |
| 62 | + |
| 63 | + await axios($, { |
| 64 | + url: uploadUrl, |
| 65 | + data: formData, |
| 66 | + method: "POST", |
| 67 | + headers: { |
| 68 | + ...formData.getHeaders(), |
| 69 | + Authorization: `Bearer ${this.slack.getToken()}`, |
| 70 | + }, |
| 71 | + }); |
| 72 | + |
| 73 | + // Complete the file upload process in Slack |
| 74 | + const completeUploadResponse = await this.slack.completeUpload({ |
40 | 75 | channel_id: this.conversation, |
41 | 76 | initial_comment: this.initialComment, |
42 | | - filename: this.content.split("/").pop(), |
| 77 | + files: [ |
| 78 | + { |
| 79 | + id: fileId, |
| 80 | + }, |
| 81 | + ], |
43 | 82 | }); |
| 83 | + |
| 84 | + if (!completeUploadResponse.ok) { |
| 85 | + throw new Error(`Error completing upload: ${JSON.stringify(completeUploadResponse)}`); |
| 86 | + } |
| 87 | + |
44 | 88 | $.export("$summary", "Successfully uploaded file"); |
45 | | - return response; |
| 89 | + return completeUploadResponse; |
46 | 90 | }, |
47 | 91 | }; |
0 commit comments