1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-09-03 07:55:36 +00:00

[view_file,view_shared_file,edit_file]:directly get file_content instead of ajax get

This commit is contained in:
llj
2012-08-09 15:28:22 +08:00
parent cfca229770
commit c19df2eece
6 changed files with 93 additions and 123 deletions

View File

@@ -21,10 +21,10 @@
</div> </div>
<div id="file-view"> <div id="file-view">
<p>文件内容读取中...</p> <div id="docu-view" class="vh"></div>
</div> </div>
<form action="post" method="post" id="file-edit-form" class="hide"> <form action="" method="post" id="file-edit-form" class="hide">
<input type="hidden" name="modified-file" /> <input type="hidden" name="modified-file" />
<input type="submit" class="submit" value="提交" /> <input type="submit" class="submit" value="提交" />
</form> </form>
@@ -38,34 +38,26 @@
<script type="text/javascript" src="{{MEDIA_URL}}ace/mode-markdown.js"></script> <script type="text/javascript" src="{{MEDIA_URL}}ace/mode-markdown.js"></script>
{% endif %} {% endif %}
<script type="text/javascript"> <script type="text/javascript">
var url = "{{ SITE_ROOT }}repo/{{ repo.id }}/file/get/?p={{ path|urlencode }}&t={{ token }}&u={{ request.user.username }}"; {% if file_content %}
$.ajax({ editor = ace.edit("docu-view");
url: url, $('#docu-view').removeClass('vh');
dataType: 'json', editor.setShowPrintMargin(false); // rm the vertical line in the center
cache: false, editor.renderer.scrollBar.element.style.display = "none"; // hide right scrollbar
success: function(data) { editor.renderer.scrollBar.width = 0; // enlarge ace_content width
$('#file-view').html('<div id="docu-view" class="vh">' + '</div>'); editor.setTheme("ace/theme/twilight");
editor = ace.edit("docu-view"); {% include "snippets/editor_set_mode.html" %}
$('#docu-view').removeClass('vh'); editor.session.getDocument().setValue('{{ file_content|escapejs }}');
editor.setShowPrintMargin(false); // rm the vertical line in the center $('#docu-view').css({'position': 'relative', 'height': (editor.session.getScreenLength() + 1) * parseInt($('#docu-view').css('line-height'))}); // '+ 1': offer space for bottom scrollbar
editor.renderer.scrollBar.element.style.display = "none"; // hide right scrollbar editor.session.setScrollLeft(0); // make bottom scrollbar start from the left-most
editor.renderer.scrollBar.width = 0; // enlarge ace_content width editor.resize(); // fix some problem for showing some file in ie8
editor.setTheme("ace/theme/twilight"); $('#file-edit-form').removeClass('hide');
{% include "snippets/editor_set_mode.html" %}
editor.session.getDocument().setValue(data['content']);
$('#docu-view').css({'position': 'relative', 'height': (editor.session.getScreenLength() + 1) * parseInt($('#docu-view').css('line-height'))}); // '+ 1': offer space for bottom scrollbar
editor.session.setScrollLeft(0); // make bottom scrollbar start from the left-most
editor.resize(); // fix some problem for showing some file in ie8
$('#file-edit-form').removeClass('hide');
},
error: function(xhr, ajaxOptions, thrownError) {
var jsonVal = jQuery.parseJSON(xhr.responseText);
$('#file-view').html('<p class="error">' + jsonVal['error'] + '</p>');
}
});
$('#file-edit-form').submit(function() { $('#file-edit-form').submit(function() {
$(this).find('[name="modified-file"]').val(editor.session.getValue()); $(this).find('[name="modified-file"]').val(editor.session.getValue());
}); });
{% endif %}
{% if err %}
$('#file-view').html('<p class="error">{{ err }}</p>');
{% endif %}
</script> </script>
{% endblock %} {% endblock %}

View File

