检测Gmail附件下载 [英] Detecting Gmail attachment downloads

查看:222
本文介绍了检测Gmail附件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法来检测一个正在下载的特定文件是否是一个Gmail附件?

我正在寻找一种方法来编写一个Greasemonkey脚本来帮助我组织下载,基于他们的下载来源,说Gmail的电子邮件附件会有不同的行为,从其他的东西。

到目前为止,我发现附件重定向到 https://mail-attachment.googleusercontent.com/attachment/u/0 / b
$ b $编辑



由于插件比用户脚本更强大,所以我决定继续添加附件。但是,检测问题仍未解决。

解决方案

对于一个问题,这太复杂了;它至少有这些主要部分:


  1. 当用户点击或者自动下载选择文件时,是否要重定向下载? 澄清问题。

  2. 您的GM脚本必须标识适当的下载链接,以及哪些页面和哪些视图? gMail,这不是一件小事,而且问题需要更清楚。考虑到各种视图和AJAX,这个问题值得一个完整的问题。
  3. 一旦确定,脚本可能需要拦截点击这些链接。 (取决于你的目标(澄清!)和Firefox扩展可以做什么)。
  4. Greasemonkey需要与一个扩展截然不同,这个扩展拦截用户启动的下载,或者允许自动下载。我详细介绍了下面的自动下载方法。

一旦脚本识别出合适的文件URL和/一个新的问题有更多的帮助,包括你想要的页面和链接的类型的图片),它可以与一个Firefox插件接口,如下所示,以自动保存这些文件。






通过附加的附加功能自动从Greasemonkey保存文件:

警告:以下是仅用于教育的工作概念证明。它没有安全功能,如果你使用它,为了实际浏览,一些网页或者脚本编写器或者扩展编写器用它来完全打开你的电脑。



如果使用附加组件构建器或SDK来安装或测试 危险。危险。危险。文件下载工具

然后,您可以使用像这样的Greasemonkey脚本来自动保存文件:

  // == UserScript == 
// @name _Call我们的文件下载插件触发文件下载。
// @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 ==
/ * - 需要@grant指令来解决GM 1.0中引入的设计更改
。它恢复沙箱。
* /

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

window.addEventListener(ImAlivefromExtension,function(zEvent){
console.log(测试扩展似乎被加载!,zEvent.detail);
extensionLoaded = true;
});

window.addEventListener(ReplyToDownloadRequest,function(zEvent){
// var xxxx = JSON.parse(zEvent.detail);
console.log(Extension extension :,zEvent.detail);
});
$ b $(body)。prepend('< button id =gmFileDownloadBtn> Click to File download request。< / button>');点击(function(){
if(extensionLoaded){

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

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



您可以在这是SO问题页面



请注意,任何其他扩展,用户脚本,网页或插件可以听到或发送欺骗事件,到目前为止唯一的安全性是限制扩展运行的页面。



作为参考,扩展源文件如下。其余由Firefox的附加SDK提供。



内容脚本

  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 );

// - 对扩展的中继请求main.js
self.port.emit(SuicidalDownloadRequestRelayed,zEvent.detail);

// - 回复通用汽车公司或任何冒充通用汽车的人。
var zEvent = new CustomEvent(ReplyToDownloadRequest,
{detail:Your funeral!)
);
window.dispatchEvent(zEvent)
});





背景JS:

  // ---为了安全起见,尽可能限制! 
const includePattern = [
'https://mail.google.com/mail/*',
'https://stackoverflow.com/questions/14440362/*'
];

让{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;
让pageMod = require('sdk / page-mod');
let dlManageWindow = Cc ['@ mozilla.org/download-manager-ui;1'].getService(Ci.nsIDownloadManagerUI);
让fileURL =;
let savePath =;
让activeWindow = Services.wm.getMostRecentWindow(navigator:browser);
$ b $ let mod = pageMod.PageMod({
include:includePattern,
contentScriptWhen:'end',
contentScriptFile:[data.url('ContentScript.js' )],
onAttach:function(worker){
console.log('DANGER下载实用程序附加到:'+ worker.tab.url);

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

console.log(接收请求到\\\下载:,fileURL,\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ;
}
});

$ b函数downloadFile(fileURL,savePath){
dlManageWindow.show(activeWindow,1);

尝试{
let newFile;
让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);
让fileObj = new FileUtils.File(savePath);

fileObj.append(fileName);
$ b $ 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 save the file!,exception);
dump(例外);
}
}


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.

解决方案

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);
    }
}

这篇关于检测Gmail附件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