author Santo Pfingsten
 *  see https import { settings } from "../../lib/settings" ; import { browser , Downloads , BrowsingData } from "webextension-polyfill-ts" ; import { Cleaner } from "./cleaner" ; import { getValidHostname } from "../../shared" ; import { TabWatcher } from "../tabWatcher" ; export class DownloadCleaner extends Cleaner { private readonly tabWatcher : TabWatcher ; public constructor ( tabWatcher ) { super ( ) ; this . tabWatcher = tabWatcher ; browser . downloads . onCreated . addListener ( this . onCreated . bind ( this ) ) ; } private onCreated ( { url , incognito } ) { const domain = getValidHostname ( url ) ; if ( domain ) { if ( settings . get ( "instantly.enabled" ) && settings . get ( "instantly.downloads" ) ) { const applyRules = settings . get ( "instantly.downloads.applyRules" ) ; if ( ! applyRules || settings . isDomainBlocked ( domain ) ) { this . cleanupUrl ( url ) ; return ; } } if ( ! incognito && settings . get ( "startup.enabled" ) && settings . get ( "startup.downloads" ) && ! settings . isDomainProtected ( domain , false ) ) { const downloadsToClean = { ... settings . get ( "downloadsToClean" ) } ; downloadsToClean [ url ] = true ; settings . set ( "downloadsToClean" , downloadsToClean ) ; settings . save ( ) ; } } } private cleanupUrl ( url ) { browser . downloads . erase ( { url } ) ; browser . history && browser . history . deleteUrl ( { url } ) ; } public clean ( typeSet , startup ) { const applyRules = settings . get ( startup ? "startup.downloads.applyRules" : "cleanAll.downloads.applyRules" ) ; if ( typeSet . downloads && ( applyRules || ! typeSet . history ) ) { typeSet . downloads = false ; browser . downloads . search ( { } ) . then ( ( downloads ) => { const protectOpenDomains = startup || settings . get ( "cleanAll.protectOpenDomains" ) ; const urlsToClean = this . getUrlsToClean ( downloads , startup , protectOpenDomains , applyRules ) ; urlsToClean . forEach ( this . cleanupUrl . bind ( this ) ) ; } ) ; } } private isDomainProtected ( domain , ignoreStartupType , protectOpenDomains ) { if ( protectOpenDomains && this . tabWatcher . containsDomain ( domain ) ) return true ; return settings . isDomainProtected ( domain , ignoreStartupType ) ; } private getUrlsToClean ( downloads , startup , protectOpenDomains , applyRules ) { const downloadsToClean = { ... settings . get ( "downloadsToClean" ) } ; downloads . forEach ( ( d ) => downloadsToClean [ d . url ] = true ) ; const newDownloadsToClean = { } ; let urls = Object . getOwnPropertyNames ( downloadsToClean ) ; if ( applyRules ) { urls = urls . filter ( ( url ) => { const isProtected = this . isDomainProtected ( getValidHostname ( url ) , startup , protectOpenDomains ) ; if ( isProtected ) newDownloadsToClean [ url ] = true ; return ! isProtected ; } ) ; } settings . set ( "downloadsToClean" , newDownloadsToClean ) ; settings . save ( ) ; return urls ; } }