1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-09-12 13:24:52 +00:00

Move file edit from views/__init__.py to views/file.py

This commit is contained in:
zhengxie
2013-03-28 14:17:28 +08:00
parent 9e40a98d4e
commit 56c779b3b3
3 changed files with 155 additions and 385 deletions

View File

@@ -4,7 +4,7 @@ from django.views.generic.simple import direct_to_template
from seahub.views import * from seahub.views import *
from seahub.views.file import view_file, view_history_file, view_trash_file,\ from seahub.views.file import view_file, view_history_file, view_trash_file,\
view_snapshot_file view_snapshot_file, file_edit
from seahub.search import search from seahub.search import search
from notifications.views import notification_list from notifications.views import notification_list
from group.views import group_list from group.views import group_list

View File

@@ -1265,231 +1265,6 @@ def repo_del_file(request, repo_id):
url = reverse('repo', args=[repo_id]) + ('?p=%s' % urllib2.quote(parent_dir.encode('utf-8'))) url = reverse('repo', args=[repo_id]) + ('?p=%s' % urllib2.quote(parent_dir.encode('utf-8')))
return HttpResponseRedirect(url) return HttpResponseRedirect(url)
# @ctx_switch_required
# def repo_view_file(request, repo_id):
# """
# Preview file on web, including files in current worktree and history.
# """
# repo = get_repo(repo_id)
# if not repo:
# raise Http404
# http_server_root = get_httpserver_root()
# path = request.GET.get('p', '/')
# u_filename = os.path.basename(path)
# filename = urllib2.quote(u_filename.encode('utf-8'))
# comment_open = request.GET.get('comment_open', '')
# page_from = request.GET.get('from', '')
# # enc option a user chose
# file_enc = request.GET.get('file_enc', 'auto')
# # a user may modify the value of 'file_enc' in the address bar of a browser
# if not file_enc in FILE_ENCODING_LIST:
# file_enc = 'auto'
# commit_id = request.GET.get('commit_id', '')
# view_history = True if commit_id else False
# current_commit = seafserv_threaded_rpc.get_commit(commit_id)
# if not current_commit:
# current_commit = get_commits(repo_id, 0, 1)[0]
# basedir = ''
# days = 0
# if page_from == 'recycle':
# basedir = request.GET.get('base', '')
# if not basedir:
# raise Http404
# days = show_delete_days(request)
# if view_history:
# obj_id = request.GET.get('obj_id', '')
# else:
# try:
# obj_id = seafserv_threaded_rpc.get_file_id_by_path(repo_id, path)
# except:
# obj_id = None
# if not obj_id:
# return render_error(request, _(u'File does not exist'))
# if repo.encrypted and not is_passwd_set(repo_id, request.user.username):
# # Redirect uesr to decrypt repo page.
# return render_to_response('decrypt_repo_form.html', {
# 'repo': repo,
# 'next': request.get_full_path(),
# }, context_instance=RequestContext(request))
# permission = get_user_permission(request, repo_id)
# if permission:
# # Get a token to visit file
# token = seafserv_rpc.web_get_access_token(repo_id,
# obj_id,
# 'view',
# request.user.username)
# else:
# return render_permission_error(request, _(u'Unable to view file'))
# read_only = True if permission == 'r' else False
# # generate path and link
# if page_from == 'recycle':
# zipped = gen_path_link(path, '')
# else:
# zipped = gen_path_link(path, repo.name)
# # determin whether file can preview on web
# filetype, fileext = valid_previewed_file(filename)
# # raw path
# raw_path = gen_file_get_url(token, filename)
# # get file content
# err, file_content, swf_exists, filetype, encoding = get_file_content(filetype, raw_path, obj_id, fileext, file_enc)
# file_encoding_list = FILE_ENCODING_LIST
# if encoding and encoding not in FILE_ENCODING_LIST:
# file_encoding_list.append(encoding)
# img_prev = None
# img_next = None
# if filetype == 'Image' and not view_history:
# parent_dir = os.path.dirname(path)
# try:
# dirs = seafserv_threaded_rpc.list_dir_by_path(current_commit.id, parent_dir.encode('utf-8'))
# except SearpcError, e:
# raise Http404
# img_list = []
# for dirent in dirs:
# if not stat.S_ISDIR(dirent.props.mode):
# fltype, flext = valid_previewed_file(dirent.obj_name)
# if fltype == 'Image':
# img_list.append(dirent.obj_name)
# if len(img_list) > 1:
# img_list.sort(lambda x, y : cmp(x.lower(), y.lower()))
# cur_img_index = img_list.index(u_filename)
# if cur_img_index != 0:
# img_prev = os.path.join(parent_dir, img_list[cur_img_index - 1])
# if cur_img_index != len(img_list) - 1:
# img_next = os.path.join(parent_dir, img_list[cur_img_index + 1])
# if view_history:
# return render_to_response('history_file_view.html', {
# 'repo': repo,
# 'obj_id': obj_id,
# 'u_filename': u_filename,
# 'file_name': filename,
# 'path': path,
# 'zipped': zipped,
# 'view_history': view_history,
# 'current_commit': current_commit,
# 'token': token,
# 'filetype': filetype,
# 'fileext': fileext,
# 'raw_path': raw_path,
# 'err': err,
# 'file_content': file_content,
# 'encoding': encoding,
# 'file_encoding_list':file_encoding_list,
# 'swf_exists': swf_exists,
# 'DOCUMENT_CONVERTOR_ROOT': DOCUMENT_CONVERTOR_ROOT,
# 'use_pdfjs':USE_PDFJS,
# 'page_from': page_from,
# 'basedir': basedir,
# 'days': days,
# }, context_instance=RequestContext(request))
# # file share link
# l = FileShare.objects.filter(repo_id=repo_id).filter(\
# username=request.user.username).filter(path=path)
# fileshare = l[0] if len(l) > 0 else None
# http_or_https = request.is_secure() and 'https' or 'http'
# domain = RequestSite(request).domain
# if fileshare:
# file_shared_link = gen_shared_link(request, fileshare.token, 'f')
# else:
# file_shared_link = ''
# # my constacts
# contacts = Contact.objects.filter(user_email=request.user.username)
# # Get groups this repo is shared.
# if request.user.org:
# org_id = request.user.org['org_id']
# repo_shared_groups = get_org_groups_by_repo(org_id, repo_id)
# else:
# repo_shared_groups = get_shared_groups_by_repo(repo_id)
# # Filter out groups that user in joined.
# groups = [ x for x in repo_shared_groups if \
# is_group_user(x.id, request.user.username)]
# """file comments"""
# # Make sure page request is an int. If not, deliver first page.
# file_path_hash = md5_constructor(urllib2.quote(path.encode('utf-8'))).hexdigest()[:12]
# comments = FileComment.objects.filter(file_path_hash=file_path_hash, repo_id=repo_id)
# contributors, last_modified, last_commit_id = get_file_contributors(repo_id, path.encode('utf-8'), file_path_hash, obj_id)
# latest_contributor = contributors[0] if contributors else None
# if len(groups) > 1:
# ctx = {}
# ctx['groups'] = groups
# repogrp_str = render_to_string("snippets/repo_group_list.html", ctx)
# else:
# repogrp_str = ''
# is_starred = False
# org_id = -1
# if request.user.org:
# org_id = request.user.org['org_id']
# is_starred = is_file_starred(request.user.username, repo.id, path.encode('utf-8'), org_id)
# user_perm = get_user_permission(request, repo_id)
# return render_to_response('file_view.html', {
# 'repo': repo,
# 'obj_id': obj_id,
# 'u_filename': u_filename,
# 'file_name': filename,
# 'path': path,
# 'zipped': zipped,
# 'view_history': view_history,
# 'current_commit': current_commit,
# 'token': token,
# 'filetype': filetype,
# 'fileext': fileext,
# 'raw_path': raw_path,
# 'fileshare': fileshare,
# 'protocol': http_or_https,
# 'domain': domain,
# 'file_shared_link': file_shared_link,
# 'contacts': contacts,
# 'err': err,
# 'file_content': file_content,
# 'file_enc': file_enc,
# 'encoding': encoding,
# 'file_encoding_list':file_encoding_list,
# "applet_root": get_ccnetapplet_root(),
# 'groups': groups,
# 'comments': comments,
# 'comment_open':comment_open,
# 'swf_exists': swf_exists,
# 'DOCUMENT_CONVERTOR_ROOT': DOCUMENT_CONVERTOR_ROOT,
# 'use_pdfjs':USE_PDFJS,
# 'contributors': contributors,
# 'latest_contributor': latest_contributor,
# 'last_modified': last_modified,
# 'last_commit_id': last_commit_id,
# 'read_only': read_only,
# 'page_from': page_from,
# 'repo_group_str': repogrp_str,
# 'is_starred': is_starred,
# 'user_perm': user_perm,
# 'img_prev': img_prev,
# 'img_next': img_next,
# }, context_instance=RequestContext(request))
def file_comment(request): def file_comment(request):
if request.method == 'POST': if request.method == 'POST':
# handle post request to leave comment on a file # handle post request to leave comment on a file
@@ -1618,162 +1393,6 @@ def get_file_content(filetype, raw_path, obj_id, fileext, file_enc):
return err, file_content, swf_exists, filetype, encoding return err, file_content, swf_exists, filetype, encoding
def file_edit_submit(request, repo_id):
content_type = 'application/json; charset=utf-8'
def error_json(error_msg=_(u'Internal Error'), op=None):
return HttpResponse(json.dumps({'error': error_msg, 'op': op}),
status=400,
content_type=content_type)
if get_user_permission(request, repo_id) != 'rw':
return error_json(_(u'Permission denied'))
repo = get_repo(repo_id)
if not repo:
return error_json(_(u'The library does not exist.'))
if repo.encrypted:
repo.password_set = seafserv_rpc.is_passwd_set(repo_id, request.user.username)
if not repo.password_set:
return error_json(_(u'The library is encrypted.'), 'decrypt')
content = request.POST.get('content')
encoding = request.POST.get('encoding')
path = request.GET.get('p')
if content is None or not path or encoding not in ["gbk", "utf-8"]:
return error_json(_(u'Invalid arguments'))
head_id = request.GET.get('head', None)
content = content.encode(encoding)
# first dump the file content to a tmp file, then update the file
fd, tmpfile = tempfile.mkstemp()
def remove_tmp_file():
try:
os.remove(tmpfile)
except:
pass
try:
bytesWritten = os.write(fd, content)
except:
bytesWritten = -1
finally:
os.close(fd)
if bytesWritten != len(content):
remove_tmp_file()
return error_json()
if request.GET.get('from', '') == 'wiki_page_edit':
try:
gid = int(request.GET.get('gid', 0))
except ValueError:
gid = 0
wiki_name = os.path.splitext(os.path.basename(path))[0]
next = reverse('group_wiki', args=[gid, wiki_name])
elif request.GET.get('from', '') == 'wiki_page_new':
try:
gid = int(request.GET.get('gid', 0))
except ValueError:
gid = 0
next = reverse('group_wiki_pages', args=[gid])
else:
next = reverse('repo_view_file', args=[repo_id]) + \
'?p=' + urllib2.quote(path.encode('utf-8'))
parent_dir = os.path.dirname(path).encode('utf-8')
filename = os.path.basename(path).encode('utf-8')
try:
seafserv_threaded_rpc.put_file(repo_id, tmpfile, parent_dir,
filename, request.user.username, head_id)
remove_tmp_file()
return HttpResponse(json.dumps({'href': next}),
content_type=content_type)
except SearpcError, e:
remove_tmp_file()
return error_json(str(e))
@login_required
@ctx_switch_required
def file_edit(request, repo_id):
repo = get_repo(repo_id)
if not repo:
raise Http404
if request.method == 'POST':
return file_edit_submit(request, repo_id)
if get_user_permission(request, repo_id) != 'rw':
return render_permission_error(request, _(u'Unable to edit file'))
path = request.GET.get('p', '/')
if path[-1] == '/':
path = path[:-1]
u_filename = os.path.basename(path)
filename = urllib2.quote(u_filename.encode('utf-8'))
head_id = repo.head_cmmt_id
try:
obj_id = seafserv_threaded_rpc.get_file_id_by_path(repo_id, path)
except:
obj_id = None
if not obj_id:
return render_error(request, _(u'The file does not exist.'))
if access_to_repo(request, repo_id, ''):
token = seafserv_rpc.web_get_access_token(repo_id, obj_id,
'view', request.user.username)
else:
return render_permission_error(request, _(u'Unable to view file'))
# generate path and link
zipped = gen_path_link(path, repo.name)
filetype, fileext = valid_previewed_file(filename)
op = None
err = ''
file_content = None
encoding = None
file_encoding_list = FILE_ENCODING_LIST
if filetype == 'Text' or filetype == 'Markdown' or filetype == 'Sf':
if repo.encrypted:
repo.password_set = seafserv_rpc.is_passwd_set(repo_id, request.user.username)
if not repo.password_set:
op = 'decrypt'
if not op:
raw_path = gen_file_get_url(token, filename)
file_enc = request.GET.get('file_enc', 'auto')
if not file_enc in FILE_ENCODING_LIST:
file_enc = 'auto'
err, file_content, encoding = repo_file_get(raw_path, file_enc)
if encoding and encoding not in FILE_ENCODING_LIST:
file_encoding_list.append(encoding)
else:
err = _(u'Edit online is not offered for this type of file.')
return render_to_response('file_edit.html', {
'repo':repo,
'u_filename':u_filename,
'wiki_name': os.path.splitext(u_filename)[0],
'path':path,
'zipped':zipped,
'filetype':filetype,
'fileext':fileext,
'op':op,
'err':err,
'file_content':file_content,
'encoding': encoding,
'file_encoding_list':file_encoding_list,
'head_id': head_id,
'from': request.GET.get('from', ''),
'gid': request.GET.get('gid', ''),
}, context_instance=RequestContext(request))
def repo_access_file(request, repo_id, obj_id): def repo_access_file(request, repo_id, obj_id):
repo = get_repo(repo_id) repo = get_repo(repo_id)
if not repo: if not repo:

