Untitled

mail@pastecode.io avatar
unknown
plain_text
14 days ago
2.3 kB
5
Indexable
Never
async function downloadMessageFromUrl(messageUrl) {
  try {
    // Fetch the message content from the URL
    const response = await fetch(messageUrl);
    if (!response.ok) {
      throw new Error(`Failed to fetch message: ${response.statusText}`);
    }
    const messageContent = await response.text();

    // Save the content temporarily using a download
    const blob = new Blob([messageContent], { type: 'message/rfc822' });
    const url = URL.createObjectURL(blob);
    browser.tabs.create({
      url: url
    });

    const filename = `message-${Date.now()}.eml`;

    // Trigger a download
    browser.downloads.download({
      url: url,
      filename: filename,
      conflictAction: 'overwrite',
      saveAs: true
    }, (downloadId) => {
      browser.downloads.onChanged.addListener(function listener(downloadDelta) {
        if (downloadDelta.id === downloadId && downloadDelta.state && downloadDelta.state.current === 'complete') {
          browser.downloads.onChanged.removeListener(listener);
          // Notify user that the download is complete and message is ready
          browser.notifications.create({
            "type": "basic",
            "title": "Message Downloaded",
            "message": `The message has been downloaded as ${filename}. You can now open it.`,
            "iconUrl": "icons/icon48.png"
          });
          //browser.downloads.open(downloadId); user input handler?
          browser.downloads.search({
            "id": downloadId
          }).then((downloadItem) => {
            const f = new File([blob], downloadItem[0].filename, { type: 'text/plain' });
            //messenger.messageDisplay.open({
            browser.messageDisplay.open({
              "file": f
              //"messageId": "a1b025a9-4fa0-42d8-9ad7-5a3888574b3f@nvidia.com11"
            }).catch(e => {
              console.log(e);
            });
          });
        }
      });
    });
  } catch (error) {
    console.error("Error downloading message:", error);
  }
}

// Listen for messages from the popup or other parts of the extension
browser.runtime.onMessage.addListener((message) => {
  if (message.action === 'downloadMessage') {
    downloadMessageFromUrl(message.messageUrl);
  }
});
Leave a Comment