Use different entry points for users and guests

pull/1/head
Victor Dubiniuk 9 years ago
parent a6be42cb26
commit b8917435f3

@ -19,10 +19,12 @@ $application->registerRoutes($this, [
['name' => 'user#disconnectUser', 'url' => 'ajax/user/disconnect', 'verb' => 'POST'], ['name' => 'user#disconnectUser', 'url' => 'ajax/user/disconnect', 'verb' => 'POST'],
['name' => 'user#disconnectGuest', 'url' => 'ajax/user/disconnectGuest', 'verb' => 'POST'], ['name' => 'user#disconnectGuest', 'url' => 'ajax/user/disconnectGuest', 'verb' => 'POST'],
//session //session
['name' => 'session#joinAsUser', 'url' => 'ajax/session/joinasuser/{fileId}', 'verb' => 'POST'], ['name' => 'session#join', 'url' => 'session/user/join/{fileId}', 'verb' => 'POST'],
['name' => 'session#joinAsGuest', 'url' => 'ajax/session/joinasguest/{token}', 'verb' => 'POST'], ['name' => 'session#poll', 'url' => 'session/user/poll', 'verb' => 'POST'],
['name' => 'session#save', 'url' => 'ajax/session/save', 'verb' => 'POST'], ['name' => 'session#save', 'url' => 'session/user/save', 'verb' => 'POST'],
['name' => 'session#poll', 'url' => 'ajax/otpoll.php', 'verb' => 'POST'], ['name' => 'session#joinAsGuest', 'url' => 'session/guest/join/{token}', 'verb' => 'POST'],
['name' => 'session#pollAsGuest', 'url' => 'session/guest/poll/{token}', 'verb' => 'POST'],
['name' => 'session#saveAsGuest', 'url' => 'session/guest/save/{token}', 'verb' => 'POST'],
//documents //documents
['name' => 'document#index', 'url' => 'index', 'verb' => 'GET'], ['name' => 'document#index', 'url' => 'index', 'verb' => 'GET'],
['name' => 'document#create', 'url' => 'ajax/documents/create', 'verb' => 'POST'], ['name' => 'document#create', 'url' => 'ajax/documents/create', 'verb' => 'POST'],

@ -16,7 +16,6 @@ use \OCP\IRequest;
use \OCP\AppFramework\Http; use \OCP\AppFramework\Http;
use \OCP\AppFramework\Http\JSONResponse; use \OCP\AppFramework\Http\JSONResponse;
use \OCA\Documents\Db; use \OCA\Documents\Db;
use \OCA\Documents\File; use \OCA\Documents\File;
use \OCA\Documents\Helper; use \OCA\Documents\Helper;
@ -40,6 +39,7 @@ class SessionController extends Controller{
protected $uid; protected $uid;
protected $logger; protected $logger;
protected $shareToken;
public function __construct($appName, IRequest $request, $logger, $uid){ public function __construct($appName, IRequest $request, $logger, $uid){
parent::__construct($appName, $request); parent::__construct($appName, $request);
@ -62,13 +62,11 @@ class SessionController extends Controller{
$response = array_merge( $response = array_merge(
Db\Session::start($uid, $file), Db\Session::start($uid, $file),
array('status'=>'success') [ 'status'=>'success' ]
); );
} catch (\Exception $e){ } catch (\Exception $e){
$this->logger->warning('Starting a session failed. Reason: ' . $e->getMessage(), array('app' => $this->appName)); $this->logger->warning('Starting a session failed. Reason: ' . $e->getMessage(), ['app' => $this->appName]);
$response = array ( $response = [ 'status'=>'error' ];
'status'=>'error'
);
} }
return $response; return $response;
@ -76,8 +74,27 @@ class SessionController extends Controller{
/** /**
* @NoAdminRequired * @NoAdminRequired
* @PublicPage
*/
public function pollAsGuest($command, $args){
$this->shareToken = $this->request->getParam('token');
return $this->poll($command, $args);
}
/**
* Store the document content to its origin
* @NoAdminRequired
* @PublicPage
*/ */
public function joinAsUser($fileId){ public function saveAsGuest(){
$this->shareToken = $this->request->getParam('token');
return $this->save();
}
/**
* @NoAdminRequired
*/
public function join($fileId){
try { try {
$view = \OC\Files\Filesystem::getView(); $view = \OC\Files\Filesystem::getView();
$path = $view->getPath($fileId); $path = $view->getPath($fileId);
@ -87,20 +104,18 @@ class SessionController extends Controller{
$response = Db\Session::start($this->uid, $file); $response = Db\Session::start($this->uid, $file);
} else { } else {
$info = $view->getFileInfo($path); $info = $view->getFileInfo($path);
$response = array( $response = [
'permissions' => $info['permissions'], 'permissions' => $info['permissions'],
'id' => $fileId 'id' => $fileId
); ];
} }
$response = array_merge( $response = array_merge(
$response, $response,
array('status'=>'success') [ 'status'=>'success' ]
); );
} catch (\Exception $e){ } catch (\Exception $e){
$this->logger->warning('Starting a session failed. Reason: ' . $e->getMessage(), array('app' => $this->appName)); $this->logger->warning('Starting a session failed. Reason: ' . $e->getMessage(), [ 'app' => $this->appName ]);
$response = array ( $response = [ 'status'=>'error' ];
'status'=>'error'
);
} }
return $response; return $response;
@ -108,41 +123,24 @@ class SessionController extends Controller{
/** /**
* @NoAdminRequired * @NoAdminRequired
* @PublicPage
*/ */
public function poll($command, $args){ public function poll($command, $args){
$response = new JSONResponse(); $response = new JSONResponse();
try{ try{
$esId = isset($args['es_id']) ? $args['es_id'] : null; $esId = isset($args['es_id']) ? $args['es_id'] : null;
$session = $this->loadSession($esId);
$session = new Db\Session();
$session->load($esId);
$memberId = isset($args['member_id']) ? $args['member_id'] : null; $memberId = isset($args['member_id']) ? $args['member_id'] : null;
$member = new Db\Member(); $member = $this->loadMember($memberId);
$member->load($memberId);
if (!$member->getIsGuest()){
\OCP\JSON::checkLoggedIn();
}
try { $this->validateSession($session);
new File($session->getFileId());
} catch (\Exception $e){
$this->logger->warning('Error. Session no longer exists. ' . $e->getMessage(), array('app' => $this->appName));
$ex = new BadRequestException();
$ex->setBody(
implode(',', $this->request->getParams())
);
throw $ex;
}
switch ($command){ switch ($command){
case 'sync_ops': case 'sync_ops':
$seqHead = (string) isset($args['seq_head']) ? $args['seq_head'] : null; $seqHead = (string) isset($args['seq_head']) ? $args['seq_head'] : null;
if (!is_null($seqHead)){ if (!is_null($seqHead)){
$ops = isset($args['client_ops']) ? $args['client_ops'] : array(); $ops = isset($args['client_ops']) ? $args['client_ops'] : [];
$op = new Db\Op(); $op = new Db\Op();
$currentHead = $op->getHeadSeq($esId); $currentHead = $op->getHeadSeq($esId);
@ -177,33 +175,24 @@ class SessionController extends Controller{
} catch (BadRequestException $e){ } catch (BadRequestException $e){
$response->setStatus(Http::STATUS_BAD_REQUEST); $response->setStatus(Http::STATUS_BAD_REQUEST);
$response->setData( $response->setData(
array('err' => 'bad request:[' . $e->getBody() . ']') [ 'err' => 'bad request:[' . $e->getBody() . ']' ]
); );
} }
return $response; return $response;
} }
/** /**
* @NoAdminRequired
* @PublicPage
* Store the document content to its origin * Store the document content to its origin
* @NoAdminRequired
*/ */
public function save(){ public function save(){
$response = new JSONResponse();
try { try {
$esId = $this->request->server['HTTP_WEBODF_SESSION_ID']; $esId = $this->request->server['HTTP_WEBODF_SESSION_ID'];
if (!$esId){ $session = $this->loadSession($esId);
throw new \Exception('Session id can not be empty');
}
$memberId = $this->request->server['HTTP_WEBODF_MEMBER_ID']; $memberId = $this->request->server['HTTP_WEBODF_MEMBER_ID'];
$currentMember = new Db\Member(); $currentMember = $this->loadMember($memberId, $esId);
$currentMember->load($memberId);
//check if member belongs to the session
if ($esId != $currentMember->getEsId()){
throw new \Exception($memberId . ' does not belong to session ' . $esId);
}
// Extra info for future usage // Extra info for future usage
// $sessionRevision = $this->request->server['HTTP_WEBODF_SESSION_REVISION']; // $sessionRevision = $this->request->server['HTTP_WEBODF_SESSION_REVISION'];
@ -215,13 +204,6 @@ class SessionController extends Controller{
} }
$content = stream_get_contents($stream); $content = stream_get_contents($stream);
$session = new Db\Session();
$session->load($esId);
if (!$session->getEsId()){
throw new \Exception('Session does not exist');
}
try { try {
if ($currentMember->getIsGuest()){ if ($currentMember->getIsGuest()){
$file = File::getByShareToken($currentMember->getToken()); $file = File::getByShareToken($currentMember->getToken());
@ -229,7 +211,8 @@ class SessionController extends Controller{
$file = new File($session->getFileId()); $file = new File($session->getFileId());
} }
list($view, $path) = $file->getOwnerViewAndPath(true); $view = $file->getOwnerView(true);
$path = $file->getPath(true);
} catch (\Exception $e){ } catch (\Exception $e){
//File was deleted or unshared. We need to save content as new file anyway //File was deleted or unshared. We need to save content as new file anyway
//Sorry, but for guests it would be lost :( //Sorry, but for guests it would be lost :(
@ -256,7 +239,7 @@ class SessionController extends Controller{
$memberCount = count($memberIds) - 1; $memberCount = count($memberIds) - 1;
if ($view->file_exists($path)){ if ($view->file_exists($path)){
$currentHash = sha1($view->file_get_contents($path)); $currentHash = $view->hash('sha1', $path, false);
if (!Helper::isVersionsEnabled() && $currentHash !== $session->getGenesisHash()){ if (!Helper::isVersionsEnabled() && $currentHash !== $session->getGenesisHash()){
// Original file was modified externally. Save to a new one // Original file was modified externally. Save to a new one
@ -274,7 +257,7 @@ class SessionController extends Controller{
// Not a last user // Not a last user
if ($memberCount>0){ if ($memberCount>0){
// Update genesis hash to prevent conflicts // Update genesis hash to prevent conflicts
$this->logger->debug('Update hash', array('app' => $this->appName)); $this->logger->debug('Update hash', [ 'app' => $this->appName ]);
$session->updateGenesisHash($esId, sha1($data['content'])); $session->updateGenesisHash($esId, sha1($data['content']));
} else { } else {
// Last user. Kill session data // Last user. Kill session data
@ -283,13 +266,56 @@ class SessionController extends Controller{
$view->touch($path); $view->touch($path);
} }
$response = array('status'=>'success'); $response->setData(['status'=>'success']);
} catch (\Exception $e){ } catch (\Exception $e){
$this->logger->warning('Saving failed. Reason:' . $e->getMessage(), array('app' => $this->appName)); $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
\OC_Response::setStatus(500); $response->setData([]);
$response = array(); $this->logger->warning('Saving failed. Reason:' . $e->getMessage(), [ 'app' => $this->appName ]);
} }
return $response; return $response;
} }
protected function validateSession($session){
try {
if (is_null($this->shareToken)) {
new File($session->getFileId());
} else {
File::getByShareToken($this->shareToken);
}
} catch (\Exception $e){
$this->logger->warning('Error. Session no longer exists. ' . $e->getMessage(), [ 'app' => $this->appName ]);
$ex = new BadRequestException();
$ex->setBody(
implode(',', $this->request->getParams())
);
throw $ex;
}
}
protected function loadSession($esId){
if (!$esId){
throw new \Exception('Session id can not be empty');
}
$session = new Db\Session();
$session->load($esId);
if (!$session->getEsId()){
throw new \Exception('Session does not exist');
}
return $session;
}
protected function loadMember($memberId, $expectedEsId = null){
if (!$memberId){
throw new \Exception('Member id can not be empty');
}
$member = new Db\Member();
$member->load($memberId);
//check if member belongs to the session
if (!is_null($expectedEsId) && $expectedEsId !== $member->getEsId()){
throw new \Exception($memberId . ' does not belong to session ' . $expectedEsId);
}
return $member;
}
} }

@ -40,8 +40,6 @@ define("owncloud/ServerFactory", [
this.createServer = function (args) { this.createServer = function (args) {
var server; var server;
args = args || {}; args = args || {};
args.url = OC.filePath('documents', 'ajax', 'otpoll.php');
args.sessionStateToFileUrl = OC.generateUrl('apps/documents/ajax/session/save');
server = new PullBoxServer(args); server = new PullBoxServer(args);
server.getGenesisUrl = function(sid) { server.getGenesisUrl = function(sid) {

@ -328,6 +328,13 @@ var documentsMain = {
return; return;
} }
var pollUrl = documentsMain.isGuest
? OC.generateUrl('apps/documents/session/guest/poll/{token}', {'token' : $("[name='document']").val()})
: OC.generateUrl('apps/documents/session/user/poll'),
saveUrl = documentsMain.isGuest
? OC.generateUrl('apps/documents/session/guest/save/{token}', {'token' : $("[name='document']").val()})
: OC.generateUrl('apps/documents/session/user/save')
;
documentsMain.canShare = !documentsMain.isGuest documentsMain.canShare = !documentsMain.isGuest
&& typeof OC.Share !== 'undefined' && response.permissions & OC.PERMISSION_SHARE; && typeof OC.Share !== 'undefined' && response.permissions & OC.PERMISSION_SHARE;
require({ }, ["owncloud/ServerFactory", "webodf/editor/Editor"], function (ServerFactory, Editor) { require({ }, ["owncloud/ServerFactory", "webodf/editor/Editor"], function (ServerFactory, Editor) {
@ -347,8 +354,10 @@ var documentsMain = {
documentsMain.memberId = response.member_id; documentsMain.memberId = response.member_id;
// TODO: set webodf translation system, by passing a proper function translate(!string):!string in "runtime.setTranslator(translate);" // TODO: set webodf translation system, by passing a proper function translate(!string):!string in "runtime.setTranslator(translate);"
documentsMain.webodfServerInstance = serverFactory.createServer({
documentsMain.webodfServerInstance = serverFactory.createServer(); url : pollUrl,
sessionStateToFileUrl : saveUrl
});
documentsMain.webodfServerInstance.setToken(oc_requesttoken); documentsMain.webodfServerInstance.setToken(oc_requesttoken);
documentsMain.webodfEditorInstance = new Editor( documentsMain.webodfEditorInstance = new Editor(
{ {
@ -383,9 +392,9 @@ var documentsMain = {
console.log('joining session '+fileId); console.log('joining session '+fileId);
var url; var url;
if (documentsMain.isGuest){ if (documentsMain.isGuest){
url = OC.generateUrl('apps/documents/ajax/session/joinasguest/{token}', {token: fileId}); url = OC.generateUrl('apps/documents/session/guest/join/{token}', {token: fileId});
} else { } else {
url = OC.generateUrl('apps/documents/ajax/session/joinasuser/{file_id}', {file_id: fileId}); url = OC.generateUrl('apps/documents/session/user/join/{file_id}', {file_id: fileId});
} }
$.post( $.post(
url, url,

@ -49,12 +49,7 @@ class Session extends \OCA\Documents\Db {
public static function start($uid, $file){ public static function start($uid, $file){
// Create a directory to store genesis // Create a directory to store genesis
$genesis = new \OCA\Documents\Genesis($file); $genesis = new \OCA\Documents\Genesis($file);
list($ownerView, $path) = $file->getOwnerViewAndPath();
$mimetype = $ownerView->getMimeType($path);
if (!Filter::isSupportedMimetype($mimetype)){
throw new \Exception( $path . ' is ' . $mimetype . ' and is not supported by Documents app');
}
$oldSession = new Session(); $oldSession = new Session();
$oldSession->loadBy('file_id', $file->getFileId()); $oldSession->loadBy('file_id', $file->getFileId());
@ -78,14 +73,14 @@ class Session extends \OCA\Documents\Db {
; ;
$memberColor = \OCA\Documents\Helper::getMemberColor($uid); $memberColor = \OCA\Documents\Helper::getMemberColor($uid);
$member = new \OCA\Documents\Db\Member(array( $member = new \OCA\Documents\Db\Member([
$sessionData['es_id'], $sessionData['es_id'],
$uid, $uid,
$memberColor, $memberColor,
time(), time(),
intval($file->isPublicShare()), intval($file->isPublicShare()),
$file->getToken() $file->getToken()
)); ]);
if (!$member->insert()){ if (!$member->insert()){
throw new \Exception('Failed to add member into database'); throw new \Exception('Failed to add member into database');
@ -113,10 +108,9 @@ class Session extends \OCA\Documents\Db {
$memberColor, $memberColor,
$imageUrl $imageUrl
); );
$sessionData['title'] = basename($path); $sessionData['title'] = basename($file->getPath());
$fileInfo = $ownerView->getFileInfo($path); $sessionData['permissions'] = $file->getPermissions();
$sessionData['permissions'] = $fileInfo->getPermissions();
return $sessionData; return $sessionData;
} }

@ -28,14 +28,14 @@ class File {
protected $fileId; protected $fileId;
protected $owner; protected $owner;
protected $sharing; protected $sharing;
protected $token =''; protected $token;
protected $passwordProtected = false; protected $passwordProtected = false;
protected $ownerView; protected $ownerView;
protected $ownerViewFiles; protected $ownerViewFiles;
protected $path; protected $path;
protected $pathFiles; protected $pathFiles;
public function __construct($fileId, $shareOps = null, $token = null){ public function __construct($fileId, $shareOps = null, $token = ''){
if (!$fileId){ if (!$fileId){
throw new \Exception('No valid file has been passed'); throw new \Exception('No valid file has been passed');
} }
@ -43,6 +43,22 @@ class File {
$this->fileId = $fileId; $this->fileId = $fileId;
$this->sharing = $shareOps; $this->sharing = $shareOps;
$this->token = $token; $this->token = $token;
if ($this->isPublicShare()) {
if (isset($this->sharing['uid_owner'])){
$this->owner = $this->sharing['uid_owner'];
if (!\OC::$server->getUserManager()->userExists($this->sharing['uid_owner'])) {
throw new \Exception('Share owner' . $this->sharing['uid_owner'] . ' does not exist ');
}
\OC_Util::tearDownFS();
\OC_Util::setupFS($this->sharing['uid_owner']);
} else {
throw new \Exception($this->fileId . ' is a broken share');
}
} else {
$this->owner = \OC::$server->getUserSession()->getUser()->getUID();
}
$this->initViews(); $this->initViews();
} }
@ -131,15 +147,6 @@ class File {
public function setPasswordProtected($value){ public function setPasswordProtected($value){
$this->passwordProtected = $value; $this->passwordProtected = $value;
} }
/**
*
* @return string owner of the current file item
* @throws \Exception
*/
public function getOwnerViewAndPath($useDefaultRoot = false){
return $useDefaultRoot ? [$this->ownerViewFiles, $this->pathFiles] : [$this->ownerView, $this->path];
}
public function getOwner(){ public function getOwner(){
return $this->owner; return $this->owner;
@ -153,23 +160,12 @@ class File {
return $relativeToFiles ? $this->pathFiles : $this->path; return $relativeToFiles ? $this->pathFiles : $this->path;
} }
public function getPermissions(){
$fileInfo = $this->ownerView->getFileInfo($this->path);
return $fileInfo->getPermissions();
}
protected function initViews(){ protected function initViews(){
if ($this->isPublicShare()) {
if (isset($this->sharing['uid_owner'])){
$this->owner = $this->sharing['uid_owner'];
if (!\OC::$server->getUserManager()->userExists($this->sharing['uid_owner'])) {
throw new \Exception('Share owner' . $this->sharing['uid_owner'] . ' does not exist ');
}
\OC_Util::tearDownFS();
\OC_Util::setupFS($this->sharing['uid_owner']);
} else {
throw new \Exception($this->fileId . ' is a broken share');
}
} else {
$this->owner = \OC::$server->getUserSession()->getUser()->getUID();
}
$this->ownerView = new View('/' . $this->owner); $this->ownerView = new View('/' . $this->owner);
$this->ownerViewFiles = new View('/' . $this->owner . '/files'); $this->ownerViewFiles = new View('/' . $this->owner . '/files');
$this->path = $this->ownerView->getPath($this->fileId); $this->path = $this->ownerView->getPath($this->fileId);
@ -186,6 +182,16 @@ class File {
if (!$this->ownerViewFiles->file_exists($this->pathFiles)) { if (!$this->ownerViewFiles->file_exists($this->pathFiles)) {
throw new \Exception($this->pathFiles . ' doesn\'t exist'); throw new \Exception($this->pathFiles . ' doesn\'t exist');
} }
if (!$this->ownerView->is_file($this->path)){
throw new \Exception('Object ' . $this->path . ' is not a file.');
}
//TODO check if it is a valid odt
$mimetype = $this->ownerView->getMimeType($this->path);
if (!Filter::isSupportedMimetype($mimetype)){
throw new \Exception( $this->path . ' is ' . $mimetype . ' and is not supported by Documents app');
}
} }
protected function getPassword(){ protected function getPassword(){

@ -40,7 +40,8 @@ class Genesis {
* @param File $file * @param File $file
* */ * */
public function __construct(File $file){ public function __construct(File $file){
list($view, $path) = $file->getOwnerViewAndPath(); $view = $file->getOwnerView();
$path = $file->getPath();
$owner = $file->getOwner(); $owner = $file->getOwner();
$this->view = new View('/' . $owner); $this->view = new View('/' . $owner);
@ -48,8 +49,9 @@ class Genesis {
if (!$this->view->file_exists(self::DOCUMENTS_DIRNAME)){ if (!$this->view->file_exists(self::DOCUMENTS_DIRNAME)){
$this->view->mkdir(self::DOCUMENTS_DIRNAME ); $this->view->mkdir(self::DOCUMENTS_DIRNAME );
} }
$this->validate($view, $path);
$this->hash = $this->getDocumentHash($view, $path); $this->hash = $view->hash('sha1', $path, false);
$this->path = self::DOCUMENTS_DIRNAME . '/' . $this->hash . '.odt'; $this->path = self::DOCUMENTS_DIRNAME . '/' . $this->hash . '.odt';
if (!$this->view->file_exists($this->path)){ if (!$this->view->file_exists($this->path)){
//copy new genesis to /user/documents/{hash}.odt //copy new genesis to /user/documents/{hash}.odt
@ -76,12 +78,6 @@ class Genesis {
return $this->hash; return $this->hash;
} }
protected function getDocumentHash($view, $path){
$this->validate($view, $path);
$hash = sha1($view->file_get_contents($path));
return $hash;
}
/** /**
* Check if genesis is valid * Check if genesis is valid
* @param \OC\Files\View $view * @param \OC\Files\View $view

Loading…
Cancel
Save