Detecting Gmail attachment downloads

2019-08-09 02:55发布

Is there a way to detect if a particular file that is being downloaded is a Gmail attachment?
I am looking for a way to write a Greasemonkey script which would help me organize the downloads, based on their download sources, say Gmail email attachments would have a different behavior from other stuff.

So far, I've found out that attachments redirect to https://mail-attachment.googleusercontent.com/attachment/u/0/ , which I guess is not sufficient.

EDIT

Since an add-on would be more powerful than a userscript, I've decided to pursue the Add On idea. However, the problem of detection remains unsolved.

3条回答
Rolldiameter
2楼-- · 2019-08-09 03:38

This is too complicated for just one question; it has at least these major parts:

  1. Do you want to redirect downloads when the user clicks, or automatically download select files? Clarify the question.
  2. Your GM script must identify the appropriate download links, and on which pages, and for which views? For gMail, this is not a trivial task, and the question needs to be clearer. It's worthy of a whole question just on this issue given the variety of views and AJAX involved.
  3. Once identified, the script probably needs to intercept clicks on those links. (Depends on your goal (clarify!) and what the Firefox extension can do.)
  4. Greasemonkey needs to interact with an extension that either intercepts the user-initiated download, or allows for an automatic download. I've detailed the auto-download approach, below.

Once your script has identified the appropriate file URLs and/or links (Open a new question for more help with that, and include pictures of the types of pages and links you want.), it can interface with a Firefox add-on, like the one below, to automatically save those files.


Automatically saving files from Greasemonkey with the help of an additional Add-on:

WARNING: The following is a working proof of concept for education only. It has no security features, and if you use it as-is, for actual surfing, some webpage or script writer or extension writer will use it to completely pwn your computer.

If you use the Add-on builder or SDK to install or "Test" the DANGER. DANGER. DANGER. File download utility,

Then you can use a Greasemonkey script, like this, to automatically save files:

// ==UserScript==
// @name        _Call our File download add-on to trigger a file download.
// @include     https://mail.google.com/mail/*
// @include     https://stackoverflow.com/questions/14440362/*
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant       GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/

var fileURL         = "http://userscripts.org/scripts/source/29222.user.js";
var savePath        = "D:\\temp\\";
var extensionLoaded = false;

window.addEventListener ("ImAlivefromExtension", function (zEvent) {
    console.log ("The test extension appears to be loaded!", zEvent.detail);
    extensionLoaded = true;
} );

window.addEventListener ("ReplyToDownloadRequest", function (zEvent) {
    //var xxxx        = JSON.parse (zEvent.detail);
    console.log ("Extension replied: ", zEvent.detail);
} );

$("body").prepend ('<button id="gmFileDownloadBtn">Click to File download request.</button>');
$("#gmFileDownloadBtn").click ( function () {
    if (extensionLoaded) {

        detailVal   = JSON.stringify (
            {targFileURL: fileURL, targSavePath: savePath}
        );

        var zEvent  = new CustomEvent (
            "SuicidalDownloadRequestToAddOn",
            {"detail": detailVal }
        );
        window.dispatchEvent (zEvent);
    }
    else {
        alert ("The file download extension is not loaded!");
    }
} );


You can test the script on this SO question page.

Note that any other extension, userscript, web page, or plugin can listen to or send spoof events, the only security, so far, is to limit which pages the extension runs on.

For reference, the extension source files are below. The rest is supplied by Firefox's Add-on SDK.

The content script:

var zEvent = new CustomEvent ("ImAlivefromExtension",
    {"detail": "GM, DANGER, DANGER, DANGER, File download utility" }
);
window.dispatchEvent (zEvent)

window.addEventListener ("SuicidalDownloadRequestToAddOn", function (zEvent) {
    console.log ("Extension received download request: ", zEvent.detail);

    //-- Relay request to extension main.js
    self.port.emit ("SuicidalDownloadRequestRelayed", zEvent.detail);

    //-- Reply back to GM, or whoever is pretending to be GM.
    var zEvent = new CustomEvent ("ReplyToDownloadRequest",
        {"detail": "Your funeral!" }
    );
    window.dispatchEvent (zEvent)
} );