@@ -89,14 +89,7 @@
{% block extra_script %} {% block extra_script %}
{% include "snippets/file_view_js.html" %} {% include "snippets/file_view_js.html" %}
<script type="text/javascript"> <script type="text/javascript">
{% if view_history %}
var url = "{{ SITE_ROOT }}repo/{{ repo.id }}/file/get/?obj_id={{ obj_id }}&p={{ path|urlencode }}&t={{ token }}&u={{ request.user.username }}";
{% else %}
var url = "{{ SITE_ROOT }}repo/{{ repo.id }}/file/get/?p={{ path|urlencode }}&t={{ token }}&u={{ request.user.username }}";
{% endif %}
{% include "snippets/repo_file_get.html" %} {% include "snippets/repo_file_get.html" %}
{% if not view_history %} {% if not view_history %}
function showLink() { function showLink() {
$('#get-shared-link').addClass('hide'); $('#get-shared-link').addClass('hide');

View File

@@ -1,41 +1,39 @@
{% if filetype == 'Text' %} {% if filetype == 'Text' %}
$.ajax({ {% if file_content %}
url: url, $('#file-view').html('<div id="docu-view" class="vh">' + '</div>');
dataType: 'json', var editor = ace.edit("docu-view");
cache: false, $('#docu-view').removeClass('vh');
success: function(data) { editor.setReadOnly(true);
$('#file-view').html('<div id="docu-view" class="vh">' + '</div>'); editor.setHighlightActiveLine(false);
var editor = ace.edit("docu-view"); $('#docu-view .ace_cursor-layer').hide(); // rm cursor
$('#docu-view').removeClass('vh'); editor.setShowPrintMargin(false); // rm the vertical line in the center
editor.setReadOnly(true); editor.renderer.scrollBar.element.style.display = "none"; // hide right scrollbar
editor.setHighlightActiveLine(false); editor.renderer.scrollBar.width = 0; // enlarge ace_content width
$('#docu-view .ace_cursor-layer').hide(); // rm cursor editor.setTheme("ace/theme/chrome");
editor.setShowPrintMargin(false); // rm the vertical line in the center {% include "snippets/editor_set_mode.html" %}
editor.renderer.scrollBar.element.style.display = "none"; // hide right scrollbar editor.session.getDocument().setValue('{{ file_content|escapejs }}');
editor.renderer.scrollBar.width = 0; // enlarge ace_content width $('#docu-view').css({'position': 'relative', 'height': (editor.session.getScreenLength() + 1) * parseInt($('#docu-view').css('line-height'))}); // '+ 1': offer space for bottom scrollbar
editor.setTheme("ace/theme/chrome"); editor.session.setScrollLeft(0); // make bottom scrollbar start from the left-most
{% include "snippets/editor_set_mode.html" %} editor.resize(); // fix some problem for showing some file in ie8
editor.session.getDocument().setValue(data['content']); {% endif %}
$('#docu-view').css({'position': 'relative', 'height': (editor.session.getScreenLength() + 1) * parseInt($('#docu-view').css('line-height'))}); // '+ 1': offer space for bottom scrollbar
editor.session.setScrollLeft(0); // make bottom scrollbar start from the left-most {% if err %}
editor.resize(); // fix some problem for showing some file in ie8 $('#file-view').html('<p class="error">{{ err }}</p>');
}, {% endif %}
error: function(xhr, ajaxOptions, thrownError) {
var jsonVal = jQuery.parseJSON(xhr.responseText);
$('#file-view').html('<p class="error">' + jsonVal['error'] + '</p>');
}
});
{% endif %} {% endif %}
{% if filetype == 'Image' %} {% if filetype == 'Image' %}
$('#file-view').html('<img src="{{ raw_path }}" alt="{{ u_filename}}" id="image-view" />').css({'text-align':'center', 'padding':'30px 0'}); $('#file-view').html('<img src="{{ raw_path }}" alt="{{ u_filename}}" id="image-view" />').css({'text-align':'center', 'padding':'30px 0'});
{% endif %} {% endif %}
{% if filetype == 'SVG' %} {% if filetype == 'SVG' %}
if (!$.browser.mozilla && !$.browser.safari && !($.browser.msie && parseInt($.browser.version) > 8)) { if (!$.browser.mozilla && !$.browser.safari && !($.browser.msie && parseInt($.browser.version) > 8)) {
$('#file-view').html('<p>在线查看请使用firefox, chrome 或 IE 9。</p>'); $('#file-view').html('<p>在线查看请使用firefox, chrome 或 IE 9。</p>');
} else { } else {
$('#file-view').html('<div><iframe src="{{ raw_path }}" frameborder="0" id="svg-view"></iframe></div>'); $('#file-view').html('<div><iframe src="{{ raw_path }}" frameborder="0" id="svg-view"></iframe></div>');
} }
{% endif %} {% endif %}
{% if filetype == 'Document' %} {% if filetype == 'Document' %}
var uuid = '', var uuid = '',
obj_id = ''; obj_id = '';
@@ -104,6 +102,7 @@ if (!$.browser.mozilla && !$.browser.safari) {
}); });
} }
{% endif %} {% endif %}
{% if filetype == 'PDF' %} {% if filetype == 'PDF' %}
if (!$.browser.mozilla && !$.browser.safari) { if (!$.browser.mozilla && !$.browser.safari) {
$('#file-view').html('<p>在线查看请使用firefox 或 chrome。</p>'); $('#file-view').html('<p>在线查看请使用firefox 或 chrome。</p>');
@@ -158,18 +157,19 @@ if (!$.browser.mozilla && !$.browser.safari) {
}); });
} }
{% endif %} {% endif %}
{% if filetype == 'Markdown' %} {% if filetype == 'Markdown' %}
$.ajax({ {% if file_content %}
url: url, var converter = new Showdown.converter();
dataType: 'json', $('#file-view').html('<div id="md-view">' + converter.makeHtml('{{ file_content|escapejs }}') + '</div>');
cache: false, $('#md-view').children(':first').css('margin-top', '0');
success: function(data) { {% endif %}
var converter = new Showdown.converter();
$('#file-view').html('<div id="md-view">' + converter.makeHtml(data['content']) + '</div>'); {% if err %}
$('#md-view').children(':first').css('margin-top', '0'); $('#file-view').html('<p class="error">{{ err }}</p>');
} {% endif %}
});
{% endif %} {% endif %}
{% if filetype == 'Unknown' %} {% if filetype == 'Unknown' %}
$('#file-view').html('<p>该类型文件无法在线查看。<a href="{{ SITE_ROOT }}repo/{{ repo.id }}/{{ obj_id }}/?file_name={{ file_name }}&op=download">下载</a></p>'); $('#file-view').html('<p>该类型文件无法在线查看。<a href="{{ SITE_ROOT }}repo/{{ repo.id }}/{{ obj_id }}/?file_name={{ file_name }}&op=download">下载</a></p>');
{% endif %} {% endif %}

