1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5const THUMBNAIL_DIRECTORY = "thumbnails";
6
7const { XPCOMUtils } = ChromeUtils.import(
8  "resource://gre/modules/XPCOMUtils.jsm"
9);
10const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm");
11
12XPCOMUtils.defineLazyGetter(this, "gCryptoHash", function() {
13  return Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
14});
15
16XPCOMUtils.defineLazyGetter(this, "gUnicodeConverter", function() {
17  let converter = Cc[
18    "@mozilla.org/intl/scriptableunicodeconverter"
19  ].createInstance(Ci.nsIScriptableUnicodeConverter);
20  converter.charset = "utf8";
21  return converter;
22});
23function PageThumbsStorageService() {}
24
25PageThumbsStorageService.prototype = {
26  classID: Components.ID("{97943eec-0e48-49ef-b7b7-cf4aa0109bb6}"),
27  QueryInterface: ChromeUtils.generateQI(["nsIPageThumbsStorageService"]),
28  // The path for the storage
29  _path: null,
30  get path() {
31    if (!this._path) {
32      this._path = OS.Path.join(
33        OS.Constants.Path.localProfileDir,
34        THUMBNAIL_DIRECTORY
35      );
36    }
37    return this._path;
38  },
39
40  getLeafNameForURL(aURL) {
41    if (typeof aURL != "string") {
42      throw new TypeError("Expecting a string");
43    }
44    let hash = this._calculateMD5Hash(aURL);
45    return hash + ".png";
46  },
47
48  getFilePathForURL(aURL) {
49    return OS.Path.join(this.path, this.getLeafNameForURL(aURL));
50  },
51
52  _calculateMD5Hash(aValue) {
53    let hash = gCryptoHash;
54    let value = gUnicodeConverter.convertToByteArray(aValue);
55
56    hash.init(hash.MD5);
57    hash.update(value, value.length);
58    return this._convertToHexString(hash.finish(false));
59  },
60
61  _convertToHexString(aData) {
62    let hex = "";
63    for (let i = 0; i < aData.length; i++) {
64      hex += ("0" + aData.charCodeAt(i).toString(16)).slice(-2);
65    }
66    return hex;
67  },
68};
69
70var EXPORTED_SYMBOLS = ["PageThumbsStorageService"];
71