save_uri: optionally use a temporary download file
[conkeror.git] / modules / save.js
blob9ed4794fd40f42de9f01af367fc0b74f19cf74c2
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007 John J. Foerch
4  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
5  *
6  * Use, modification, and distribution are subject to the terms specified in the
7  * COPYING file.
8 **/
10 require("content-buffer.js");
11 require("load-spec.js");
12 require("suggest-file-name.js");
14 /* buffer is used only to associate with the download */
15 define_keywords("$use_cache", "$buffer", "$prepare_download", "$temp_file");
16 function save_uri(lspec, output_file) {
17     keywords(arguments, $use_cache = true);
19     var use_cache = arguments.$use_cache;
21     var buffer = arguments.$buffer;
23     var prepare_download = arguments.$prepare_download;
25     var download_file = output_file;
27     var temp_file = arguments.$temp_file;
28     if (temp_file === true) {
29         temp_file = Cc["@mozilla.org/file/local;1"]
30             .createInstance(Ci.nsILocalFile);
31         temp_file.initWithFile(output_file);
32         temp_file.leafName = "temp";
33         temp_file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0666);
34     }
35     if (temp_file)
36         download_file = temp_file;
38     var cache_key = null;
39     var uri = load_spec_uri(lspec);
40     var referrer_uri = load_spec_referrer(lspec);
41     var post_data = load_spec_post_data(lspec);
42     if (use_cache)
43         cache_key = load_spec_cache_key(lspec);
45     var file_uri = make_uri(download_file);
47     var persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
48         .createInstance(Ci.nsIWebBrowserPersist);
50     persist.persistFlags =
51         Ci.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES |
52         Ci.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION |
53         Ci.nsIWebBrowserPersist.PERSIST_FLAGS_CLEANUP_ON_FAILURE;
55     if (use_cache)
56         persist.persistFlags |= Ci.nsIWebBrowserPersist.PERSIST_FLAGS_FROM_CACHE;
57     else
58         persist.persistFlags |= Ci.nsIWebBrowserPersist.PERSIST_FLAGS_BYPASS_CACHE;
60     var info = register_download(buffer, uri, download_file);
61     if (temp_file) {
62         // We want this hook so that we run before the download buffer updates.
63         add_hook.call(info, "download_state_change_hook", function() {
64             if (info.state == DOWNLOAD_FINISHED) {
65                 temp_file.moveTo(null, output_file.leafName);
66                 info.target_file.leafName = output_file.leafName;
67             }
68         });
69     }
70     if (prepare_download)
71         prepare_download(info);
73     var tr = Cc["@mozilla.org/transfer;1"].createInstance(Ci.nsITransfer);
74     tr.init(uri, file_uri, output_file.leafName,
75             load_spec_mime_info(lspec),
76             null /* start time */,
77             null /* temp file */,
78             persist);
79     persist.progressListener = tr;
80     persist.saveURI(uri, cache_key, referrer_uri, post_data, null /* no extra headers */, file_uri);
82     return info;
86 // We have no DOM, and can only save the URL as is.
87 const SAVEMODE_FILEONLY      = 0x00;
88 // We have a DOM and can save as complete.
89 const SAVEMODE_COMPLETE_DOM  = 0x01;
90 // We have a DOM which we can serialize as text.
91 const SAVEMODE_COMPLETE_TEXT = 0x02;
93 function get_save_mode_from_content_type(content_type) {
94     var mode = SAVEMODE_FILEONLY;
95     switch (content_type) {
96     case "text/html":
97     case "application/xhtml+xml":
98         mode |= SAVEMODE_COMPLETE_TEXT;
99         // Fall through
100     case "text/xml":
101     case "application/xml":
102         mode |= SAVEMODE_COMPLETE_DOM;
103         break;
104     }
105     return mode;
108 define_keywords("$use_cache", "$buffer", "$wrap_column", "$prepare_download");
109 function save_document_as_text(document, output_file)
111     keywords(arguments, $use_cache = true, $wrap_column = 80);
113     var mode = get_save_mode_from_content_type(document.contentType);
114     if (!(mode & SAVEMODE_COMPLETE_TEXT))
115         throw interactive_error("Document cannot be saved as text.");
117     var use_cache = arguments.$use_cache;
119     var prepare_download = arguments.$prepare_download;
121     var buffer = arguments.$buffer;
123     var uri = document.documentURIObject;
125     var file_uri = make_uri(output_file);
127     var persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
128         .createInstance(Ci.nsIWebBrowserPersist);
130     persist.persistFlags =
131         Ci.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES |
132         Ci.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION |
133         Ci.nsIWebBrowserPersist.PERSIST_FLAGS_CLEANUP_ON_FAILURE;
135     var encoding_flags =
136         Ci.nsIWebBrowserPersist.ENCODE_FLAGS_FORMATTED |
137         Ci.nsIWebBrowserPersist.ENCODE_FLAGS_ABSOLUTE_LINKS |
138         Ci.nsIWebBrowserPersist.ENCODE_FLAGS_NOFRAMES_CONTENT;
141     if (use_cache)
142         persist.persistFlags |= Ci.nsIWebBrowserPersist.PERSIST_FLAGS_FROM_CACHE;
143     else
144         persist.persistFlags |= Ci.nsIWebBrowserPersist.PERSIST_FLAGS_BYPASS_CACHE;
148     var info = register_download(buffer, uri);
149     if (prepare_download)
150         prepare_download(info);
152     var tr = Cc["@mozilla.org/transfer;1"].createInstance(Ci.nsITransfer);
153     tr.init(uri, file_uri, output_file.leafName,
154             mime_info_from_mime_type("text/plain"),
155             null /* start time */,
156             null /* temp file */,
157             persist);
158     persist.progressListener = tr;
159     persist.saveDocument(document, file_uri, null /* data path */,
160                          "text/plain", encoding_flags,
161                          arguments.$wrap_column);
162     return info;
165 define_keywords("$use_cache", "$buffer", "$prepare_download");
166 function save_document_complete(document, output_file, output_dir) {
167     keywords(arguments);
169     var mime_type = document.contentType;
171     var mode = get_save_mode_from_content_type(mime_type);
172     if (!(mode & SAVEMODE_COMPLETE_DOM))
173         throw interactive_error("Complete document cannot be saved.");
175     var use_cache = arguments.$use_cache;
177     var buffer = arguments.$buffer;
179     var prepare_download = arguments.$prepare_download;
181     var uri = document.documentURIObject;
183     var file_uri = make_uri(output_file);
185     var persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
186         .createInstance(Ci.nsIWebBrowserPersist);
188     persist.persistFlags =
189         Ci.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES |
190         Ci.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION |
191         Ci.nsIWebBrowserPersist.PERSIST_FLAGS_CLEANUP_ON_FAILURE;
193     var encoding_flags =
194         Ci.nsIWebBrowserPersist.ENCODE_FLAGS_BASIC_ENTITIES;
196     if (use_cache)
197         persist.persistFlags |= Ci.nsIWebBrowserPersist.PERSIST_FLAGS_FROM_CACHE;
198     else
199         persist.persistFlags |= Ci.nsIWebBrowserPersist.PERSIST_FLAGS_BYPASS_CACHE;
202     var info = register_download(buffer, uri);
203     if (prepare_download)
204         prepare_download(info);
206     var tr = Cc["@mozilla.org/transfer;1"].createInstance(Ci.nsITransfer);
207     tr.init(uri, file_uri, output_file.leafName,
208             mime_info_from_mime_type(mime_type),
209             null /* start time */,
210             null /* temp file */,
211             persist);
212     persist.progressListener = tr;
213     persist.saveDocument(document, file_uri, output_dir /* data path */,
214                          mime_type, encoding_flags,
215                          0);
216     return info;
219 function download_failed_error() {
220     var e = new Error("Download failed");
221     e.__proto__ = download_failed_error.prototype;
222     return e;
224 download_failed_error.prototype.__proto__ = Error.prototype;
226 /* Returns an array of two elements: the first element is the
227  * nsILocalFile object, the second element is a boolean indicating
228  * whether the file is temporary and should be deleted when the caller is
229  * done with it.
230  */
231 define_keywords("$action", "$shell_command", "$shell_command_cwd", "$buffer", "$use_cache");
232 function download_as_temporary(lspec) {
233     keywords(arguments, $use_cache = true);
235     var action_description = arguments.$action;
236     var shell_command = arguments.$shell_command;
237     var shell_command_cwd = arguments.$shell_command_cwd;
239     var uri = load_spec_uri(lspec);
240     // If it is local file, there is no need to download it
241     if (uri.scheme == "file")
242     {
243         let file = uri.QueryInterface(Ci.nsIFileURL).file;
245         yield co_return([file, false /* not temporary */]);
246     }
249     var file = get_temporary_file(suggest_file_name(lspec));
251     var cc = yield CONTINUATION;
253     function handle_state_change(info) {
254         var state = info.state;
255         switch (state) {
256         case DOWNLOAD_CANCELED:
257         case DOWNLOAD_FAILED:
258             info.remove(); // ensure that the download cannot be retried later
259             try {
260                 // Delete the temporary file
261                 file.remove(false /*non-recursive*/);
262             } catch (e) {}
263             cc.throw(download_failed_error());
264             break;
265         case DOWNLOAD_FINISHED:
266             cc([file, true /* temporary */]);
267             break;
268         }
269     }
271     save_uri(lspec, file,
272              $use_cache = arguments.$use_cache,
273              $buffer = arguments.$buffer,
274              $prepare_download = function (info) {
275                  if (action_description != null) {
276                      info.action_description = action_description;
277                      info.temporary_status = DOWNLOAD_TEMPORARY_FOR_ACTION;
278                  } else if (shell_command != null) {
279                      info.set_shell_command(shell_command, shell_command_cwd);
280                      info.temporary_status = DOWNLOAD_TEMPORARY_FOR_COMMAND;
281                  }
282                  add_hook.call(info, "download_state_change_hook", handle_state_change);
283              });
285     var result = yield SUSPEND;
286     yield co_return(result);