1
/* IVLE - Informatics Virtual Learning Environment
2
* Copyright (C) 2007-2008 The University of Melbourne
4
* This program is free software; you can redistribute it and/or modify
5
* it under the terms of the GNU General Public License as published by
6
* the Free Software Foundation; either version 2 of the License, or
7
* (at your option) any later version.
9
* This program is distributed in the hope that it will be useful,
10
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
* GNU General Public License for more details.
14
* You should have received a copy of the GNU General Public License
15
* along with this program; if not, write to the Free Software
16
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
* Module: File Browser (client)
23
/* Url names for apps */
26
service_app = "fileservice";
28
download_app = "download";
30
/* Mapping MIME types onto handlers.
31
* "text" : When navigating to a text file, the text editor is opened.
32
* "image" : When navigating to an image, the image is displayed (rather than
33
* going to the text editor).
34
* "audio" : When navigating to an audio file, a "play" button is presented.
35
* "binary" : When navigating to a binary file, offer it as a download through
38
* If a file is not on the list, its default action is determined by the first
39
* part of its content type, where "text/*", "image/*" and "audio/*" are
40
* treated as above, and other types are simply treated as binary.
43
"application/x-javascript" : "text",
44
"application/javascript" : "text",
45
"application/json" : "text",
46
"application/xml" : "text"
49
/* Mapping MIME types to icons, just the file's basename */
51
"text/directory": "dir.png",
52
"text/x-python": "py.png"
55
default_type_icon = "txt.png";
57
/* Relative to IVLE root */
58
type_icons_path = "media/images/mime";
59
type_icons_path_large = "media/images/mime/large";
61
/* Mapping SVN status to icons, just the file's basename */
64
"normal": "normal.png",
66
"missing": "missing.png",
67
"deleted": "deleted.png",
68
"modified": "modified.png",
69
"conflicted": "conflicted.png",
70
"revision": "revision.png"
73
/* Mapping SVN status to "nice" strings */
75
"unversioned": "Temporary file",
76
"normal": "Permanent file",
77
"added": "Temporary file (scheduled to be added)",
78
"missing": "Permanent file (missing)",
79
"deleted": "Permanent file (scheduled for deletion)",
80
"replaced": "Permanent file (replaced)",
81
"modified": "Permanent file (modified)",
82
"merged": "Permanent file (merged)",
83
"conflicted": "Permanent file (conflicted)",
84
"revision": "Past Permanent file (revision)"
87
default_svn_icon = null;
88
default_svn_nice = "Unknown status";
90
svn_icons_path = "media/images/svn";
92
published_icon = "media/images/interface/published.png";
94
/* List of MIME types considered "executable" by the system.
95
* Executable files offer a "run" link, implying that the "serve"
96
* application can interpret them.
103
/* Global variables */
105
/** The listing object returned by the server as JSON */
108
current_revision = null;
111
/** Filenames of all files selected
112
* (Only used by dir listings, but still needs to be [] for files, so that
113
* update_actions knows that nothing is selected).
117
upload_callback_count = 0; /* See upload_callback */
119
/** Calls the server using Ajax, performing an action on the server side.
120
* Receives the response from the server and performs a refresh of the page
121
* contents, updating it to display the returned data (such as a directory
122
* listing, file preview, or editor pane).
123
* Always makes a POST request.
126
* \param action String. Name of the action to perform, as defined in the
128
* \param path URL path to make the request to, within the application.
129
* \param args Argument object, as described in util.parse_url and friends.
130
* This should contain the arguments to the action, but NOT the action
131
* itself. (Also a minor side-effect; the "args" object will be mutated
132
* to include the action attribute).
133
* \param content_type String, optional.
134
* May be "application/x-www-form-urlencoded" or "multipart/form-data".
135
* Defaults to "application/x-www-form-urlencoded".
136
* "multipart/form-data" is recommended for large uploads.
138
function do_action(action, path, args, content_type, ignore_response)
140
args.action = action;
141
/* Callback action, when the server returns */
142
var callback = function(response)
144
/* Check for action errors reported by the server, and report them
146
var error = response.getResponseHeader("X-IVLE-Action-Error");
148
/* Note: This header (in particular) comes URI-encoded, to
149
* allow multi-line error messages. Decode */
150
alert("Error: " + decodeURIComponent(error.toString()) + ".");
151
/* Now read the response and set up the page accordingly */
152
if (ignore_response != true)
153
handle_response(path, response, true);
155
/* Call the server and perform the action. This mutates the server. */
156
ajax_call(callback, service_app, path, args, "POST", content_type);
159
/** Calls the server using Ajax, requesting a directory listing. This should
160
* not modify the server in any way. Receives the response from the server and
161
* performs a refresh of the page contents, updating it to display the
162
* returned data (such as a directory listing, file preview, or editor pane).
163
* Called "navigate", can also be used for a simple refresh.
164
* Always makes a GET request.
167
function navigate(path)
169
callback = function(response)
171
/* Read the response and set up the page accordingly */
172
handle_response(path, response, false, url.args);
174
/* Get any query strings */
175
url = parse_url(window.location.href);
177
/* Call the server and request the listing. */
178
ajax_call(callback, service_app, path, url.args, "GET");
181
/* Refreshes the current view.
182
* Calls navigate on the current path.
186
if (maybe_save('All changes since the last save will be lost!'))
187
navigate(current_path);
190
/** Determines the "handler type" from a MIME type.
191
* The handler type is a string, either "text", "image", "audio" or "binary".
193
function get_handler_type(content_type)
197
if (content_type in type_handlers)
198
return type_handlers[content_type];
200
{ /* Based on the first part of the MIME type */
201
var handler_type = content_type.split('/')[0];
202
if (handler_type != "text" && handler_type != "image" &&
203
handler_type != "audio")
204
handler_type = "binary";
209
/** Given an HTTP response object, cleans up and rebuilds the contents of the
210
* page using the response data. This does not navigate away from the page, it
211
* merely rebuilds most of the data.
212
* Note that depending on the type of data returned, this could result in a
213
* directory listing, an image preview, an editor pane, etc.
214
* Figures out the type and calls the appropriate function.
215
* \param path URL path which the request was made for. This can (among other
216
* things) be used to update the URL in the location bar.
217
* \param response XMLHttpRequest object returned by the server. Should
218
* contain all the response data.
219
* \param is_action Boolean. True if this is the response to an action, false
220
* if this is the response to a simple listing. This is used in handling the
222
* \param url_args Arguments dict, for the arguments passed to the URL
223
* in the browser's address bar (will be forwarded along).
225
function handle_response(path, response, is_action, url_args)
227
/* TODO: Set location bar to "path" */
230
/* Clear away the existing page contents */
233
/* Check the status, and if not 200, read the error and handle this as an
235
if (response.status != 200)
237
var error = response.getResponseHeader("X-IVLE-Return-Error");
239
error = response.statusText;
244
/* This will always return a listing, whether it is a dir or a file.
246
var listing = response.responseText;
247
/* The listing SHOULD be valid JSON text. Parse it into an object. */
250
listing = JSON.parse(listing);
251
file_listing = listing.listing; /* Global */
257
var err = document.createElement("div");
258
var p = dom_make_text_elem("p", "Error: "
259
+ "There was an unexpected server error processing "
260
+ "the selected command.");
262
p = dom_make_text_elem("p", "If the problem persists, please "
263
+ "contact the system administrator.")
265
p = document.createElement("p");
266
var refresh = document.createElement("input");
267
refresh.setAttribute("type", "button");
268
refresh.setAttribute("value", "Back to file view");
269
refresh.setAttribute("onclick", "refresh()");
270
p.appendChild(refresh);
276
var err = document.createElement("div");
277
var p = dom_make_text_elem("p", "Error: "
278
+ "There was an unexpected server error retrieving "
279
+ "the requested file or directory.");
281
p = dom_make_text_elem("p", "If the problem persists, please "
282
+ "contact the system administrator.")
288
/* Get "." out, it's special */
289
current_file = file_listing["."]; /* Global */
290
delete file_listing["."];
292
if ('revision' in listing)
294
current_revision = listing.revision;
297
/* Check if this is a directory listing or file contents */
298
var isdir = response.getResponseHeader("X-IVLE-Return") == "Dir";
301
handle_dir_listing(path, listing);
305
/* Need to make a 2nd ajax call, this time get the actual file
307
callback = function(response)
309
/* Read the response and set up the page accordingly */
310
handle_contents_response(path, response);
312
/* Call the server and request the listing. */
314
args = shallow_clone_object(url_args);
317
/* This time, get the contents of the file, not its metadata */
318
args['return'] = "contents";
319
ajax_call(callback, service_app, path, args, "GET");
321
update_actions(isdir);
324
function handle_contents_response(path, response)
326
/* Treat this as an ordinary file. Get the file type. */
327
var content_type = response.getResponseHeader("Content-Type");
328
var handler_type = get_handler_type(content_type);
329
would_be_handler_type = handler_type;
330
/* handler_type should now be set to either
331
* "text", "image", "audio" or "binary". */
332
switch (handler_type)
335
handle_text(path, response.responseText,
336
would_be_handler_type);
339
/* TODO: Custom image handler */
340
handle_binary(path, response.responseText);
343
/* TODO: Custom audio handler */
344
handle_binary(path, response.responseText);
352
/* Called when a form upload comes back (from an iframe).
353
* Refreshes the page.
355
function upload_callback()
357
/* This has a pretty nasty hack, which happens to work.
358
* upload_callback is set as the "onload" callback for the iframe which
359
* receives the response from the server for uploading a file.
360
* This means it gets called twice. Once when initialising the iframe, and
361
* a second time when the actual response comes back.
362
* All we want to do is call navigate to refresh the page. But we CAN'T do
363
* that on the first load or it will just go into an infinite cycle of
364
* refreshing. We need to refresh the page ONLY on the second refresh.
365
* upload_callback_count is reset to 0 just before the iframe is created.
367
upload_callback_count++;
368
if (upload_callback_count >= 2)
370
document.getElementsByName('data')[0].value = '';
375
/** Deletes all "dynamic" content on the page.
376
* This returns the page back to the state it is in when the HTML arrives to
377
* the browser, ready for another handler to populate it.
381
dom_removechildren(document.getElementById("filesbody"));
384
/* Checks if a file needs to be saved. If it does, the user will be asked
385
* if they want to continue anyway. The caller must specify a warning
386
* sentence which indicates the consequences of continuing.
387
* Returns true if we should continue, and false if we should not.
389
function maybe_save(warning)
391
if (warning == null) warning = '';
392
if (current_file.isdir) return true;
393
if (document.getElementById("save_button").disabled) return true;
394
return confirm("This file has unsaved changes. " + warning +
395
"\nAre you sure you wish to continue?");
398
/** Deletes all "dynamic" content on the page necessary to navigate from
399
* one directory listing to another (does not clear as much as clearpage
401
* This is the equivalent of calling clearpage() then
402
* setup_for_dir_listing(), assuming the page is already on a dir listing.
404
function clearpage_dir()
406
dom_removechildren(document.getElementById("path"));
407
dom_removechildren(document.getElementById("files"));
408
dom_removechildren(document.getElementById("sidepanel"));
411
/*** HANDLERS for different types of responses (such as dir listing, file,
415
* message may either be a string, or a DOM node, which will be placed inside
418
function handle_error(message)
420
var files = document.getElementById("filesbody");
422
if (typeof(message) == "string")
424
txt_elem = dom_make_text_elem("div", "Error: "
425
+ message.toString() + ".")
429
/* Assume message is a DOM node */
430
txt_elem = document.createElement("div");
431
txt_elem.appendChild(message);
433
txt_elem.setAttribute("class", "padding error");
434
files.appendChild(txt_elem);
437
/** Given a path, filename and optional revision, returns a URL to open that
438
* revision of that file.
440
function build_revision_url(path, filename, revision)
442
bits = {'path': app_path(this_app, path, filename)};
443
if (current_revision)
445
bits['query_string'] = 'r=' + revision;
447
return build_url(bits);
450
/** Given a mime type, returns the path to the icon.
451
* \param type String, Mime type.
452
* \param sizelarge Boolean, optional.
453
* \return Path to the icon. Has applied make_path, so it is relative to site
456
function mime_type_to_icon(type, sizelarge)
459
if (type in type_icons)
460
filename = type_icons[type];
462
filename = default_type_icon;
464
return make_path(path_join(type_icons_path_large, filename));
466
return make_path(path_join(type_icons_path, filename));
469
/** Given an svnstatus, returns the path to the icon.
470
* \param type String, svn status.
471
* \return Path to the icon. Has applied make_path, so it is relative to site
472
* root. May return null to indicate no SVN icon.
474
function svnstatus_to_icon(svnstatus)
477
if (svnstatus in svn_icons)
478
filename = svn_icons[svnstatus];
480
filename = default_svn_icon;
481
if (filename == null) return null;
482
return make_path(path_join(svn_icons_path, filename));
485
/** Given an svnstatus, returns the "nice" string.
487
function svnstatus_to_string(svnstatus)
489
if (svnstatus in svn_nice)
490
return svn_nice[svnstatus];
492
return default_svn_nice;
495
/** Displays a download link to the binary file.
497
function handle_binary(path)
499
var files = document.getElementById("filesbody");
500
var div = document.createElement("div");
501
files.appendChild(div);
502
div.setAttribute("class", "padding");
503
var download_link = app_path(download_app, path);
504
var par1 = dom_make_text_elem("p",
505
"The file " + path + " is a binary file. To download this file, " +
506
"click the following link:");
507
var par2 = dom_make_link_elem("p",
508
"Download " + path, "Download " + path, download_link);
509
div.appendChild(par1);
510
div.appendChild(par2);
513
/* Enable or disable actions1 moreactions actions. Takes either a single
514
* name, or an array of them.*/
515
function set_action_state(names, which, allow_on_revision)
517
if (!(names instanceof Array)) names = Array(names);
519
for (var i=0; i < names.length; i++)
521
element = document.getElementById('act_' + names[i]);
523
!(current_file.svnstatus == 'revision' && !allow_on_revision))
526
element.setAttribute("class", "choice");
527
element.removeAttribute("disabled");
532
element.setAttribute("class", "disabled");
533
element.setAttribute("disabled", "disabled");
538
function update_actions()
541
var numsel = selected_files.length;
546
/* Display information about the current directory instead */
547
filename = path_basename(current_path);
550
else if (numsel == 1)
552
filename = selected_files[0];
553
file = file_listing[filename];
556
/* Update each action node in the topbar.
557
* This includes enabling/disabling actions as appropriate, and
558
* setting href/onclick attributes. */
562
/* Available if exactly one file is selected */
563
var open = document.getElementById("act_open");
566
open.setAttribute("class", "choice");
568
open.setAttribute("title",
569
"Navigate to this directory in the file browser");
571
open.setAttribute("title",
572
"Edit or view this file");
573
open.setAttribute("href", build_revision_url(current_path, filename,
578
open.setAttribute("class", "disabled");
579
open.removeAttribute("title");
580
open.removeAttribute("href");
584
/* Available if zero or one files are selected,
585
* and only if this is a file, not a directory */
586
var serve = document.getElementById("act_serve");
587
if (numsel <= 1 && !file.isdir && current_file.svnstatus != 'revision')
589
serve.setAttribute("class", "choice");
590
serve.setAttribute("onclick",
591
"return maybe_save('The last saved version will be served.')");
593
serve.setAttribute("href",
594
app_path(serve_app, current_path));
596
serve.setAttribute("href",
597
app_path(serve_app, current_path, filename));
601
serve.setAttribute("class", "disabled");
602
serve.removeAttribute("href");
603
serve.removeAttribute("onclick");
607
/* Available if exactly one file is selected,
608
* and it is a Python file.
610
var run = document.getElementById("act_run");
612
if (!file.isdir && file.type == "text/x-python" && numsel <= 1
613
&& current_file.svnstatus != 'revision')
617
// In the edit window
618
var localpath = path_join('/home', current_path);
622
// In the browser window
623
var localpath = path_join('/home', current_path, filename);
625
run.setAttribute("class", "choice");
626
run.setAttribute("onclick", "runfile('" + localpath + "')");
630
run.setAttribute("class", "disabled");
631
run.removeAttribute("onclick");
635
/* Always available for current files.
636
* If 0 files selected, download the current file or directory as a ZIP.
637
* If 1 directory selected, download it as a ZIP.
638
* If 1 non-directory selected, download it.
639
* If >1 files selected, download them all as a ZIP.
641
var download = document.getElementById("act_download");
642
if (current_file.svnstatus == 'revision')
644
download.setAttribute("class", "disabled");
645
download.removeAttribute("onclick");
647
else if (numsel <= 1)
649
download.setAttribute("class", "choice")
652
download.setAttribute("href",
653
app_path(download_app, current_path));
655
download.setAttribute("title",
656
"Download the current directory as a ZIP file");
658
download.setAttribute("title",
659
"Download the current file");
663
download.setAttribute("href",
664
app_path(download_app, current_path, filename));
666
download.setAttribute("title",
667
"Download the selected directory as a ZIP file");
669
download.setAttribute("title",
670
"Download the selected file");
675
/* Make a query string with all the files to download */
676
var dlpath = urlencode_path(app_path(download_app, current_path)) + "?";
677
for (var i=0; i<numsel; i++)
678
dlpath += "path=" + encodeURIComponent(selected_files[i]) + "&";
679
dlpath = dlpath.substr(0, dlpath.length-1);
680
download.setAttribute("class", "choice")
681
download.setAttribute("href", dlpath);
682
download.setAttribute("title",
683
"Download the selected files as a ZIP file");
686
/* Refresh - No changes required */
688
/* Publish and Submit */
689
/* If this directory is under subversion and selected/unselected file is a
691
var publish = document.getElementById("act_publish");
692
var submit = document.getElementById("act_submit");
693
var pubcond = numsel <= 1 && file.isdir;
696
/* TODO: Work out of file is svn'd */
697
/* If this dir is already published, call it "Unpublish" */
700
publish.setAttribute("value", "unpublish");
701
publish.setAttribute("title" ,"Make it so this directory "
702
+ "can not be seen by anyone on the web");
703
publish.textContent = "Unpublish";
705
publish.setAttribute("value", "publish");
706
publish.setAttribute("title","Make it so this directory "
707
+ "can be seen by anyone on the web");
708
publish.textContent = "Publish";
711
set_action_state(["publish", "submit"], pubcond);
714
/* If exactly 1 non-directory file is selected, and its parent
715
* directory is published.
717
set_action_state("share", numsel == 1 && !file.isdir &&
718
current_file.published);
721
/* If exactly 1 file is selected */
722
set_action_state("rename", numsel == 1);
724
/* Delete, cut, copy */
725
/* If >= 1 file is selected */
726
set_action_state(["delete", "cut", "copy"], numsel >= 1);
728
/* Paste, new file, new directory, upload */
729
/* Disable if the current file is not a directory */
730
set_action_state(["paste", "newfile", "mkdir", "upload"], current_file.isdir);
732
/* Subversion actions */
733
/* These are only useful if we are in a versioned directory and have some
735
set_action_state(["svnadd", "svnremove", "svnrevert", "svncommit"], numsel >= 1 && current_file.svnstatus);
737
/* Diff, log and update only support one path at the moment, so we must
738
* have 0 or 1 versioned files selected. If 0, the directory must be
740
single_versioned_path = (
742
(numsel == 1 && (svnst = file_listing[selected_files[0]].svnstatus)) ||
743
(numsel == 0 && (svnst = current_file.svnstatus))
744
) && svnst != "unversioned");
745
set_action_state(["svndiff", "svnupdate"], single_versioned_path);
747
/* We can resolve if we have a file selected and it is conflicted. */
748
set_action_state("svnresolved", single_versioned_path && numsel == 1 && svnst == "conflicted");
750
/* Log should be available for revisions as well. */
751
set_action_state("svnlog", single_versioned_path, true);
753
/* current_path == username: We are at the top level */
754
set_action_state("svncheckout", current_path == username);
756
/* There is currently nothing on the More Actions menu of use
757
* when the current file is not a directory. Hence, just remove
759
* (This makes some of the above decisions somewhat redundant).
760
* We also take this opportunity to show the appropriate actions2
761
* bar for this path. It should either be a save or upload widget.
763
if (current_file.isdir)
765
var actions2_directory = document.getElementById("actions2_directory");
766
actions2_directory.setAttribute("style", "display: inline;");
767
var moreactions = document.getElementById("moreactions_area");
768
moreactions.setAttribute("style", "display: inline;");
772
var actions2_file = document.getElementById("actions2_file");
773
actions2_file.setAttribute("style", "display: inline;");
779
/** Event handler for when an item of the "More actions..." dropdown box is
780
* selected. Performs the selected action. */
781
function handle_moreactions()
783
var moreactions = document.getElementById("moreactions");
784
if (moreactions.value == "top")
786
var selectedaction = moreactions.value;
787
/* Reset to "More actions..." */
788
moreactions.selectedIndex = 0;
790
/* If 0 files selected, filename is the name of the current dir.
791
* If 1 file selected, filename is that file.
793
if (selected_files.length == 0)
794
filename = path_basename(current_path);
795
else if (selected_files.length == 1)
796
filename = selected_files[0];
800
/* Now handle the selected action */
801
switch(selectedaction)
804
action_publish(selected_files);
807
action_unpublish(selected_files);
810
//alert("Not yet implemented: Sharing files");
811
window.open(public_app_path(serve_app, current_path, filename), 'share')
815
alert("Not yet implemented: Submit");
818
action_rename(filename);
821
action_delete(selected_files);
824
action_copy(selected_files);
827
action_cut(selected_files);
839
show_uploadpanel(true);
842
action_add(selected_files);
845
action_remove(selected_files);
848
action_revert(selected_files);
851
window.location = path_join(app_path('diff'), current_path, selected_files[0] || '');
854
action_update(selected_files);
857
action_resolved(selected_files);
860
action_commit(selected_files);
863
window.location = path_join(app_path('svnlog'), current_path, selected_files[0] || '');
871
/** User clicks "Run" button.
872
* Do an Ajax call and print the test output.
874
function runfile(localpath)
876
if (!maybe_save('The last saved version will be run.')) return false;
878
/* Dump the entire file to the console */
879
var callback = function()
881
console_enter_line("execfile('" + localpath + "')", "block");
883
start_server(callback)
887
/** Called when the page loads initially.
889
function browser_init()
891
/* Navigate (internally) to the path in the URL bar.
892
* This causes the page to be populated with whatever is at that address,
893
* whether it be a directory or a file.
895
var path = parse_url(window.location.href).path;
896
/* Strip out root_dir + "/files" from the front of the path */
897
var strip = make_path(this_app);
898
if (path.substr(0, strip.length) == strip)
899
path = path.substr(strip.length+1);
902
/* See if this is an edit path */
903
strip = make_path(edit_app);
904
if (path.substr(0, strip.length) == strip)
906
path = path.substr(strip.length+1);
910
if (path.length == 0)
912
/* Navigate to the user's home directory by default */