Commit 8ed489aa authored by Marcel's avatar Marcel
Browse files

Add and clean FSController.

parent 66cb2f92
......@@ -45,7 +45,7 @@ class AbstractController(object):
return result
# a little helper
def get(self, key):
def get(self, key, *args):
key = key.lower()
try:
if key == 'session_id':
......@@ -64,6 +64,11 @@ class AbstractController(object):
return cherrypy.session['profile_id']
elif key == 'profile':
return cherrypy.request.profile
elif key == 'fs':
workspace_id = None
if len(args) > 0:
workspace_id = args[0]
return self.get_fs(workspace_id=workspace_id)
except:
return None
return None
......@@ -71,7 +76,6 @@ class AbstractController(object):
# a little unicode helper
def convert(self, value, flag):
flag = flag.lower()
# convet lists, tuples and dicts by pseudo recursion
if isinstance(value, list):
return map(lambda elem: self.convert(elem, flag), value)
......@@ -85,7 +89,6 @@ class AbstractController(object):
# string
if flag in ['s', 'str', 'string']:
return str(value)
# boolean
if flag in ['b', 'bool', 'boolean']:
value = str(value).lower()
......@@ -96,7 +99,6 @@ class AbstractController(object):
else:
raise Exception("TypeError: boolean conversion expects 'true' or 'false' (string).")
return None
# integer
if flag in ['i', 'int', 'integer', 'l', 'long']:
value = str(value)
......@@ -104,7 +106,6 @@ class AbstractController(object):
return int(value)
except:
raise Exception('TypeError: conversion to integer received bad argument.')
# float
if flag in ['f', 'float', 'd', 'double']:
value = str(value)
......@@ -112,29 +113,16 @@ class AbstractController(object):
return float(value)
except:
raise Exception('TypeError: conversion to float received bad argument.')
# error case
raise Exception('TypeError: conversion with unknown type flag.')
def _get_fs_instance(self, username, workspace_id=None):
workspace_id = workspace_id or self.get('workspace_id') or cherrypy.config.get('rpc.default_workspace_id', 0)
key = (str(username), workspace_id)
if key in self._fs_instances.keys():
instance = self._fs_instances[key]
if isinstance(instance, RpcProcess):
if instance.online():
return instance
def get_fs(self, workspace_id=None):
if not workspace_id and workspace_id !== 0:
# try to get the workspace id from the session
if 'workspace_id' in cherrypy.session.keys():
workspace_id = cherrypy.session['workspace_id']
else:
return instance
if workspace_id:
workspace = models.workspace.Workspace.get_by_id(cherrypy.request.db, workspace_id)
instance = cherrypy.engine.publish('rpc_get', 'vispa.filesystem.FileSystem', False, None, workspace_id).pop()
instance.setup(str(workspace.basedir))
else:
instance = filesystem.FileSystem()
instance.setup()
self._fs_instances[key] = instance
return instance
return None
# the workspace_id is set now
# TODO: use the ws plugin
return None
......@@ -6,6 +6,7 @@ from subprocess import call
from string import Template
import json as JSON
from vispa.controller import AbstractController
from vispa.controller.filesystem import FSAjaxController
from vispa.models.user import User
from vispa.models.workspace import Workspace
from vispa.models.profile import Profile
......@@ -21,6 +22,7 @@ class AjaxController(AbstractController):
def __init__(self, platform):
AbstractController.__init__(self, platform)
self._platform = platform
self.fs = FSAjaxController(platform)
@cherrypy.expose
@cherrypy.tools.user()
......
# -*- coding: utf-8 -*-
# Imports
# imports
import vispa
import cherrypy
import os, json, cStringIO
......@@ -10,89 +10,80 @@ from vispa.filesystem import FileSystem as fs
from vispa.controller import AbstractController
import xmlrpclib
class FSController(AbstractController):
@cherrypy.expose
@cherrypy.tools.allow(methods=["GET"])
@cherrypy.tools.allow(methods=['GET'])
@cherrypy.tools.user()
def getfile(self, path, download=None, rnd=None):
if download is None or str(download).lower() not in ["true", "1", "yes"]:
download = False
else:
download = True
uname = self.get("uname")
try:
data, contenttype, isbrowserfile = self.handleDownload(uname, str(path))
if not download or str(download).lower() not in ['true', '1', 'yes']:
download = False
else:
download = True
data, contenttype, isbrowserfile = self.handleDownload(str(path))
cherrypy.response.headers['Content-Type'] = contenttype
if download or not isbrowserfile:
cherrypy.response.headers["Content-Disposition"] = "attachment; filename=%s" % path.split("/")[-1]
cherrypy.response.headers['Content-Disposition'] = 'attachment; filename=%s' % path.split('/')[-1]
return data
except Exception, e:
cherrypy.session["error_data"] = {"status": 404, "message": str(e), "traceback": "", "version": ""}
raise cherrypy.HTTPRedirect(os.path.join(vispa.url.base_static, "error/filenotfound"))
cherrypy.session['error_data'] = {'status': 404, 'message': str(e), 'traceback': '', 'version': ''}
raise cherrypy.HTTPRedirect(vispa.url.dynamic(os.path.join('error/filenotfound')))
def handleDownload(self, username, path):
fs = self._get_fs_instance(username)
if not fs.exists(path, "file"):
raise Exception("The file '%s' does not exist or<br />you don't have the permission to read this file." % vPath)
return None
def handleDownload(self, path):
self.get('fs')
if not fs.exists(path, 'file'):
raise Exception('The file \'%s\' does not exist' % path)
binary, message = fs.get_file_content(path)
data = binary.data
content = fs.get_file_content(path)
data = xmlrpclib.Binary(content).data
# get the content type depending on the file extension
ext = path.split(".")[-1]
ext = path.split('.')[-1]
mimetype = fs.get_mime_type(path)
if mimetype is None:
raise Exception("The file extension '%s' is not supported by this server" % ext)
return None
raise Exception('The file extension \'%s\' is not supported by this server' % ext)
return data, mimetype, fs.is_browser_file(path)
class FSAjaxController(AbstractController):
@cherrypy.expose
@cherrypy.tools.user()
@cherrypy.tools.allow(methods=["POST"])
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def exists(self):
json = cherrypy.request.json
uname = self.get('uname')
fs = self._get_fs_instance(uname)
def exists(self, path, is_folder=None):
try:
return {"success": fs.exists(json["path"], json["pathtype"], json['fileextension'], json["permissionmode"])}
except Exception, e:
return {"success": False, "msg": "Error while checking path!<br />Reason: %s" % str(e)}
# TODO
if self.convert(path, 'string').startswith('/user/'):
return self.success({'type': 'file'})
else:
return self.fail()
except:
return self.fail()
@cherrypy.expose
@cherrypy.tools.user()
@cherrypy.tools.allow(methods=['POST'])
@cherrypy.tools.json_out()
def filelist(self, path, deep, ext_filter, reverse_filter):
uname = self.get('uname')
fs = self._get_fs_instance(uname)
# as recursive and only_directories are send
# by xhrPost (in ajax.js) as a string/unicode we have
# to convert it into a boolean.
#try:
path = self.convert(path, "string")
deep = self.convert(deep, "boolean")
ext_filter = self.convert([ext_filter] if type(ext_filter) != type([]) else ext_filter, "string")
reverse_filter = self.convert(reverse_filter, "boolean")
# get the files with the filter
try:
files = fs.get_file_list(path, deep, ext_filter, reverse_filter)
@cherrypy.tools.json_in()
def filelist(self):
try:
json = cherrypy.request.json
fs = self.get('fs')
# get the files with the filter
files = fs.get_file_list(json[u'path', json[u'deep'], json[u'ext_filter'], json[u'reverse_filter'])
# sort by name first
files = sorted(files, key=lambda entry: str(entry["name"]))
files = sorted(files, key=lambda entry: str(entry['name']))
# sort files by file/folder
files = sorted(files, key=lambda entry: str(entry["type"]), reverse=True)
return {"success": True, "files": files}
files = sorted(files, key=lambda entry: str(entry['type']), reverse=True)
return self.success({'files': files})
except Exception, e:
return {"success": False, "msg": "Couldn't load files!<br />Reason: %s"%str(e)}
return self.fail(msg='Couldn\'t load files: %s' % str(e))
@cherrypy.expose
@cherrypy.tools.user()
......@@ -100,12 +91,11 @@ class FSAjaxController(AbstractController):
@cherrypy.tools.json_out()
def createfolder(self, path, name):
try:
username = self.get('uname')
fs = self._get_fs_instance(username)
fs = self.get('fs')
fs.create_folder(str(path), str(name))
return {"success": True}
return self.success()
except Exception, e:
return {"success": False, "msg": "Couldn't create the folder!<br />Reason: %s" % str(e)}
return self.fail(msg='Couldn\'t create the folder: %s' % str(e))
@cherrypy.expose
@cherrypy.tools.user()
......@@ -113,12 +103,11 @@ class FSAjaxController(AbstractController):
@cherrypy.tools.json_out()
def createfile(self, path, name):
try:
username = self.get('uname')
fs = self._get_fs_instance(username)
fs = self.get('fs')
fs.create_file(str(path), str(name))
return {"success": True}
return self.success()
except Exception, e:
return {"success": False, "msg": "Couldn't create the file!<br />Reason: %s" % str(e)}
return self.fail(msg='Couldn\'t create the file: %s' % str(e))
@cherrypy.expose
@cherrypy.tools.user()
......@@ -126,12 +115,11 @@ class FSAjaxController(AbstractController):
@cherrypy.tools.json_out()
def renamefolder(self, path, name):
try:
username = self.get('uname')
fs = self._get_fs_instance(username)
fs = self.get('fs')
fs.rename_folder(str(path), str(name))
return {"success": True}
return self.success()
except Exception, e:
return {"success": False, "msg": "Couldn't rename the folder!<br />Reason: %s" % str(e)}
return self.fail(msg='Couldn\'t rename the folder: %s' % str(e))
@cherrypy.expose
@cherrypy.tools.user()
......@@ -139,12 +127,11 @@ class FSAjaxController(AbstractController):
@cherrypy.tools.json_out()
def renamefile(self, path, name):
try:
username = self.get('uname')
fs = self._get_fs_instance(username)
fs = self.get('fs')
fs.rename_file(str(path), str(name))
return {"success": True}
return self.success()
except Exception, e:
return {"success": False, "msg": "Couldn't rename the file!<br />Reason: %s" % str(e)}
return self.fail(msg='Couldn\'t rename the file: %s' % str(e))
@cherrypy.expose
@cherrypy.tools.user()
......@@ -152,12 +139,13 @@ class FSAjaxController(AbstractController):
@cherrypy.tools.json_out()
def remove(self, path):
try:
username = self.get('uname')
fs = self._get_fs_instance(username)
fs.remove(self.convert(path, "s"))
return {"success": True}
fs = self.get('fs')
# 'path' can be a unicode/string or list of unicodes/strings
# so convert it with the convert function
fs.remove(self.convert(path, 'string'))
return self.success()
except Exception, e:
return {"success": False, "msg": "Couldn't remove file(s)!<br />Reason: %s" % str(e)}
return self.fail(msg='Couldn\'t remove the file(s): %s' % str(e))
@cherrypy.expose
@cherrypy.tools.user()
......@@ -165,12 +153,13 @@ class FSAjaxController(AbstractController):
@cherrypy.tools.json_out()
def compress(self, path, paths, name):
try:
username = self.get('uname')
fs = self._get_fs_instance(username)
fs.compress(str(path), self.convert(paths, "s"), str(name))
return {"success": True}
fs = self.get('fs')
# 'paths' can be a unicode/string or list of unicodes/strings
# so convert it with the convert function
fs.compress(str(path), self.convert(path, 'string'), str(name))
return self.success()
except Exception, e:
return {"success": False, "msg": "Couldn't compress the file(s)!<br />Reason: %s" % str(e)}
return self.fail(msg='Couldn\'t compress the file(s): %s' % str(e))
@cherrypy.expose
@cherrypy.tools.user()
......@@ -178,13 +167,14 @@ class FSAjaxController(AbstractController):
@cherrypy.tools.json_out()
def paste(self, path, paths, cut):
try:
username = self.get('uname')
fs = self._get_fs_instance(username)
fs.paste(str(path), self.convert(paths, "s"), self.convert(cut, "b"))
return {"success": True}
fs = self.get('fs')
# 'paths' can be a unicode/string or list of unicodes/strings
# so convert it with the convert function
fs.paste(str(path), self.convert(path, 'string'), self.convert(cut, 'boolean'))
return self.success()
except Exception, e:
action = "cut" if self.convert(cut, "b") else "copy"
return {"success": False, "msg": "Couldn't %s the file(s)!<br />Reason: %s" % (action, str(e))}
action = 'cut' if self.convert(cut, 'boolean') else 'copy'
return self.fail(msg='Couldn\'t %s the file(s): %s' % (action, str(e)))
@cherrypy.expose
@cherrypy.tools.user()
......@@ -197,47 +187,47 @@ class FSAjaxController(AbstractController):
# we have to use kwargs instead of args
try:
# extract the path
path = "/user/"
if "path" in kwargs.keys():
path = str(kwargs["path"])
path = str(kwargs['path'])
# prepare the parts
parts = kwargs["uploadedfiles[]"]
parts = parts if type(parts) == type([]) else [parts]
parts = kwargs['uploadedfiles[]']
# force parrts to be a list
if not isinstance(parts, list):
parts = [parts]
# upload
self.handleUpload(self.get("uname"), path, parts)
self.handleUpload(path, parts)
return {"success": True}
return self.success()
except Exception, e:
return {"success": False, "msg": "Couldn't upload the file(s)!<br />Reason: %s" % str(e)}
def handleUpload(self, username, path, parts):
fs = self._get_fs_instance(username)
return self.fail(msg='Couldn\'t upload the file(s): %s' % str(e))
def handleUpload(self, path, parts):
fs = self.get('fs')
for part in parts:
f = part.file
name = str(part.filename)
#check mime type, i.e. get the content type depending on the file extension
# check mime type, i.e. get the content type depending on the file extension
mimetype = fs.get_mime_type(name)
if mimetype is None:
ext = name.split(".")[-1]
raise Exception("The file extension '%s' is not supported by this server" % ext)
ext = name.split('.')[-1]
raise Exception('The file extension \'%s\' is not supported by this server' % ext)
#save the content using the fs
try:
fs.save_file_content(path + name, xmlrpclib.Binary(f), force=True)
except Exception, e:
raise Exception("Couldn't handle the upload. Reason: %s", str(e))
fs.save_file_content(os.path.join(path, name), xmlrpclib.Binary(f), force=True)
@cherrypy.expose
@cherrypy.tools.user()
@cherrypy.tools.allow(methods=["POST"])
@cherrypy.tools.json_out()
def isbrowserfile(self, path):
uname = self.get("uname")
fs = self._get_fs_instance(uname)
return {"success": fs.is_browser_file(str(path))}
\ No newline at end of file
try:
fs = self.get('fs')
is_bf = fs.is_browser_file(str(path))
if is_bf:
return self.success()
else:
return self.fail()
except Exception, e:
return self.fail()
......@@ -26,7 +26,7 @@ class PlatformController(AbstractController):
'''
AbstractController.__init__(self, platform)
self.ajax = AjaxController(platform)
self.vfs = FSController(platform)
self.fs = FSController(platform)
self.error = ErrorController()
self.extensions = AbstractController(platform)
self.bus = BusController(platform)
......@@ -50,8 +50,10 @@ class PlatformController(AbstractController):
@cherrypy.tools.profile()
@cherrypy.tools.allow(methods=['GET'])
@cherrypy.tools.stats(page='index')
@cherrypy.tools.render(template='sites/index.html')
#@cherrypy.tools.render(template='sites/index.html')
def index(self, *args, **kwargs):
print self.get('workspace_id')
return "index"
db = cherrypy.request.db
username = cherrypy.request.user.name
use_websockets = vispa.config('websockets', 'enabled', False)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment