standlone HTML output
[grauphel.git] / controller / apicontroller.php
index 166436e..90c036f 100644 (file)
@@ -16,9 +16,12 @@ namespace OCA\Grauphel\Controller;
 use \OCP\AppFramework\Controller;
 use \OCP\AppFramework\Http\JSONResponse;
 
+use \OCA\Grauphel\Lib\Client;
 use \OCA\Grauphel\Lib\NoteStorage;
 use \OCA\Grauphel\Lib\OAuth;
+use \OCA\Grauphel\Lib\OAuthException;
 use \OCA\Grauphel\Lib\Dependencies;
+use \OCA\Grauphel\Lib\Response\ErrorResponse;
 
 /**
  * Tomboy's REST API
@@ -33,13 +36,13 @@ use \OCA\Grauphel\Lib\Dependencies;
  */
 class ApiController extends Controller
 {
-       /**
-        * constructor of the controller
+    /**
+     * constructor of the controller
      *
-        * @param string   $appName Name of the app
-        * @param IRequest $request Instance of the request
-        */
-       public function __construct($appName, \OCP\IRequest $request, $user)
+     * @param string   $appName Name of the app
+     * @param IRequest $request Instance of the request
+     */
+    public function __construct($appName, \OCP\IRequest $request, $user)
     {
         parent::__construct($appName, $request);
         $this->user  = $user;
@@ -66,7 +69,7 @@ class ApiController extends Controller
         $urlGen = $deps->urlGen;
 
         try {
-            $provider = new \OAuthProvider();
+            $provider = OAuth::getProvider();
             $oauth->registerHandler($provider)
                 ->registerAccessTokenHandler($provider);
             $provider->checkOAuthRequest(
@@ -78,8 +81,8 @@ class ApiController extends Controller
             $token = $deps->tokens->load('access', $provider->token);
             $username = $token->user;
 
-        } catch (\OAuth_Exception $e) {
-            $deps->renderer->errorOut($e->getMessage());
+        } catch (OAuthException $e) {
+            return new ErrorResponse($e->getMessage());
         } catch (\OAuthException $e) {
             if ($e->getCode() != OAUTH_PARAMETER_ABSENT) {
                 $oauth->error($e);
@@ -103,6 +106,12 @@ class ApiController extends Controller
             'api-version' => '1.0',
         );
 
+        $cl = new Client();
+        $client = $cl->getClient();
+        if ($client !== false) {
+            $data['oauth_authorize_url'] .= '?client=' . urlencode($client);
+        }
+
         if ($authenticated) {
             $data['user-ref'] = array(
                 'api-ref' => $urlGen->getAbsoluteURL(
@@ -110,7 +119,7 @@ class ApiController extends Controller
                         'grauphel.api.user', array('username' => $username)
                     )
                 ),
-                'href' => null,//FIXME
+                'href' => null,
             );
         }
 
@@ -138,8 +147,15 @@ class ApiController extends Controller
      */
     public function user($username)
     {
-        $this->verifyUser($username);
-        $syncdata = $this->notes->loadSyncData($username);
+        $this->verifyUser(
+            $username,
+            $this->deps->urlGen->getAbsoluteURL(
+                $this->deps->urlGen->linkToRoute(
+                    'grauphel.api.user', array('username' => $username)
+                )
+            )
+        );
+        $syncdata = $this->notes->loadSyncData();
 
         $data = array(
             'user-name'  => $username,
@@ -151,7 +167,9 @@ class ApiController extends Controller
                         'grauphel.api.notes', array('username' => $username)
                     )
                 ),
-                'href'    => null,
+                'href'    => $this->deps->urlGen->getAbsoluteURL(
+                    $this->deps->urlGen->linkToRoute('grauphel.gui.index')
+                ),
             ),
             'latest-sync-revision' => $syncdata->latestSyncRevision,
             'current-sync-guid'    => $syncdata->currentSyncGuid,
@@ -176,8 +194,8 @@ class ApiController extends Controller
                 )
             )
         );