View File

@@ -18,7 +18,6 @@
{% block extra_script %} {% block extra_script %}
{% include "snippets/file_view_js.html" %} {% include "snippets/file_view_js.html" %}
<script type="text/javascript"> <script type="text/javascript">
var url = '{{ SITE_ROOT }}repo/{{ repo.id }}/file/get/?t={{ access_token }}&p={{ path|urlencode }}&u={{ username }}';
{% include "snippets/repo_file_get.html" %} {% include "snippets/repo_file_get.html" %}
</script> </script>
{% endblock %} {% endblock %}

View File

@@ -5,7 +5,7 @@ from django.views.generic.simple import direct_to_template
from seahub.views import root, myhome, \ from seahub.views import root, myhome, \
repo, repo_history, modify_token, remove_repo, sys_seafadmin, sys_useradmin, \ repo, repo_history, modify_token, remove_repo, sys_seafadmin, sys_useradmin, \
activate_user, user_add, user_remove, sys_group_admin, sys_org_admin, \ activate_user, user_add, user_remove, sys_group_admin, sys_org_admin, \
ownerhome, repo_history_revert, repo_file_get, repo_file_edit, org_remove, \ ownerhome, repo_history_revert, repo_file_edit, org_remove, \
user_info, repo_set_access_property, repo_access_file, \ user_info, repo_set_access_property, repo_access_file, \
repo_remove_share, repo_download, org_info, repo_view_file, pdf_full_view, \ repo_remove_share, repo_download, org_info, repo_view_file, pdf_full_view, \
seafile_access_check, repo_history_changes, \ seafile_access_check, repo_history_changes, \
@@ -67,7 +67,6 @@ urlpatterns = patterns('',
# (r'^repo/removefetched/(?P<user_id>[^/]+)/(?P<repo_id>[^/]+)/$', remove_fetched_repo), # (r'^repo/removefetched/(?P<user_id>[^/]+)/(?P<repo_id>[^/]+)/$', remove_fetched_repo),
# (r'^repo/setap/(?P<repo_id>[^/]+)/$', repo_set_access_property), # (r'^repo/setap/(?P<repo_id>[^/]+)/$', repo_set_access_property),
url(r'^repo/(?P<repo_id>[^/]+)/files/$', repo_view_file, name="repo_view_file"), url(r'^repo/(?P<repo_id>[^/]+)/files/$', repo_view_file, name="repo_view_file"),
(r'^repo/(?P<repo_id>[^/]+)/file/get/$', repo_file_get),
(r'^repo/(?P<repo_id>[^/]+)/file/edit/$', repo_file_edit), (r'^repo/(?P<repo_id>[^/]+)/file/edit/$', repo_file_edit),
(r'^pdf_full_view/$', pdf_full_view), (r'^pdf_full_view/$', pdf_full_view),
url(r'^repo/(?P<repo_id>[^/]+)/(?P<obj_id>[^/]+)/$', repo_access_file, name='repo_access_file'), url(r'^repo/(?P<repo_id>[^/]+)/(?P<obj_id>[^/]+)/$', repo_access_file, name='repo_access_file'),

View File

@@ -798,6 +798,12 @@ def repo_view_file(request, repo_id):
# raw path # raw path
raw_path = gen_file_get_url(token, filename) raw_path = gen_file_get_url(token, filename)
# get file content
err = ''
file_content = ''
if filetype == 'Text' or filetype == 'Markdown':
err, file_content = repo_file_get(raw_path)
# file share link # file share link
l = FileShare.objects.filter(repo_id=repo_id).filter(\ l = FileShare.objects.filter(repo_id=repo_id).filter(\
@@ -834,63 +840,31 @@ def repo_view_file(request, repo_id):
'domain': domain, 'domain': domain,
'file_shared_link': file_shared_link, 'file_shared_link': file_shared_link,
'contacts': contacts, 'contacts': contacts,
'err': err,
'file_content': file_content,
}, context_instance=RequestContext(request)) }, context_instance=RequestContext(request))
def repo_file_get(request, repo_id): def repo_file_get(raw_path):
""" err = ''
Handle ajax request to get file content from httpserver. file_content = ''
If get current worktree file, need access_token, path and username from
url params.
If get history file, need access_token, path username and obj_id from
url params.
"""
if not request.is_ajax():
return Http404
# http_server_root = get_httpserver_root()
content_type = 'application/json; charset=utf-8'
access_token = request.GET.get('t')
path = request.GET.get('p', '/')
if path[-1] == '/':
path = path[:-1]
filename = urllib2.quote(os.path.basename(path).encode('utf-8'))
obj_id = request.GET.get('obj_id', '')
if not obj_id:
try:
obj_id = seafserv_threaded_rpc.get_file_by_path(repo_id, path)
except:
obj_id = None
if not obj_id:
data = json.dumps({'error': '获取文件数据失败'})
return HttpResponse(data, status=400, content_type=content_type)
# username = request.GET.get('u', '')
redirect_url = gen_file_get_url(access_token, filename)
try: try:
proxied_request = urllib2.urlopen(redirect_url) file_response = urllib2.urlopen(raw_path)
if long(proxied_request.headers['Content-Length']) > FILE_PREVIEW_MAX_SIZE: if long(file_response.headers['Content-Length']) > FILE_PREVIEW_MAX_SIZE:
data = json.dumps({'error': '文件超过10M无法在线查看。'}) err = '文件超过10M无法在线查看。'
return HttpResponse(data, status=400, content_type=content_type)
else: else:
content = proxied_request.read() content = file_response.read()
except urllib2.HTTPError, e: except urllib2.HTTPError, e:
err = 'HTTPError: 无法在线打开该文件' err = 'HTTPError: 无法在线打开该文件'
data = json.dumps({'error': err})
return HttpResponse(data, status=400, content_type=content_type)
except urllib2.URLError as e: except urllib2.URLError as e:
err = 'URLError: 无法在线打开该文件' err = 'URLError: 无法在线打开该文件'
data = json.dumps({'error': err})
return HttpResponse(data, status=400, content_type=content_type)
else: else:
try: try:
u_content = content.decode('utf-8') u_content = content.decode('utf-8')
except: except:
# XXX: file in windows is encoded in gbk # XXX: file in windows is encoded in gbk
u_content = content.decode('gbk') u_content = content.decode('gbk')
from django.utils.html import escape file_content = u_content
data = json.dumps({'content': u_content}) return err, file_content
return HttpResponse(data, status=200, content_type=content_type)
def pdf_full_view(request): def pdf_full_view(request):
@@ -942,13 +916,18 @@ def repo_file_edit(request, repo_id):
filetype, fileext = valid_previewed_file(filename) filetype, fileext = valid_previewed_file(filename)
# get file content
raw_path = gen_file_get_url(token, filename)
err, file_content = repo_file_get(raw_path)
return render_to_response('repo_edit_file.html', { return render_to_response('repo_edit_file.html', {
'repo':repo, 'repo':repo,
'u_filename':u_filename, 'u_filename':u_filename,
'path':path, 'path':path,
'zipped':zipped, 'zipped':zipped,
'token':token,
'fileext':fileext, 'fileext':fileext,
'err':err,
'file_content':file_content,
}, context_instance=RequestContext(request)) }, context_instance=RequestContext(request))
@@ -1751,6 +1730,12 @@ def view_shared_file(request, token):
# Raw path # Raw path
raw_path = gen_file_get_url(access_token, quote_filename) raw_path = gen_file_get_url(access_token, quote_filename)
# get file content
err = ''
file_content = ''
if filetype == 'Text' or filetype == 'Markdown':
err, file_content = repo_file_get(raw_path)
# Increase file shared link view_cnt, this operation should be atomic # Increase file shared link view_cnt, this operation should be atomic
fileshare = FileShare.objects.get(token=token) fileshare = FileShare.objects.get(token=token)
@@ -1768,6 +1753,8 @@ def view_shared_file(request, token):
'fileext': fileext, 'fileext': fileext,
'raw_path': raw_path, 'raw_path': raw_path,
'username': username, 'username': username,
'err': err,
'file_content': file_content,
}, context_instance=RequestContext(request)) }, context_instance=RequestContext(request))
@login_required @login_required