View File

@@ -7,6 +7,7 @@ view_trash_file, view_snapshot_file
import os import os
import simplejson as json import simplejson as json
import stat import stat
import tempfile
import urllib import urllib
import urllib2 import urllib2
import chardet import chardet
@@ -23,9 +24,10 @@ from django.utils.translation import ugettext as _
from seaserv import list_dir_by_path, get_repo, web_get_access_token, \ from seaserv import list_dir_by_path, get_repo, web_get_access_token, \
get_commits, is_passwd_set, check_permission, get_shared_groups_by_repo,\ get_commits, is_passwd_set, check_permission, get_shared_groups_by_repo,\
is_group_user, get_file_id_by_path, get_commit, get_file_size, \ is_group_user, get_file_id_by_path, get_commit, get_file_size, \
get_org_groups_by_repo get_org_groups_by_repo, seafserv_rpc, seafserv_threaded_rpc
from pysearpc import SearpcError from pysearpc import SearpcError
from auth.decorators import login_required
from base.decorators import ctx_switch_required, repo_passwd_set_required from base.decorators import ctx_switch_required, repo_passwd_set_required
from base.models import UuidObjidMap, FileComment from base.models import UuidObjidMap, FileComment
from contacts.models import Contact from contacts.models import Contact
@@ -34,7 +36,8 @@ from seahub.utils import get_httpserver_root, show_delete_days, render_error,\
get_file_type_and_ext, gen_file_get_url, gen_shared_link, is_file_starred,\ get_file_type_and_ext, gen_file_get_url, gen_shared_link, is_file_starred,\
get_file_contributors, get_ccnetapplet_root, render_permission_error, \ get_file_contributors, get_ccnetapplet_root, render_permission_error, \
is_textual_file, show_delete_days is_textual_file, show_delete_days
from seahub.utils.file_types import (IMAGE, PDF, IMAGE, DOCUMENT, MARKDOWN) from seahub.utils.file_types import (IMAGE, PDF, IMAGE, DOCUMENT, MARKDOWN, \
TEXT, SF)
from seahub.settings import FILE_ENCODING_LIST, FILE_PREVIEW_MAX_SIZE, \ from seahub.settings import FILE_ENCODING_LIST, FILE_PREVIEW_MAX_SIZE, \
FILE_ENCODING_TRY_LIST, USE_PDFJS, MEDIA_URL FILE_ENCODING_TRY_LIST, USE_PDFJS, MEDIA_URL
try: try:
@@ -540,3 +543,151 @@ def view_snapshot_file(request, repo_id):
return render_to_response('view_history_file.html', ret_dict, return render_to_response('view_history_file.html', ret_dict,
context_instance=RequestContext(request), ) context_instance=RequestContext(request), )
def file_edit_submit(request, repo_id):
content_type = 'application/json; charset=utf-8'
def error_json(error_msg=_(u'Internal Error'), op=None):
return HttpResponse(json.dumps({'error': error_msg, 'op': op}),
status=400,
content_type=content_type)
if get_user_permission(request, repo_id) != 'rw':
return error_json(_(u'Permission denied'))
repo = get_repo(repo_id)
if not repo:
return error_json(_(u'The library does not exist.'))
if repo.encrypted:
repo.password_set = seafserv_rpc.is_passwd_set(repo_id, request.user.username)
if not repo.password_set:
return error_json(_(u'The library is encrypted.'), 'decrypt')
content = request.POST.get('content')
encoding = request.POST.get('encoding')
path = request.GET.get('p')
if content is None or not path or encoding not in ["gbk", "utf-8"]:
return error_json(_(u'Invalid arguments'))
head_id = request.GET.get('head', None)
content = content.encode(encoding)
# first dump the file content to a tmp file, then update the file
fd, tmpfile = tempfile.mkstemp()
def remove_tmp_file():
try:
os.remove(tmpfile)
except:
pass
try:
bytesWritten = os.write(fd, content)
except:
bytesWritten = -1
finally:
os.close(fd)
if bytesWritten != len(content):
remove_tmp_file()
return error_json()
if request.GET.get('from', '') == 'wiki_page_edit':
try:
gid = int(request.GET.get('gid', 0))
except ValueError:
gid = 0
wiki_name = os.path.splitext(os.path.basename(path))[0]
next = reverse('group_wiki', args=[gid, wiki_name])
elif request.GET.get('from', '') == 'wiki_page_new':
try:
gid = int(request.GET.get('gid', 0))
except ValueError:
gid = 0
next = reverse('group_wiki_pages', args=[gid])
else:
next = reverse('repo_view_file', args=[repo_id]) + \
'?p=' + urllib2.quote(path.encode('utf-8'))
parent_dir = os.path.dirname(path).encode('utf-8')
filename = os.path.basename(path).encode('utf-8')
try:
seafserv_threaded_rpc.put_file(repo_id, tmpfile, parent_dir,
filename, request.user.username, head_id)
remove_tmp_file()
return HttpResponse(json.dumps({'href': next}),
content_type=content_type)
except SearpcError, e:
remove_tmp_file()
return error_json(str(e))
@login_required
@ctx_switch_required
def file_edit(request, repo_id):
repo = get_repo(repo_id)
if not repo:
raise Http404
if request.method == 'POST':
return file_edit_submit(request, repo_id)
if get_user_permission(request, repo_id) != 'rw':
return render_permission_error(request, _(u'Unable to edit file'))
path = request.GET.get('p', '/')
if path[-1] == '/':
path = path[:-1]
u_filename = os.path.basename(path)
filename = urllib2.quote(u_filename.encode('utf-8'))
head_id = repo.head_cmmt_id
obj_id = get_file_id_by_path(repo_id, path)
if not obj_id:
return render_error(request, _(u'The file does not exist.'))
token = web_get_access_token(repo_id, obj_id, 'view', request.user.username)
# generate path and link
zipped = gen_path_link(path, repo.name)
filetype, fileext = get_file_type_and_ext(filename)
op = None
err = ''
file_content = None
encoding = None
file_encoding_list = FILE_ENCODING_LIST
if filetype == TEXT or filetype == MARKDOWN or filetype == SF:
if repo.encrypted:
repo.password_set = seafserv_rpc.is_passwd_set(repo_id, request.user.username)
if not repo.password_set:
op = 'decrypt'
if not op:
raw_path = gen_file_get_url(token, filename)
file_enc = request.GET.get('file_enc', 'auto')
if not file_enc in FILE_ENCODING_LIST:
file_enc = 'auto'
err, file_content, encoding = repo_file_get(raw_path, file_enc)
if encoding and encoding not in FILE_ENCODING_LIST:
file_encoding_list.append(encoding)
else:
err = _(u'Edit online is not offered for this type of file.')
return render_to_response('file_edit.html', {
'repo':repo,
'u_filename':u_filename,
'wiki_name': os.path.splitext(u_filename)[0],
'path':path,
'zipped':zipped,
'filetype':filetype,
'fileext':fileext,
'op':op,
'err':err,
'file_content':file_content,
'encoding': encoding,
'file_encoding_list':file_encoding_list,
'head_id': head_id,
'from': request.GET.get('from', ''),
'gid': request.GET.get('gid', ''),
}, context_instance=RequestContext(request))