Use SQL transactions during sync
[grauphel.git] / controller / apicontroller.php
1 <?php
2 /**
3  * Part of grauphel
4  *
5  * PHP version 5
6  *
7  * @category  Tools
8  * @package   Grauphel
9  * @author    Christian Weiske <cweiske@cweiske.de>
10  * @copyright 2014 Christian Weiske
11  * @license   http://www.gnu.org/licenses/agpl.html GNU AGPL v3
12  * @link      http://cweiske.de/grauphel.htm
13  */
14 namespace OCA\Grauphel\Controller;
15
16 use \OCP\AppFramework\Controller;
17 use \OCP\AppFramework\Http\JSONResponse;
18
19 use \OCA\Grauphel\Lib\Client;
20 use \OCA\Grauphel\Lib\NoteStorage;
21 use \OCA\Grauphel\Lib\OAuth;
22 use \OCA\Grauphel\Lib\OAuthException;
23 use \OCA\Grauphel\Lib\Dependencies;
24 use \OCA\Grauphel\Lib\Response\ErrorResponse;
25
26 /**
27  * Tomboy's REST API
28  *
29  * @category  Tools
30  * @package   Grauphel
31  * @author    Christian Weiske <cweiske@cweiske.de>
32  * @copyright 2014 Christian Weiske
33  * @license   http://www.gnu.org/licenses/agpl.html GNU AGPL v3
34  * @version   Release: @package_version@
35  * @link      http://cweiske.de/grauphel.htm
36  */
37 class ApiController extends Controller
38 {
39     /**
40      * constructor of the controller
41      *
42      * @param string   $appName Name of the app
43      * @param IRequest $request Instance of the request
44      */
45     public function __construct($appName, \OCP\IRequest $request, $user)
46     {
47         parent::__construct($appName, $request);
48         $this->user  = $user;
49         $this->deps  = Dependencies::get();
50         $this->notes = new NoteStorage($this->deps->urlGen);
51
52         //default http header: we assume something is broken
53         header('HTTP/1.0 500 Internal Server Error');
54     }
55
56     /**
57      * /api/1.0
58      *
59      * @NoAdminRequired
60      * @NoCSRFRequired
61      * @PublicPage
62      */
63     public function index($route = 'grauphel.api.index')
64     {
65         $deps = Dependencies::get();
66         $authenticated = false;
67         $oauth = new OAuth();
68         $oauth->setDeps($deps);
69         $urlGen = $deps->urlGen;
70
71         try {
72             $provider = OAuth::getProvider();
73             $oauth->registerHandler($provider)
74                 ->registerAccessTokenHandler($provider);
75             $provider->checkOAuthRequest(
76                 $urlGen->getAbsoluteURL(
77                     $urlGen->linkToRoute($route)
78                 )
79             );
80             $authenticated = true;
81             $token = $deps->tokens->load('access', $provider->token);
82             $username = $token->user;
83
84         } catch (OAuthException $e) {
85             return new ErrorResponse($e->getMessage());
86         } catch (\OAuthException $e) {
87             if ($e->getCode() != OAUTH_PARAMETER_ABSENT) {
88                 $oauth->error($e);
89             }
90             if ($this->user !== null) {
91                 $username = $this->user->getUID();
92                 $authenticated = true;
93             }
94         }
95
96         $data = array(
97             'oauth_request_token_url' => $urlGen->getAbsoluteURL(
98                 $urlGen->linkToRoute('grauphel.oauth.requestToken')
99             ),
100             'oauth_authorize_url'     => $urlGen->getAbsoluteURL(
101                 $urlGen->linkToRoute('grauphel.oauth.authorize')
102             ),
103             'oauth_access_token_url'  => $urlGen->getAbsoluteURL(
104                 $urlGen->linkToRoute('grauphel.oauth.accessToken')
105             ),
106             'api-version' => '1.0',
107         );
108
109         $cl = new Client();
110         $client = $cl->getClient();
111         if ($client !== false) {
112             $data['oauth_authorize_url'] .= '?client=' . urlencode($client);
113         }
114
115         if ($authenticated) {
116             $data['user-ref'] = array(
117                 'api-ref' => $urlGen->getAbsoluteURL(
118                     $urlGen->linkToRoute(
119                         'grauphel.api.user', array('username' => $username)
120                     )
121                 ),
122                 'href' => null,//FIXME
123             );
124         }
125
126         return new JSONResponse($data);
127     }
128
129     /**
130      * /api/1.0/
131      *
132      * @NoAdminRequired
133      * @NoCSRFRequired
134      * @PublicPage
135      */
136     public function indexSlash()
137     {
138         return $this->index('grauphel.api.indexSlash');
139     }
140
141     /**
142      * GET /api/1.0/$user
143      *
144      * @NoAdminRequired
145      * @NoCSRFRequired
146      * @PublicPage
147      */
148     public function user($username)
149     {
150         $this->verifyUser(
151             $username,
152             $this->deps->urlGen->getAbsoluteURL(
153                 $this->deps->urlGen->linkToRoute(
154                     'grauphel.api.user', array('username' => $username)
155                 )
156             )
157         );
158         $syncdata = $this->notes->loadSyncData();
159
160         $data = array(
161             'user-name'  => $username,
162             'first-name' => null,
163             'last-name'  => null,
164             'notes-ref'  => array(
165                 'api-ref' => $this->deps->urlGen->getAbsoluteURL(
166                     $this->deps->urlGen->linkToRoute(
167                         'grauphel.api.notes', array('username' => $username)
168                     )
169                 ),
170                 'href'    => null,
171             ),
172             'latest-sync-revision' => $syncdata->latestSyncRevision,
173             'current-sync-guid'    => $syncdata->currentSyncGuid,
174         );
175         return new JSONResponse($data);
176     }
177
178     /**
179      * GET /api/1.0/$user/notes
180      *
181      * @NoAdminRequired
182      * @NoCSRFRequired
183      * @PublicPage
184      */
185     public function notes($username)
186     {
187         $this->verifyUser(
188             $username,
189             $this->deps->urlGen->getAbsoluteURL(
190                 $this->deps->urlGen->linkToRoute(
191                     'grauphel.api.notes', array('username' => $username)
192                 )
193             )
194         );
195         $syncdata = $this->notes->loadSyncData();
196         return $this->fetchNotes($syncdata);
197     }
198
199     /**
200      * PUT /api/1.0/$user/notes
201      *
202      * @NoAdminRequired
203      * @NoCSRFRequired
204      * @PublicPage
205      */
206     public function notesSave($username)
207     {
208         $this->verifyUser(
209             $username,
210             $this->deps->urlGen->getAbsoluteURL(
211                 $this->deps->urlGen->linkToRoute(
212                     'grauphel.api.notesSave', array('username' => $username)
213                 )
214             )
215         );
216         $syncdata = $this->notes->loadSyncData();
217
218         $res = $this->handleNoteSave($username, $syncdata);
219         if ($res instanceof \OCP\AppFramework\Http\Response) {
220             return $res;
221         }
222
223         return $this->fetchNotes($syncdata);
224     }
225
226     protected function fetchNotes($syncdata)
227     {
228         $since = null;
229         if (isset($_GET['since'])) {
230             $since = (int) $_GET['since'];
231         }
232
233         if (isset($_GET['include_notes']) && $_GET['include_notes']) {
234             $notes = $this->notes->loadNotesFull($since);
235         } else {
236             $notes = $this->notes->loadNotesOverview($since);
237         }
238
239         //work around bug https://bugzilla.gnome.org/show_bug.cgi?id=734313
240         foreach ($notes as $note) {
241             if (isset($note->{'note-content-version'})) {
242                 $note->{'note-content-version'} = 0.3;
243             }
244         }
245
246         $data = array(
247             'latest-sync-revision' => $syncdata->latestSyncRevision,
248             'notes' => $notes,
249         );
250         return new JSONResponse($data);
251     }
252
253     protected function handleNoteSave($username, $syncdata)
254     {
255         if ($_SERVER['REQUEST_METHOD'] != 'PUT') {
256             return;
257         }
258
259         //Note that we have more data in $arPut than just our JSON.
260         // The request object merges it with other data.
261         $arPut = $this->request->put;
262
263         //structural validation
264         if (!isset($arPut['latest-sync-revision'])) {
265             return new ErrorResponse('Missing "latest-sync-revision"');
266         }
267         if (!isset($arPut['note-changes'])) {
268             return new ErrorResponse('Missing "note-changes"');
269         }
270         foreach ($arPut['note-changes'] as $note) {
271             //owncloud converts object to array, so we reverse
272             $note = (object) $note;
273             if (!isset($note->guid) || $note->guid == '') {
274                 return new ErrorResponse('Missing "guid" on note');
275             }
276         }
277
278         //content validation
279         if ($arPut['latest-sync-revision'] != $syncdata->latestSyncRevision +1
280             && $syncdata->latestSyncRevision != -1
281         ) {
282             return new ErrorResponse(
283                 'Wrong "latest-sync-revision". You are not up to date.'
284             );
285         }
286
287         //update
288         \OC_DB::beginTransaction();
289         try {
290             ++$syncdata->latestSyncRevision;
291             foreach ($arPut['note-changes'] as $noteUpdate) {
292                 //owncloud converts object to array, so we reverse
293                 $noteUpdate = (object) $noteUpdate;
294
295                 $note = $this->notes->load($noteUpdate->guid);
296                 if (isset($noteUpdate->command) && $noteUpdate->command == 'delete') {
297                     $this->notes->delete($noteUpdate->guid);
298                 } else {
299                     $this->notes->update(
300                         $note, $noteUpdate, $syncdata->latestSyncRevision
301                     );
302                     $this->notes->save($note);
303                 }
304             }
305
306             $this->notes->saveSyncData($syncdata);
307             \OC_DB::commit();
308         } catch (\DatabaseException $e) {
309             \OC_DB::getConnection()->rollBack();
310             throw $e;
311         }
312     }
313
314     /**
315      * GET /api/1.0/$user/notes/$noteguid
316      *
317      * @NoAdminRequired
318      * @NoCSRFRequired
319      * @PublicPage
320      */
321     public function note($username, $guid)
322     {
323         $this->verifyUser(
324             $username,
325             $this->deps->urlGen->getAbsoluteURL(
326                 $this->deps->urlGen->linkToRoute(
327                     'grauphel.api.note',
328                     array('username' => $username, 'guid' => $guid)
329                 )
330             )
331         );
332
333         $note = $this->notes->load($guid, false);
334         if ($note === null) {
335             header('HTTP/1.0 404 Not Found');
336             header('Content-type: text/plain');
337             echo "Note does not exist\n";
338             exit(1);
339         }
340
341         return new JSONResponse($note);
342     }
343
344     /**
345      * Checks if the given user is authorized (by oauth token or normal login)
346      *
347      * @param string $username Username to verify
348      *
349      * @return boolean True if all is fine, Response in case of an error
350      */
351     protected function verifyUser($username, $curUrl)
352     {
353         if ($this->user !== null && $this->user->getUid() == $username) {
354             $this->notes->setUsername($username);
355             return true;
356         }
357
358         $oauth = new OAuth();
359         $oauth->setDeps($this->deps);
360         $oauth->verifyOAuthUser($username, $curUrl);
361
362         $this->notes->setUsername($username);
363         return true;
364     }
365 }
366 ?>