Completed
Pull Request — master (#14)
by Piotr
01:21
created

PaperHiveController::getBookIdforPath()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 4
nc 3
nop 2
1
<?php
2
/**
3
 * @author Piotr Mrowczynski <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2018, Piotr Mrowczynski.
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace OCA\Files_PaperHive\Controller;
23
24
use OCA\Files_PaperHive\PaperHiveMetadata;
25
use OCP\Http\Client\IClient;
26
use OC\Files\View;
27
use OCP\AppFramework\Controller;
28
use OCP\AppFramework\Http;
29
use OCP\AppFramework\Http\DataResponse;
30
use OCP\Files\ForbiddenException;
31
use OCP\IL10N;
32
use OCP\ILogger;
33
use OCP\IRequest;
34
use OCP\Lock\LockedException;
35
36
class PaperHiveController extends Controller {
37
38
	/** @var IL10N */
39
	private $l;
40
41
	/** @var View */
42
	private $view;
43
44
	/** @var ILogger */
45
	private $logger;
46
47
	/** @var \OCP\Http\Client\IClient */
48
	private $client;
49
50
	/** @var PaperHiveMetadata */
51
	private $paperHiveMetadata;
52
53
	/**
54
	 * Paperhive base URL
55
	 */
56
	private $paperhive_base_url = 'https://paperhive.org';
57
58
	/**
59
	 * Paperhive url for document API
60
	 */
61
	private $paperhive_api_documents = '/api/document-items/';
62
63
	/**
64
	 * Paperhive url for discussions API
65
	 */
66
	private $paperhive_api_discussions = '/api/discussions?documentItem=';
67
68
	/**
69
	 * Paperhive url for document text in browser
70
	 */
71
	private $paperhive_base_document_url = '/documents/items/';
72
73
	/**
74
	 * Paperhive file extension
75
	 */
76
	private $paperhive_file_extension = '.paperhive';
77
78
	/**
79
	 * Paperhive BookID example
80
	 */
81
	private $paperhive_bookid_example = 'ZYY0r21rJbqr';
82
83
	/**
84
	 * @NoAdminRequired
85
	 *
86
	 * @param string $AppName
87
	 * @param IRequest $request
88
	 * @param IL10N $l10n
89
	 * @param View $view
90
	 * @param ILogger $logger
91
	 * @param IClient $client
92
	 * @param PaperHiveMetadata $paperHiveMetadata
93
	 */
94
	public function __construct($AppName,
95
								IRequest $request,
96
								IL10N $l10n,
97
								View $view,
98
								ILogger $logger,
99
								IClient $client,
100
								PaperHiveMetadata $paperHiveMetadata) {
101
		parent::__construct($AppName, $request);
102
		$this->l = $l10n;
103
		$this->view = $view;
104
		$this->logger = $logger;
105
		$this->client = $client;
106
		$this->paperHiveMetadata = $paperHiveMetadata;
107
	}
108
109
	/**
110
	 * Get URL to PaperHive book url
111
	 *
112
	 * @NoAdminRequired
113
	 *
114
	 * @param string $dir
115
	 * @param string $filename
116
	 * @return DataResponse
117
	 */
118
	public function getPaperHiveBookURL($dir, $filename) {
119
		try {
120
			$bookId = $this->getBookIdforPath($dir, $filename);
121
			return new DataResponse($this->paperhive_base_url . $this->paperhive_base_document_url . $bookId, Http::STATUS_OK);
122
		} catch (\Exception $e) {
123
			$message = (string)$this->l->t('An internal server error occurred.');
124
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
125
		}
126
	}
127
128
	/**
129
	 * Get URL to PaperHive book discussion count
130
	 *
131
	 * @NoAdminRequired
132
	 *
133
	 * @param string $dir
134
	 * @param string $filename
135
	 * @return DataResponse
136
	 */
137
	public function getPaperHiveBookDiscussionCount($dir, $filename) {
138
		try {
139
			$bookId = $this->getBookIdforPath($dir, $filename);
140
			$paperHiveString = $this->fetchDiscussions($bookId);
141
			$paperHiveDiscussions = json_decode($paperHiveString, true);
142
			$disscussionCount = -1;
143 View Code Duplication
			if (json_last_error() === JSON_ERROR_NONE && isset($paperHiveDiscussions['discussions'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
144
				$disscussionCount = count($paperHiveDiscussions['discussions']);
145
			}
146
			return new DataResponse($disscussionCount, Http::STATUS_OK);
147
		} catch (\Exception $e) {
148
			$message = (string)$this->l->t('An internal server error occurred.');
149
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
150
		}
151
	}
152
153
	private function getBookIdforPath($dir, $filename){
154
		if (!empty($filename)) {
155
			$path = $dir . '/' . $filename;
156
157
			$fileInfo = $this->view->getFileInfo($path);
158
			if($fileInfo && $bookId = $this->paperHiveMetadata->getBookID($fileInfo['fileid'])) {
159
				return $bookId;
160
			}
161
		}
162
		return false;
163
	}
164
165
	/**
166
	 * Does the call to PaperHive Discussions API and returns disussions for specific it for specific BookID
167
	 *
168
	 * @NoAdminRequired
169
	 *
170
	 * @param string $bookID
171
	 * @return string
172
	 */
173 View Code Duplication
	private function fetchDiscussions($bookID) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
174
		$urlDiscussions = $this->paperhive_base_url . $this->paperhive_api_discussions . $bookID;
175
		try {
176
			$response = $this->client->get($urlDiscussions, []);
177
		} catch (\Exception $e) {
178
			return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by OCA\Files_PaperHive\Cont...oller::fetchDiscussions of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
179
		}
180
		return $response->getBody();
181
	}
182
183
	/**
184
	 * Does the call to PaperHive Documents API and returns the JSON for a book for specific BookID
185
	 *
186
	 * @NoAdminRequired
187
	 *
188
	 * @param string $bookID
189
	 * @return string/boolean
0 ignored issues
show
Documentation introduced by
The doc-type string/boolean could not be parsed: Unknown type name "string/boolean" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
190
	 */
191 View Code Duplication
	private function fetchDocument($bookID) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
192
		$urlDocument = $this->paperhive_base_url . $this->paperhive_api_documents . $bookID;
193
		try {
194
			$response = $this->client->get($urlDocument, []);
195
		} catch (\Exception $e) {
196
			return false;
197
		}
198
		return $response->getBody();
199
	}
200
201
	/**
202
	 * Gets the informations about the book for specific BookID and saves as a file
203
	 *
204
	 * @NoAdminRequired
205
	 *
206
	 * @param string $dir
207
	 * @param string $bookID
208
	 * @return DataResponse
209
	 */
210
	public function generatePaperHiveDocument($dir, $bookID) {
211
		// Try to get the document
212
		$paperHiveObjectString = $this->fetchDocument($bookID);
213 View Code Duplication
		if ($paperHiveObjectString === false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
214
			$message = (string)$this->l->t('Problem connecting to PaperHive.');
215
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
216
		}
217
		$paperHiveObject = json_decode($paperHiveObjectString, true);
218
219
		// Check if correct response has been returned
220 View Code Duplication
		if (json_last_error() != JSON_ERROR_NONE) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
221
			$message = (string)$this->l->t('Received wrong response from PaperHive.');
222
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
223
		}
224
225
		// Check if document is found
226
		if (!(isset($paperHiveObject['metadata']) && isset($paperHiveObject['metadata']['title']))) {
227
			$message = (string)$this->l->t('Document with this BookID cannot be found');
228
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
229
		}
230
231
		// Try fetching discussions
232
		$paperHiveDiscussionsString = $this->fetchDiscussions($bookID);
233 View Code Duplication
		if ($paperHiveDiscussionsString === false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
234
			$message = (string)$this->l->t('Problem connecting to PaperHive.');
235
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
236
		}
237
		$paperHiveDiscussions = json_decode($paperHiveDiscussionsString, true);
238
		$discussionCount = -1;
239 View Code Duplication
		if (json_last_error() === JSON_ERROR_NONE && isset($paperHiveDiscussions['discussions'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
240
			$discussionCount = count($paperHiveDiscussions['discussions']);
241
		}
242
243
		// Save the file
244
		$title = $paperHiveObject['metadata']['title'];
245
		$filename = $title . $this->paperhive_file_extension;
246
		if($dir == '/') {
247
			$path = $dir . $filename;
248
		} else {
249
			$path = $dir . '/' . $filename;
250
		}
251
252
		$exists = $this->view->file_exists($path);
253 View Code Duplication
		if ($exists) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
254
			$message = (string) $this->l->t('The file already exists.');
255
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
256
		}
257
258
		try {
259
			$created = $this->view->touch($path);
260 View Code Duplication
			if(!$created) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
261
				$message = (string) $this->l->t('Could not save document.');
262
				return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
263
			}
264
265
			$fileInfo = $this->view->getFileInfo($path);
266
			$inserted = $this->paperHiveMetadata->insertBookID($fileInfo['fileid'], $bookID);
267 View Code Duplication
			if(!$inserted) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
268
				$this->view->unlink($path);
269
				$message = (string) $this->l->t('Could not save document metadata.');
270
				return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
271
			}
272
		} catch (LockedException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Lock\LockedException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
273
			$message = (string) $this->l->t('The file is locked.');
274
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
275
		} catch (ForbiddenException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\ForbiddenException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
276
			return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
277
		} catch (\Exception $e) {
278
			$message = (string)$this->l->t('An internal server error occurred.');
279
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
280
		}
281
282
		return new DataResponse(['path' => $path, 'filename' => $title, 'extension' => $this->paperhive_file_extension, 'discussionCount' => $discussionCount], Http::STATUS_OK);
283
	}
284
285
	/**
286
	 * Returns all required PaperHive setting
287
	 *
288
	 * @NoAdminRequired
289
	 *
290
	 * @param string $bookID
0 ignored issues
show
Bug introduced by
There is no parameter named $bookID. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
291
	 * @return DataResponse
292
	 */
293
	public function getPaperHiveDetails() {
294
		return new DataResponse([
295
			'paperhive_bookid_example' => $this->paperhive_bookid_example,
296
			'paperhive_base_url' => $this->paperhive_base_url,
297
			'paperhive_base_document_url' => $this->paperhive_base_document_url,
298
			'paperhive_api_documents' => $this->paperhive_api_documents,
299
			'paperhive_api_discussions' => $this->paperhive_api_discussions,
300
			'paperhive_extension' => $this->paperhive_file_extension,
301
		], Http::STATUS_OK);
302
	}
303
}
304