-        $syncdata = $this->notes->loadSyncData($username);
-        return $this->fetchNotes($username, $syncdata);
+        $syncdata = $this->notes->loadSyncData();
+        return $this->fetchNotes($syncdata);
     }
 
     /**
@@ -193,18 +211,21 @@ class ApiController extends Controller
             $username,
             $this->deps->urlGen->getAbsoluteURL(
                 $this->deps->urlGen->linkToRoute(
-                    'grauphel.api.user', array('username' => $username)
+                    'grauphel.api.notesSave', array('username' => $username)
                 )
             )
         );
-        $syncdata = $this->notes->loadSyncData($username);
-        
-        $this->handleNoteSave($username, $syncdata);
+        $syncdata = $this->notes->loadSyncData();
+
+        $res = $this->handleNoteSave($username, $syncdata);
+        if ($res instanceof \OCP\AppFramework\Http\Response) {
+            return $res;
+        }
 
-        return $this->fetchNotes($username, $syncdata);
+        return $this->fetchNotes($syncdata);
     }
 
-    protected function fetchNotes($username, $syncdata)
+    protected function fetchNotes($syncdata)
     {
         $since = null;
         if (isset($_GET['since'])) {
@@ -212,9 +233,9 @@ class ApiController extends Controller
         }
 
         if (isset($_GET['include_notes']) && $_GET['include_notes']) {
-            $notes = $this->notes->loadNotesFull($username, $since);
+            $notes = $this->notes->loadNotesFull($since);
         } else {
-            $notes = $this->notes->loadNotesOverview($username, $since);
+            $notes = $this->notes->loadNotesOverview($since);
         }
 
         //work around bug https://bugzilla.gnome.org/show_bug.cgi?id=734313
@@ -237,48 +258,59 @@ class ApiController extends Controller
             return;
         }
 
-        $data = file_get_contents('php://input');
-        $putObj = json_decode($data);
-        if ($putObj === NULL) {
-            errorOut('Invalid JSON data in PUT request');
-        }
+        //Note that we have more data in $arPut than just our JSON.
+        // The request object merges it with other data.
+        $arPut = $this->request->put;
 
         //structural validation
-        if (!isset($putObj->{'latest-sync-revision'})) {
-            errorOut('Missing "latest-sync-revision"');
+        if (!isset($arPut['latest-sync-revision'])) {
+            return new ErrorResponse('Missing "latest-sync-revision"');
         }
-        if (!isset($putObj->{'note-changes'})) {
-            errorOut('Missing "note-changes"');
+        if (!isset($arPut['note-changes'])) {
+            return new ErrorResponse('Missing "note-changes"');
         }
-        foreach ($putObj->{'note-changes'} as $note) {
+        foreach ($arPut['note-changes'] as $note) {
+            //owncloud converts object to array, so we reverse
+            $note = (object) $note;
             if (!isset($note->guid) || $note->guid == '') {
-                errorOut('Missing "guid" on note');
+                return new ErrorResponse('Missing "guid" on note');
             }
         }
 
         //content validation
-        if ($putObj->{'latest-sync-revision'} != $syncdata->latestSyncRevision +1
+        if ($arPut['latest-sync-revision'] != $syncdata->latestSyncRevision +1
             && $syncdata->latestSyncRevision != -1
         ) {
-            errorOut('Wrong "latest-sync-revision". You are not up to date.');
+            return new ErrorResponse(
+                'Wrong "latest-sync-revision". You are not up to date.'
+            );
         }
 
         //update
-        $deps = Dependencies::get();
-        ++$syncdata->latestSyncRevision;
-        foreach ($putObj->{'note-changes'} as $noteUpdate) {
-            $note = $deps->notes->load($username, $noteUpdate->guid);
-            if (isset($noteUpdate->command) && $noteUpdate->command == 'delete') {
-                $deps->notes->delete($username, $noteUpdate->guid);
-            } else {
-                $deps->notes->update(
-                    $note, $noteUpdate, $syncdata->latestSyncRevision
-                );
-                $deps->notes->save($username, $note);
+        \OC_DB::beginTransaction();
+        try {
+            ++$syncdata->latestSyncRevision;
+            foreach ($arPut['note-changes'] as $noteUpdate) {
+                //owncloud converts object to array, so we reverse
+                $noteUpdate = (object) $noteUpdate;
+
+                $note = $this->notes->load($noteUpdate->guid);
+                if (isset($noteUpdate->command) && $noteUpdate->command == 'delete') {
+                    $this->notes->delete($noteUpdate->guid);
+                } else {
+                    $this->notes->update(
+                        $note, $noteUpdate, $syncdata->latestSyncRevision
+                    );
+                    $this->notes->save($note);
+                }
             }
-        }
 
-        $deps->notes->saveSyncData($username, $syncdata);
+            $this->notes->saveSyncData($syncdata);
+            \OC_DB::commit();
+        } catch (\DatabaseException $e) {
+            \OC_DB::getConnection()->rollBack();
+            throw $e;
+        }
     }
 
     /**
@@ -288,17 +320,19 @@ class ApiController extends Controller
      * @NoCSRFRequired
      * @PublicPage
      */
-    public function note()
+    public function note($username, $guid)
     {
-        //FIXME
-        $deps = Dependencies::get();
-        $username = $deps->urlGen->loadUsername();
-        $guid     = $deps->urlGen->loadGuid();
-        $oauth = new \OAuth();
-        $oauth->setDeps($deps);
-        $oauth->verifyOAuthUser($username, $deps->urlGen->note($username, $guid));
+        $this->verifyUser(
+            $username,
+            $this->deps->urlGen->getAbsoluteURL(
+                $this->deps->urlGen->linkToRoute(
+                    'grauphel.api.note',
+                    array('username' => $username, 'guid' => $guid)
+                )
+            )
+        );
 
-        $note = $deps->notes->load($username, $guid, false);
+        $note = $this->notes->load($guid, false);
         if ($note === null) {
             header('HTTP/1.0 404 Not Found');
             header('Content-type: text/plain');
@@ -306,8 +340,7 @@ class ApiController extends Controller
             exit(1);
         }
 
-        $data = array('note' => array($note));
-        $deps->renderer->sendJson($data);
+        return new JSONResponse($note);
     }
 
     /**
@@ -319,13 +352,17 @@ class ApiController extends Controller
      */
     protected function verifyUser($username, $curUrl)
     {
-        if ($this->user !== null && $this->user->getUID() == $username) {
+        if ($this->user !== null && $this->user->getUid() == $username) {
+            $this->notes->setUsername($username);
             return true;
         }
 
         $oauth = new OAuth();
         $oauth->setDeps($this->deps);
         $oauth->verifyOAuthUser($username, $curUrl);
+
+        $this->notes->setUsername($username);
+        return true;
     }
 }
 ?>