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/ivle.webapp.core/images/mime";
59
type_icons_path_large = "+media/ivle.webapp.core/images/mime/large";
61
/* Mapping SVN status to icons, just the file's basename */
63
"unversioned": "unversioned.png",
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/ivle.webapp.core/images/svn";
92
published_icon = "+media/ivle.webapp.core/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.
137
* \param callback, optional.
138
* A callback function for after the action has been handled.
140
function do_action(action, path, args, content_type, callback)
142
args.action = action;
143
/* Callback action, when the server returns */
144
var callback_inner = function(response)
146
/* Check for action errors reported by the server, and report them
148
var error = response.getResponseHeader("X-IVLE-Action-Error");
149
if (error != null && error != "")
150
/* Note: This header (in particular) comes URI-encoded, to
151
* allow multi-line error messages. Decode */
152
alert("Error: " + decodeURIComponent(error.toString()) + ".");
153
/* Now read the response and set up the page accordingly */
154
if (callback != null)
155
callback(path, response);
157
/* Call the server and perform the action. This mutates the server. */
158
ajax_call(callback_inner, service_app, path, args, "POST", content_type);
161
/** Calls the server using Ajax, requesting a directory listing. This should
162
* not modify the server in any way. Receives the response from the server and
163
* performs a refresh of the page contents, updating it to display the
164
* returned data (such as a directory listing, file preview, or editor pane).
165
* Called "navigate", can also be used for a simple refresh.
166
* Always makes a GET request.
169
function navigate(path)
171
callback = function(response)
173
/* Read the response and set up the page accordingly */
174
handle_response(path, response, false, url.args);
176
/* Get any query strings */
177
url = parse_url(window.location.href);
179
/* Call the server and request the listing. */
180
ajax_call(callback, service_app, path, url.args, "GET");
183
/* Refreshes the current view.
184
* Calls navigate on the current path.
188
if (maybe_save('All changes since the last save will be lost!'))
189
navigate(current_path);
192
/** Determines the "handler type" from a MIME type.
193
* The handler type is a string, either "text", "image", "audio" or "binary".
195
function get_handler_type(content_type)
199
if (content_type in type_handlers)
200
return type_handlers[content_type];
202
{ /* Based on the first part of the MIME type */
203
var handler_type = content_type.split('/')[0];
204
if (handler_type != "text" && handler_type != "image" &&
205
handler_type != "audio")
206
handler_type = "binary";
211
/** Given an HTTP response object, cleans up and rebuilds the contents of the
212
* page using the response data. This does not navigate away from the page, it
213
* merely rebuilds most of the data.
214
* Note that depending on the type of data returned, this could result in a
215
* directory listing, an image preview, an editor pane, etc.
216
* Figures out the type and calls the appropriate function.
217
* \param path URL path which the request was made for. This can (among other
218
* things) be used to update the URL in the location bar.
219
* \param response XMLHttpRequest object returned by the server. Should
220
* contain all the response data.
221
* \param is_action Boolean. True if this is the response to an action, false
222
* if this is the response to a simple listing. This is used in handling the
224
* \param url_args Arguments dict, for the arguments passed to the URL
225
* in the browser's address bar (will be forwarded along).
227
function handle_response(path, response, is_action, url_args)
229
/* TODO: Set location bar to "path" */
232
/* Clear away the existing page contents */
235
/* Check the status, and if not 200, read the error and handle this as an
237
if (response.status != 200)
239
var error = response.getResponseHeader("X-IVLE-Return-Error");
241
error = response.statusText;
247
var top_level_dir = path==username;
250
var req = ajax_call(null, "userservice", "get_enrolments", null, "GET")
251
subjects = decode_response(req);
255
/* This will always return a listing, whether it is a dir or a file.
257
var listing = response.responseText;
258
/* The listing SHOULD be valid JSON text. Parse it into an object. */
261
listing = JSON.parse(listing);
262
file_listing = listing.listing; /* Global */
268
var err = document.createElement("div");
269
var p = dom_make_text_elem("p", "Error: "
270
+ "There was an unexpected server error processing "
271
+ "the selected command.");
273
p = dom_make_text_elem("p", "If the problem persists, please "
274
+ "contact the system administrator.")
276
p = document.createElement("p");
277
var refresh = document.createElement("input");
278
refresh.setAttribute("type", "button");
279
refresh.setAttribute("value", "Back to file view");
280
refresh.setAttribute("onclick", "refresh()");
281
p.appendChild(refresh);
287
var err = document.createElement("div");
288
var p = dom_make_text_elem("p", "Error: "
289
+ "There was an unexpected server error retrieving "
290
+ "the requested file or directory.");
292
p = dom_make_text_elem("p", "If the problem persists, please "
293
+ "contact the system administrator.")
299
/* Get "." out, it's special */
300
current_file = file_listing["."]; /* Global */
301
delete file_listing["."];
303
if ('revision' in listing)
305
current_revision = listing.revision;
308
/* Check if this is a directory listing or file contents */
309
var isdir = response.getResponseHeader("X-IVLE-Return") == "Dir";
313
home_listing(listing, subjects, path);
317
/* Need to make a 2nd ajax call, this time get the actual file
319
callback = function(response)
321
/* Read the response and set up the page accordingly */
322
handle_contents_response(path, response);
324
/* Call the server and request the listing. */
326
args = shallow_clone_object(url_args);
329
/* This time, get the contents of the file, not its metadata */
330
args['return'] = "contents";
331
ajax_call(callback, service_app, path, args, "GET");
333
update_actions(isdir);
336
function handle_contents_response(path, response)
338
/* Treat this as an ordinary file. Get the file type. */
339
var content_type = response.getResponseHeader("Content-Type");
340
var handler_type = get_handler_type(content_type);
341
would_be_handler_type = handler_type;
342
/* handler_type should now be set to either
343
* "text", "image", "audio" or "binary". */
344
switch (handler_type)
347
handle_text(path, response.responseText,
348
would_be_handler_type);
351
/* TODO: Custom image handler */
352
handle_binary(path, response.responseText);
355
/* TODO: Custom audio handler */
356
handle_binary(path, response.responseText);
364
/* Called when a form upload comes back (from an iframe).
365
* Refreshes the page.
367
function upload_callback()
369
/* This has a pretty nasty hack, which happens to work.
370
* upload_callback is set as the "onload" callback for the iframe which
371
* receives the response from the server for uploading a file.
372
* This means it gets called twice. Once when initialising the iframe, and
373
* a second time when the actual response comes back.
374
* All we want to do is call navigate to refresh the page. But we CAN'T do
375
* that on the first load or it will just go into an infinite cycle of
376
* refreshing. We need to refresh the page ONLY on the second refresh.
377
* upload_callback_count is reset to 0 just before the iframe is created.
379
upload_callback_count++;
380
if (upload_callback_count >= 2)
382
myFrame = frames['upload_iframe'].document;
383
/* Browsers will turn the raw returned JSON into an HTML document. We
384
* need to get the <pre> from inside the <body>, and look at its text.
386
data = myFrame.firstChild.getElementsByTagName(
387
'body')[0].firstChild.firstChild.nodeValue;
388
data = JSON.parse(data);
390
alert("Error: " + decodeURIComponent(data['Error']));
391
document.getElementsByName('data')[0].value = '';
396
/** Deletes all "dynamic" content on the page.
397
* This returns the page back to the state it is in when the HTML arrives to
398
* the browser, ready for another handler to populate it.
402
dom_removechildren(document.getElementById("filesbody"));
405
/* Checks if a file needs to be saved. If it does, the user will be asked
406
* if they want to continue anyway. The caller must specify a warning
407
* sentence which indicates the consequences of continuing.
408
* Returns true if we should continue, and false if we should not.
410
function maybe_save(warning)
412
if (warning == null) warning = '';
413
if (current_file.isdir) return true;
414
if (document.getElementById("save_button").disabled) return true;
415
return confirm("This file has unsaved changes. " + warning +
416
"\nAre you sure you wish to continue?");
419
/** Deletes all "dynamic" content on the page necessary to navigate from
420
* one directory listing to another (does not clear as much as clearpage
422
* This is the equivalent of calling clearpage() then
423
* setup_for_dir_listing(), assuming the page is already on a dir listing.
425
function clearpage_dir()
427
dom_removechildren(document.getElementById("path"));
428
dom_removechildren(document.getElementById("files"));
429
dom_removechildren(document.getElementById("sidepanel"));
432
/*** HANDLERS for different types of responses (such as dir listing, file,
436
* message may either be a string, or a DOM node, which will be placed inside
439
function handle_error(message)
441
var files = document.getElementById("filesbody");
443
if (typeof(message) == "string")
445
txt_elem = dom_make_text_elem("div", "Error: "
446
+ message.toString() + ".")
450
/* Assume message is a DOM node */
451
txt_elem = document.createElement("div");
452
txt_elem.appendChild(message);
454
txt_elem.setAttribute("class", "padding error");
455
files.appendChild(txt_elem);
458
/** Given a path, filename and optional revision, returns a URL to open that
459
* revision of that file.
461
function build_revision_url(path, filename, revision)
463
bits = {'path': app_path(this_app, path, filename)};
464
if (current_revision)
466
bits['query_string'] = 'r=' + revision;
468
return build_url(bits);
471
/** Given a mime type, returns the path to the icon.
472
* \param type String, Mime type.
473
* \param sizelarge Boolean, optional.
474
* \return Path to the icon. Has applied make_path, so it is relative to site
477
function mime_type_to_icon(type, sizelarge)
480
if (type in type_icons)
481
filename = type_icons[type];
483
filename = default_type_icon;
485
return make_path(path_join(type_icons_path_large, filename));
487
return make_path(path_join(type_icons_path, filename));
490
/** Given an svnstatus, returns the path to the icon.
491
* \param type String, svn status.
492
* \return Path to the icon. Has applied make_path, so it is relative to site
493
* root. May return null to indicate no SVN icon.
495
function svnstatus_to_icon(svnstatus)
498
if (svnstatus in svn_icons)
499
filename = svn_icons[svnstatus];
501
filename = default_svn_icon;
502
if (filename == null) return null;
503
return make_path(path_join(svn_icons_path, filename));
506
/** Given an svnstatus, returns the "nice" string.
508
function svnstatus_to_string(svnstatus)
510
if (svnstatus in svn_nice)
511
return svn_nice[svnstatus];
513
return default_svn_nice;
516
/** Displays a download link to the binary file.
518
function handle_binary(path)
520
var files = document.getElementById("filesbody");
521
var div = document.createElement("div");
522
files.appendChild(div);
523
div.setAttribute("class", "padding");
524
var download_link = app_path(download_app, path);
525
var par1 = dom_make_text_elem("p",
526
"The file " + path + " is a binary file. To download this file, " +
527
"click the following link:");
528
var par2 = dom_make_link_elem("p",
529
"Download " + path, "Download " + path, download_link);
530
div.appendChild(par1);
531
div.appendChild(par2);
534
/* Enable or disable actions1 moreactions actions. Takes either a single
535
* name, or an array of them.*/
536
function set_action_state(names, which, allow_on_revision)
538
if (!(names instanceof Array)) names = Array(names);
540
for (var i=0; i < names.length; i++)
542
element = document.getElementById('act_' + names[i]);
544
!(current_file.svnstatus == 'revision' && !allow_on_revision))
547
element.setAttribute("class", "choice");
548
element.removeAttribute("disabled");
553
element.setAttribute("class", "disabled");
554
element.setAttribute("disabled", "disabled");
559
/* Updates the list of available actions based on files selected */
560
function update_actions()
563
var numsel = selected_files.length;
564
var svn_selection = false;
568
svn_selection = true;
569
for (var i = 0; i < selected_files.length; i++){
570
if (file_listing[selected_files[i]]["svnstatus"] == "unversioned")
572
svn_selection = false;
581
/* Display information about the current directory instead */
582
filename = path_basename(current_path);
585
else if (numsel == 1)
587
filename = selected_files[0];
588
file = file_listing[filename];
591
/* Update each action node in the topbar.
592
* This includes enabling/disabling actions as appropriate, and
593
* setting href/onclick attributes. */
597
/* Available if exactly one file is selected */
598
var open = document.getElementById("act_open");
601
open.setAttribute("class", "choice");
603
open.setAttribute("title",
604
"Navigate to this directory in the file browser");
606
open.setAttribute("title",
607
"Edit or view this file");
608
open.setAttribute("href", build_revision_url(current_path, filename,
613
open.setAttribute("class", "disabled");
614
open.removeAttribute("title");
615
open.removeAttribute("href");
619
/* Available if zero or one files are selected,
620
* and only if this is a file, not a directory */
621
var serve = document.getElementById("act_serve");
622
if (numsel <= 1 && !file.isdir && current_file.svnstatus != 'revision')
624
serve.setAttribute("class", "choice");
625
serve.setAttribute("onclick",
626
"return maybe_save('The last saved version will be served.')");
628
serve.setAttribute("href",
629
app_path(serve_app, current_path));
631
serve.setAttribute("href",
632
app_path(serve_app, current_path, filename));
636
serve.setAttribute("class", "disabled");
637
serve.removeAttribute("href");
638
serve.removeAttribute("onclick");
642
/* Available if exactly one file is selected,
643
* and it is a Python file.
645
var run = document.getElementById("act_run");
647
if (numsel <= 1 && !file.isdir && file.type == "text/x-python"
648
&& current_file.svnstatus != 'revision')
652
// In the edit window
653
var localpath = path_join('/home', current_path);
657
// In the browser window
658
var localpath = path_join('/home', current_path, filename);
660
run.setAttribute("class", "choice");
661
run.setAttribute("onclick", "runfile('" + localpath + "')");
665
run.setAttribute("class", "disabled");
666
run.removeAttribute("onclick");
670
/* Always available for current files.
671
* If 0 files selected, download the current file or directory as a ZIP.
672
* If 1 directory selected, download it as a ZIP.
673
* If 1 non-directory selected, download it.
674
* If >1 files selected, download them all as a ZIP.
676
var download = document.getElementById("act_download");
677
if (current_file.svnstatus == 'revision')
679
download.setAttribute("class", "disabled");
680
download.removeAttribute("onclick");
682
else if (numsel <= 1)
684
download.setAttribute("class", "choice")
687
download.setAttribute("href",
688
app_path(download_app, current_path));
690
download.setAttribute("title",
691
"Download the current directory as a ZIP file");
693
download.setAttribute("title",
694
"Download the current file");
698
download.setAttribute("href",
699
app_path(download_app, current_path, filename));
701
download.setAttribute("title",
702
"Download the selected directory as a ZIP file");
704
download.setAttribute("title",
705
"Download the selected file");
710
/* Make a query string with all the files to download */
711
var dlpath = urlencode_path(app_path(download_app, current_path)) + "?";
712
for (var i=0; i<numsel; i++)
713
dlpath += "path=" + encodeURIComponent(selected_files[i]) + "&";
714
dlpath = dlpath.substr(0, dlpath.length-1);
715
download.setAttribute("class", "choice")
716
download.setAttribute("href", dlpath);
717
download.setAttribute("title",
718
"Download the selected files as a ZIP file");
721
/* Refresh - No changes required */
723
/* Publish and Submit */
724
/* If this directory is under subversion and selected/unselected file is a
726
var publish = document.getElementById("act_publish");
727
var submit = document.getElementById("act_submit");
728
var pubcond = numsel <= 1 && file.isdir;
731
/* If this dir is already published, call it "Unpublish" */
734
publish.setAttribute("value", "unpublish");
735
publish.setAttribute("title" ,"Make it so this directory "
736
+ "can not be seen by anyone on the web");
737
publish.firstChild.nodeValue = "Unpublish";
739
publish.setAttribute("value", "publish");
740
publish.setAttribute("title","Make it so this directory "
741
+ "can be seen by anyone on the web");
742
publish.firstChild.nodeValue = "Publish";
745
set_action_state(["publish", "submit"], pubcond);
748
/* If exactly 1 non-directory file is selected, and its parent
749
* directory is published.
751
set_action_state("share", numsel == 1 && !file.isdir &&
752
current_file.published);
755
/* If exactly 1 file is selected */
756
set_action_state("rename", numsel == 1);
758
/* Delete, cut, copy */
759
/* If >= 1 file is selected */
760
set_action_state(["delete", "cut", "copy"], numsel >= 1);
762
/* Paste, new file, new directory, upload */
763
/* Disable if the current file is not a directory */
764
set_action_state(["paste", "newfile", "mkdir", "upload"], current_file.isdir);
766
/* Subversion actions */
767
/* These are only useful if we are in a versioned directory and have some
769
set_action_state(["svnadd"], numsel >= 1 && current_file.svnstatus);
770
/* And these are only usefull is ALL the selected files are versioned */
771
set_action_state(["svnremove", "svnrevert", "svncommit", "svncopy",
772
"svncut"], numsel >= 1 && current_file.svnstatus && svn_selection);
774
/* Diff, log and update only support one path at the moment, so we must
775
* have 0 or 1 versioned files selected. If 0, the directory must be
777
single_versioned_path = (
779
(numsel == 1 && (svnst = file_listing[selected_files[0]].svnstatus)) ||
780
(numsel == 0 && (svnst = current_file.svnstatus))
781
) && svnst != "unversioned");
782
set_action_state(["svndiff", "svnupdate"], single_versioned_path);
784
/* We can resolve if we have a file selected and it is conflicted. */
785
set_action_state("svnresolved", single_versioned_path && numsel == 1 && svnst == "conflicted");
787
/* Log should be available for revisions as well. */
788
set_action_state("svnlog", single_versioned_path, true);
790
/* Cleanup should be available for revisions as well. */
791
set_action_state("svncleanup", single_versioned_path, true);
793
single_ivle_versioned_path = (
795
(numsel == 1 && (stat = file_listing[selected_files[0]])) ||
796
(numsel == 0 && (stat = current_file))
797
) && stat.svnstatus != "unversioned"
799
&& stat.svnurl.substr(0, svn_base.length) == svn_base);
800
set_action_state(["submit"], single_ivle_versioned_path);
802
/* There is currently nothing on the More Actions menu of use
803
* when the current file is not a directory. Hence, just remove
805
* (This makes some of the above decisions somewhat redundant).
806
* We also take this opportunity to show the appropriate actions2
807
* bar for this path. It should either be a save or upload widget.
809
if (current_file.isdir)
811
var actions2_directory = document.getElementById("actions2_directory");
812
actions2_directory.setAttribute("style", "display: inline;");
813
var moreactions = document.getElementById("moreactions_area");
814
moreactions.setAttribute("style", "display: inline;");
818
var actions2_file = document.getElementById("actions2_file");
819
actions2_file.setAttribute("style", "display: inline;");
825
/** Event handler for when an item of the "More actions..." dropdown box is
826
* selected. Performs the selected action. */
827
function handle_moreactions()
829
var moreactions = document.getElementById("moreactions");
830
if (moreactions.value == "top")
832
var selectedaction = moreactions.value;
833
/* Reset to "More actions..." */
834
moreactions.selectedIndex = 0;
836
/* If 0 files selected, filename is the name of the current dir.
837
* If 1 file selected, filename is that file.
839
if (selected_files.length == 0)
840
filename = path_basename(current_path);
841
else if (selected_files.length == 1)
842
filename = selected_files[0];
846
/* Now handle the selected action */
847
switch(selectedaction)
850
action_publish(selected_files);
853
action_unpublish(selected_files);
856
window.open(public_app_path("~" + current_path, filename), 'share')
859
if (selected_files.length == 1)
860
stat = file_listing[selected_files[0]];
863
path = stat.svnurl.substr(svn_base.length);
865
/* The working copy might not have an up-to-date version of the
866
* directory. While submitting like this could yield unexpected
867
* results, we should really submit the latest revision to minimise
868
* terrible mistakes - so we run off and ask fileservice for the
870
$.post(app_path(service_app, current_path),
871
{"action": "svnrepostat", "path": path},
874
window.location = path_join(app_path('+submit'), path) + '?revision=' + result.svnrevision;
880
action_rename(filename);
883
action_delete(selected_files);
886
action_copy(selected_files);
889
action_cut(selected_files);
901
show_uploadpanel(true);
904
action_add(selected_files);
907
action_remove(selected_files);
910
action_revert(selected_files);
913
window.location = path_join(app_path('diff'), current_path, selected_files[0] || '');
916
action_update(selected_files);
919
action_resolved(selected_files);
922
action_commit(selected_files);
925
window.location = path_join(app_path('svnlog'), current_path, selected_files[0] || '');
928
action_svncopy(selected_files);
931
action_svncut(selected_files);
934
action_svncleanup(".");
939
/** User clicks "Run" button.
940
* Do an Ajax call and print the test output.
942
function runfile(localpath)
944
if (!maybe_save('The last saved version will be run.')) return false;
946
/* Dump the entire file to the console */
947
var callback = function()
949
console_enter_line("execfile('" + localpath + "')", "block");
951
start_server(callback)
955
23
/** Called when the page loads initially.
957
function browser_init()
25
window.onload = function()
959
/* Navigate (internally) to the path in the URL bar.
960
* This causes the page to be populated with whatever is at that address,
961
* whether it be a directory or a file.
963
var path = get_path();
967
/** Gets the current path of the window */
968
function get_path() {
969
var path = parse_url(window.location.href).path;
970
/* Strip out root_dir + "/files" from the front of the path */
971
var strip = make_path(this_app);
972
if (path.substr(0, strip.length) == strip)
973
path = path.substr(strip.length+1);
976
/* See if this is an edit path */
977
strip = make_path(edit_app);
978
if (path.substr(0, strip.length) == strip)
980
path = path.substr(strip.length+1);
984
if (path.length == 0)
986
/* Navigate to the user's home directory by default */