The background JS:

//--- For security, MAKE THESE AS RESTRICTIVE AS POSSIBLE!
const includePattern = [
    'https://mail.google.com/mail/*',
    'https://stackoverflow.com/questions/14440362/*'
];

let {Cc, Cu, Ci}    = require ("chrome");

Cu.import ("resource://gre/modules/Services.jsm");
Cu.import ("resource://gre/modules/XPCOMUtils.jsm");
Cu.import ("resource://gre/modules/FileUtils.jsm");

let data            = require ("sdk/self").data;
let pageMod         = require ('sdk/page-mod');
let dlManageWindow  = Cc['@mozilla.org/download-manager-ui;1'].getService (Ci.nsIDownloadManagerUI);
let fileURL         = "";
let savePath        = "";
let activeWindow    = Services.wm.getMostRecentWindow ("navigator:browser");

let mod             = pageMod.PageMod ( {
    include:            includePattern,
    contentScriptWhen:  'end',
    contentScriptFile:  [ data.url ('ContentScript.js') ],
    onAttach:           function (worker) {
        console.log ('DANGER download utility attached to: ' + worker.tab.url);

        worker.port.on ('SuicidalDownloadRequestRelayed', function (message) {
            var detailVal   = JSON.parse (message);
            fileURL         = detailVal.targFileURL;
            savePath        = detailVal.targSavePath;

            console.log ("Received request to \ndownload: ", fileURL, "\nto:", savePath);

            downloadFile (fileURL, savePath);
        } );
    }
} );


function downloadFile (fileURL, savePath) {
    dlManageWindow.show (activeWindow, 1);

    try {
        let newFile;
        let fileURIToDownload   = Services.io.newURI (fileURL, null, null);
        let persistWin          = Cc['@mozilla.org/embedding/browser/nsWebBrowserPersist;1']
                                .createInstance (Ci.nsIWebBrowserPersist);
        let fileName            = fileURIToDownload.path.slice (fileURIToDownload.path.lastIndexOf ('/') + 1);
        let fileObj             = new FileUtils.File (savePath);

        fileObj.append (fileName);

        if (fileObj.exists ()) {
            console.error ('*** Error! File "' + fileName + '" already exists!');
        }
        else {
            let newFile         = Services.io.newFileURI (fileObj);
            let newDownload     = Services.downloads.addDownload (
                0, fileURIToDownload, newFile, fileName, null, null, null, persistWin, false
            );

            persistWin.progressListener = newDownload;
            persistWin.savePrivacyAwareURI (fileURIToDownload, null, null, null, "", newFile, false);
        }
    } catch (exception) {
        console.error ("Error saving the file! ", exception);
        dump (exception);
    }
}
查看更多
Fickle 薄情
3楼-- · 2019-08-09 03:40

You could use Gmail contextual gadgets to modify the behavior on the Google side:

Gmail Contexual Gadgets

Contextual Gadgets don't have direct access to attachments but server side, you could use IMAP to access the attachment (based on the Gmail message ID identified by the gadget):

Gmail IMAP Extensions

Using gadgets and server-side IMAP has the advantage of being browser-agnostic.

It's not entirely clear what you want to do differently with the downloaded Gmail attachment as opposed to any given download (save it to a different location? Perform actions upon the attachment data?) But the contextual gadget and IMAP should give you some chance to modify the attachment data as needed before the browser download begins.

查看更多
时光不老,我们不散
4楼-- · 2019-08-09 03:57

So far from what you are saying,the only thing you can do is making add-on(Firefox) and Extension(for chrome if you want).

If you have closer look at download of attachment,it happens when:

1) You click on icon of attachments

2) If you click download

For these two things you can find the click event of <a> tag containing download_url value.You can easily do that using js/jquery for creting extension.

So you can write the functionality when user tries to download attachment.

查看更多
登录 后发表回答