michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: "use strict"; michael@0: michael@0: const { Cc, Ci } = require("chrome"); michael@0: michael@0: const system = require("sdk/system"); michael@0: const file = require("sdk/io/file"); michael@0: const unload = require("sdk/system/unload"); michael@0: michael@0: // Retrieve the path to the OS temporary directory: michael@0: const tmpDir = require("sdk/system").pathFor("TmpD"); michael@0: michael@0: // List of all tmp file created michael@0: let files = []; michael@0: michael@0: // Remove all tmp files on addon disabling michael@0: unload.when(function () { michael@0: files.forEach(function (path){ michael@0: // Catch exception in order to avoid leaking following files michael@0: try { michael@0: if (file.exists(path)) michael@0: file.remove(path); michael@0: } michael@0: catch(e) { michael@0: console.exception(e); michael@0: } michael@0: }); michael@0: }); michael@0: michael@0: // Utility function that synchronously reads local resource from the given michael@0: // `uri` and returns content string. Read in binary mode. michael@0: function readBinaryURI(uri) { michael@0: let ioservice = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); michael@0: let channel = ioservice.newChannel(uri, "UTF-8", null); michael@0: let stream = Cc["@mozilla.org/binaryinputstream;1"]. michael@0: createInstance(Ci.nsIBinaryInputStream); michael@0: stream.setInputStream(channel.open()); michael@0: michael@0: let data = ""; michael@0: while (true) { michael@0: let available = stream.available(); michael@0: if (available <= 0) michael@0: break; michael@0: data += stream.readBytes(available); michael@0: } michael@0: stream.close(); michael@0: michael@0: return data; michael@0: } michael@0: michael@0: // Create a temporary file from a given string and returns its path michael@0: exports.createFromString = function createFromString(data, tmpName) { michael@0: let filename = (tmpName ? tmpName : "tmp-file") + "-" + (new Date().getTime()); michael@0: let path = file.join(tmpDir, filename); michael@0: michael@0: let tmpFile = file.open(path, "wb"); michael@0: tmpFile.write(data); michael@0: tmpFile.close(); michael@0: michael@0: // Register tmp file path michael@0: files.push(path); michael@0: michael@0: return path; michael@0: } michael@0: michael@0: // Create a temporary file from a given URL and returns its path michael@0: exports.createFromURL = function createFromURL(url, tmpName) { michael@0: let data = readBinaryURI(url); michael@0: return exports.createFromString(data, tmpName); michael@0: } michael@0: