Completed
Push — master ( 8de354...4e0f9f )
by Maxence
01:38
created

FilesService::generateDocument()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
declare(strict_types=1);
3
4
5
/**
6
 * Files_FullTextSearch - Index the content of your files
7
 *
8
 * This file is licensed under the Affero General Public License version 3 or
9
 * later. See the COPYING file.
10
 *
11
 * @author Maxence Lange <[email protected]>
12
 * @copyright 2018
13
 * @license GNU AGPL version 3 or any later version
14
 *
15
 * This program is free software: you can redistribute it and/or modify
16
 * it under the terms of the GNU Affero General Public License as
17
 * published by the Free Software Foundation, either version 3 of the
18
 * License, or (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU Affero General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU Affero General Public License
26
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
27
 *
28
 */
29
30
31
namespace OCA\Files_FullTextSearch\Service;
32
33
34
use daita\MySmallPhpTools\Traits\TPathTools;
35
use Exception;
36
use OCA\Files_FullTextSearch\Exceptions\EmptyUserException;
37
use OCA\Files_FullTextSearch\Exceptions\FileIsNotIndexableException;
38
use OCA\Files_FullTextSearch\Exceptions\FilesNotFoundException;
39
use OCA\Files_FullTextSearch\Exceptions\KnownFileMimeTypeException;
40
use OCA\Files_FullTextSearch\Exceptions\KnownFileSourceException;
41
use OCA\Files_FullTextSearch\Model\FilesDocument;
42
use OCA\Files_FullTextSearch\Provider\FilesProvider;
43
use OCP\App\IAppManager;
44
use OCP\AppFramework\IAppContainer;
45
use OCP\Files\File;
46
use OCP\Files\FileInfo;
47
use OCP\Files\Folder;
48
use OCP\Files\InvalidPathException;
49
use OCP\Files\IRootFolder;
50
use OCP\Files\Node;
51
use OCP\Files\NotFoundException;
52
use OCP\Files\NotPermittedException;
53
use OCP\Files\StorageNotAvailableException;
54
use OCP\FullTextSearch\Model\IIndex;
55
use OCP\FullTextSearch\Model\IIndexOptions;
56
use OCP\FullTextSearch\Model\IndexDocument;
57
use OCP\FullTextSearch\Model\IRunner;
58
use OCP\IUserManager;
59
use OCP\Share\IManager;
60
use Throwable;
61
62
63
/**
64
 * Class FilesService
65
 *
66
 * @package OCA\Files_FullTextSearch\Service
67
 */
68
class FilesService {
69
70
71
	use TPathTools;
72
73
74
	const MIMETYPE_TEXT = 'files_text';
75
	const MIMETYPE_PDF = 'files_pdf';
76
	const MIMETYPE_OFFICE = 'files_office';
77
	const MIMETYPE_IMAGE = 'files_image';
78
	const MIMETYPE_AUDIO = 'files_audio';
79
80
81
	/** @var IAppContainer */
82
	private $container;
83
84
	/** @var IRootFolder */
85
	private $rootFolder;
86
87
	/** @var IUserManager */
88
	private $userManager;
89
90
	/** @var IAppManager */
91
	private $appManager;
92
93
	/** @var IManager */
94
	private $shareManager;
95
96
	/** @var ConfigService */
97
	private $configService;
98
99
	/** @var LocalFilesService */
100
	private $localFilesService;
101
102
	/** @var ExternalFilesService */
103
	private $externalFilesService;
104
105
	/** @var GroupFoldersService */
106
	private $groupFoldersService;
107
108
	/** @var ExtensionService */
109
	private $extensionService;
110
111
	/** @var MiscService */
112
	private $miscService;
113
114
115
	/** @var IRunner */
116
	private $runner;
117
118
	/** @var int */
119
	private $sumDocuments;
120
121
122
	/**
123
	 * FilesService constructor.
124
	 *
125
	 * @param IAppContainer $container
126
	 * @param IRootFolder $rootFolder
127
	 * @param IAppManager $appManager
128
	 * @param IUserManager $userManager
129
	 * @param IManager $shareManager
130
	 * @param ConfigService $configService
131
	 * @param LocalFilesService $localFilesService
132
	 * @param ExternalFilesService $externalFilesService
133
	 * @param GroupFoldersService $groupFoldersService
134
	 * @param ExtensionService $extensionService
135
	 * @param MiscService $miscService
136
	 *
137
	 * @internal param IProviderFactory $factory
138
	 */
139
	public function __construct(
140
		IAppContainer $container, IRootFolder $rootFolder, IAppManager $appManager,
141
		IUserManager $userManager, IManager $shareManager,
142
		ConfigService $configService, LocalFilesService $localFilesService,
143
		ExternalFilesService $externalFilesService, GroupFoldersService $groupFoldersService,
144
		ExtensionService $extensionService, MiscService $miscService
145
	) {
146
		$this->container = $container;
147
		$this->rootFolder = $rootFolder;
148
		$this->appManager = $appManager;
149
		$this->userManager = $userManager;
150
		$this->shareManager = $shareManager;
151
152
		$this->configService = $configService;
153
		$this->localFilesService = $localFilesService;
154
		$this->externalFilesService = $externalFilesService;
155
		$this->groupFoldersService = $groupFoldersService;
156
		$this->extensionService = $extensionService;
157
158
		$this->miscService = $miscService;
159
	}
160
161
162
	/**
163
	 * @param IRunner $runner
164
	 */
165
	public function setRunner(IRunner $runner) {
166
		$this->runner = $runner;
167
	}
168
169
170
	/**
171
	 * @param string $userId
172
	 * @param IIndexOptions $indexOptions
173
	 *
174
	 * @return FilesDocument[]
175
	 * @throws InvalidPathException
176
	 * @throws NotFoundException
177
	 */
178
	public function getFilesFromUser(string $userId, IIndexOptions $indexOptions): array {
179
180
		$this->initFileSystems($userId);
181
		$this->sumDocuments = 0;
182
183
		/** @var Folder $files */
184
		$files = $this->rootFolder->getUserFolder($userId)
185
								  ->get($indexOptions->getOption('path', '/'));
186
		if ($files instanceof Folder) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\Folder does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
187
			$result = $this->getFilesFromDirectory($userId, $files);
188
		} else {
189
			$result = [];
190
			try {
191
				$result[] = $this->generateFilesDocumentFromFile($userId, $files);
192
			} catch (FileIsNotIndexableException $e) {
193
				/** we do nothin' */
194
			}
195
		}
196
197
		return $result;
198
	}
199
200
201
	/**
202
	 * @param string $userId
203
	 */
204
	private function initFileSystems(string $userId) {
205
		if ($userId === '') {
206
			return;
207
		}
208
209
		$this->externalFilesService->initExternalFilesForUser($userId);
210
		$this->groupFoldersService->initGroupSharesForUser($userId);
211
	}
212
213
214
	/**
215
	 * @param string $userId
216
	 * @param Folder $node
217
	 *
218
	 * @return FilesDocument[]
219
	 * @throws InvalidPathException
220
	 * @throws NotFoundException
221
	 * @throws Exception
222
	 */
223
	public function getFilesFromDirectory(string $userId, Folder $node): array {
224
		$documents = [];
225
226
		$this->updateRunnerAction('generateIndexFiles', true);
227
		$this->updateRunnerInfo(
228
			[
229
				'info'          => $node->getPath(),
230
				'documentTotal' => $this->sumDocuments
231
			]
232
		);
233
234
		try {
235
			if ($node->nodeExists('.noindex')) {
236
				return $documents;
237
			}
238
		} catch (StorageNotAvailableException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\StorageNotAvailableException 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...
239
			return $documents;
240
		}
241
242
		$files = $node->getDirectoryListing();
243
		foreach ($files as $file) {
244
245
			try {
246
				$documents[] = $this->generateFilesDocumentFromFile($userId, $file);
247
				$this->sumDocuments++;
248
			} catch (FileIsNotIndexableException $e) {
249
				continue;
250
			}
251
252
			if ($file->getType() === FileInfo::TYPE_FOLDER) {
253
				/** @var $file Folder */
254
				$documents =
255
					array_merge($documents, $this->getFilesFromDirectory($userId, $file));
256
			}
257
		}
258
259
		return $documents;
260
	}
261
262
263
	/**
264
	 * @param string $viewerId
265
	 * @param Node $file
266
	 *
267
	 * @return FilesDocument
268
	 * @throws FileIsNotIndexableException
269
	 * @throws InvalidPathException
270
	 * @throws NotFoundException
271
	 * @throws Exception
272
	 */
273
	private function generateFilesDocumentFromFile(string $viewerId, Node $file): FilesDocument {
274
275
		$source = $this->getFileSource($file);
276
		$document = new FilesDocument(FilesProvider::FILES_PROVIDER_ID, (string) $file->getId());
277
278
		if ($file->getId() === -1) {
279
			throw new FileIsNotIndexableException();
280
		}
281
282
		$ownerId = '';
283
		if ($file->getOwner() !== null) {
284
			$ownerId = $file->getOwner()
285
							->getUID();
286
		}
287
		$document->setType($file->getType())
288
				 ->setOwnerId($ownerId)
289
				 ->setPath($this->getPathFromViewerId($file->getId(), $viewerId))
290
				 ->setViewerId($viewerId)
291
				 ->setMimetype($file->getMimetype());
292
		$document->setModifiedTime($file->getMTime())
293
				 ->setSource($source);
294
295
		return $document;
296
	}
297
298
299
	/**
300
	 * @param Node $file
301
	 *
302
	 * @return string
303
	 * @throws FileIsNotIndexableException
304
	 */
305
	private function getFileSource(Node $file): string {
306
		$source = '';
307
308
		try {
309
			$this->localFilesService->getFileSource($file, $source);
310
			$this->externalFilesService->getFileSource($file, $source);
311
			$this->groupFoldersService->getFileSource($file, $source);
312
		} catch (KnownFileSourceException $e) {
313
			/** we know the source, just leave. */
314
		}
315
316
		return $source;
317
	}
318
319
320
	/**
321
	 * @param string $userId
322
	 * @param string $path
323
	 *
324
	 * @return Node
325
	 * @throws NotFoundException
326
	 */
327
	public function getFileFromPath(string $userId, string $path): Node {
328
		return $this->rootFolder->getUserFolder($userId)
329
								->get($path);
330
	}
331
332
333
	/**
334
	 * @param string $userId
335
	 * @param int $fileId
336
	 *
337
	 * @return Node
338
	 * @throws FilesNotFoundException
339
	 * @throws EmptyUserException
340
	 */
341
	public function getFileFromId(string $userId, int $fileId): Node {
342
343
		if ($userId === '') {
344
			throw new EmptyUserException();
345
		}
346
347
		$files = $this->rootFolder->getUserFolder($userId)
348
								  ->getById($fileId);
349
		if (sizeof($files) === 0) {
350
			throw new FilesNotFoundException();
351
		}
352
353
		$file = array_shift($files);
354
355
		return $file;
356
	}
357
358
359
	/**
360
	 * @param IIndex $index
361
	 *
362
	 * @return Node
363
	 * @throws EmptyUserException
364
	 * @throws FilesNotFoundException
365
	 */
366
	public function getFileFromIndex(IIndex $index): Node {
367
		$this->impersonateOwner($index);
368
369
		return $this->getFileFromId($index->getOwnerId(), (int)$index->getDocumentId());
370
	}
371
372
373
	/**
374
	 * @param int $fileId
375
	 * @param string $viewerId
376
	 *
377
	 * @throws Exception
378
	 * @return string
379
	 */
380
	private function getPathFromViewerId(int $fileId, string $viewerId): string {
381
382
		$viewerFiles = $this->rootFolder->getUserFolder($viewerId)
383
										->getById($fileId);
384
385
		if (sizeof($viewerFiles) === 0) {
386
			return '';
387
		}
388
389
		$file = array_shift($viewerFiles);
390
391
		// TODO: better way to do this : we remove the '/userid/files/'
392
		$path = $this->withoutEndSlash(substr($file->getPath(), 8 + strlen($viewerId)));
393
394
		return $path;
395
	}
396
397
398
	/**
399
	 * @param FilesDocument $document
400
	 */
401
	public function generateDocument(FilesDocument $document) {
402
403
		try {
404
			$this->updateFilesDocument($document);
405
		} catch (Exception $e) {
406
			// TODO - update $document with a error status instead of just ignore !
407
			$document->getIndex()
408
					 ->setStatus(IIndex::INDEX_IGNORE);
409
			echo 'Exception: ' . json_encode($e->getTrace()) . ' - ' . $e->getMessage()
410
				 . "\n";
411
		}
412
	}
413
414
415
	/**
416
	 * @param IIndex $index
417
	 *
418
	 * @return FilesDocument
419
	 * @throws FileIsNotIndexableException
420
	 * @throws InvalidPathException
421
	 * @throws NotFoundException
422
	 */
423
	private function generateDocumentFromIndex(IIndex $index): FilesDocument {
424
425
		try {
426
			$file = $this->getFileFromIndex($index);
427
		} catch (Exception $e) {
428
			$index->setStatus(IIndex::INDEX_REMOVE);
429
			$document = new FilesDocument($index->getProviderId(), $index->getDocumentId());
430
			$document->setIndex($index);
431
432
			return $document;
433
		}
434
435
		$document = $this->generateFilesDocumentFromFile($index->getOwnerId(), $file);
436
		$document->setIndex($index);
437
438
		$this->updateFilesDocumentFromFile($document, $file);
439
440
		return $document;
441
	}
442
443
444
	/**
445
	 * @param IndexDocument $document
446
	 *
447
	 * @return bool
448
	 */
449
	public function isDocumentUpToDate(IndexDocument $document): bool {
450
		$index = $document->getIndex();
451
452
		if (!$this->configService->compareIndexOptions($index)) {
453
			$index->setStatus(IIndex::INDEX_CONTENT);
454
			$document->setIndex($index);
455
456
			return false;
457
		}
458
459
		if ($index->getStatus() !== IIndex::INDEX_OK) {
460
			return false;
461
		}
462
463
		if ($index->getLastIndex() >= $document->getModifiedTime()) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return $index->getLastIn...ent->getModifiedTime();.
Loading history...
464
			return true;
465
		}
466
467
		return false;
468
	}
469
470
471
	/**
472
	 * @param IIndex $index
473
	 *
474
	 * @return FilesDocument
475
	 * @throws InvalidPathException
476
	 * @throws NotFoundException
477
	 * @throws NotPermittedException
478
	 * @throws FileIsNotIndexableException
479
	 */
480
	public function updateDocument(IIndex $index): FilesDocument {
481
		$this->impersonateOwner($index);
482
		$this->initFileSystems($index->getOwnerId());
483
484
		return $this->generateDocumentFromIndex($index);
485
	}
486
487
488
	/**
489
	 * @param FilesDocument $document
490
	 *
491
	 * @throws NotFoundException
492
	 */
493
	private function updateFilesDocument(FilesDocument $document) {
494
		$userFolder = $this->rootFolder->getUserFolder($document->getViewerId());
495
		$file = $userFolder->get($document->getPath());
496
497
		try {
498
			$this->updateFilesDocumentFromFile($document, $file);
499
		} catch (FileIsNotIndexableException $e) {
500
			$document->getIndex()
501
					 ->setStatus(IIndex::INDEX_IGNORE);
502
		}
503
	}
504
505
506
	/**
507
	 * @param FilesDocument $document
508
	 * @param Node $file
509
	 */
510
	private function updateFilesDocumentFromFile(FilesDocument $document, Node $file) {
511
512
		$document->getIndex()
513
				 ->setSource($document->getSource());
514
515
		$this->updateDocumentAccess($document, $file);
516
		$this->updateContentFromFile($document, $file);
517
518
		$document->addMetaTag($document->getSource());
519
	}
520
521
522
	/**
523
	 * @param FilesDocument $document
524
	 * @param Node $file
525
	 */
526
	private function updateDocumentAccess(FilesDocument $document, Node $file) {
527
528
		$index = $document->getIndex();
529
530
		if (!$index->isStatus(IIndex::INDEX_FULL)
531
			&& !$index->isStatus(FilesDocument::STATUS_FILE_ACCESS)) {
532
			return;
533
		}
534
535
		$this->localFilesService->updateDocumentAccess($document, $file);
536
		$this->externalFilesService->updateDocumentAccess($document, $file);
537
		$this->groupFoldersService->updateDocumentAccess($document, $file);
538
539
		$this->updateShareNames($document, $file);
540
	}
541
542
543
	/**
544
	 * @param FilesDocument $document
545
	 * @param Node $file
546
	 */
547
	private function updateContentFromFile(FilesDocument $document, Node $file) {
548
549
		$document->setTitle($document->getPath());
550
551
		if (!$document->getIndex()
552
					  ->isStatus(IIndex::INDEX_CONTENT)
553
			|| $file->getType() !== FileInfo::TYPE_FILE) {
554
			return;
555
		}
556
557
		try {
558
			/** @var File $file */
559
			if ($file->getSize() <
560
				($this->configService->getAppValue(ConfigService::FILES_SIZE) * 1024 * 1024)) {
561
				$this->extractContentFromFileText($document, $file);
562
				$this->extractContentFromFileOffice($document, $file);
563
				$this->extractContentFromFilePDF($document, $file);
564
565
				$this->extensionService->fileIndexing($document, $file);
566
			}
567
		} catch (Throwable $t) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
568
			$this->manageContentErrorException($document, $t);
569
		}
570
571
		if ($document->getContent() === null) {
572
			$document->getIndex()
573
					 ->unsetStatus(IIndex::INDEX_CONTENT);
574
		}
575
	}
576
577
578
	/**
579
	 * @param FilesDocument $document
580
	 * @param Node $file
581
	 *
582
	 * @return array
583
	 */
584
	private function updateShareNames(FilesDocument $document, Node $file): array {
585
586
		$users = [];
587
588
		$this->localFilesService->getShareUsersFromFile($file, $users);
589
		$this->externalFilesService->getShareUsers($document, $users);
590
		$this->groupFoldersService->getShareUsers($document, $users);
591
592
		$shareNames = [];
593
		foreach ($users as $username) {
594
			try {
595
				$user = $this->userManager->get($username);
596
				if ($user === null || $user->getLastLogin() === 0) {
597
					continue;
598
				}
599
600
				$path = $this->getPathFromViewerId($file->getId(), $username);
601
				$shareNames[$this->miscService->secureUsername($username)] =
602
					(!is_string($path)) ? $path = '' : $path;
603
604
			} catch (Exception $e) {
605
				$this->miscService->log(
606
					'Issue while getting information on documentId:' . $document->getId(), 0
607
				);
608
			}
609
		}
610
611
		$document->setInfoArray('share_names', $shareNames);
612
613
		return $shareNames;
614
	}
615
616
617
	/**
618
	 * @param string $mimeType
619
	 *
620
	 * @return string
621
	 */
622
	private function parseMimeType(string $mimeType): string {
623
624
		$parsed = '';
625
		try {
626
			$this->parseMimeTypeText($mimeType, $parsed);
627
			$this->parseMimeTypePDF($mimeType, $parsed);
628
			$this->parseMimeTypeOffice($mimeType, $parsed);
629
		} catch (KnownFileMimeTypeException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
630
		}
631
632
		return $parsed;
633
	}
634
635
636
	/**
637
	 * @param string $mimeType
638
	 * @param string $parsed
639
	 *
640
	 * @throws KnownFileMimeTypeException
641
	 */
642
	private function parseMimeTypeText(string $mimeType, string &$parsed) {
643
644
		if (substr($mimeType, 0, 5) === 'text/') {
645
			$parsed = self::MIMETYPE_TEXT;
646
			throw new KnownFileMimeTypeException();
647
		}
648
649
		$textMimes = [
650
			'application/epub+zip'
651
		];
652
653 View Code Duplication
		foreach ($textMimes as $mime) {
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...
654
			if (strpos($mimeType, $mime) === 0) {
655
				$parsed = self::MIMETYPE_TEXT;
656
				throw new KnownFileMimeTypeException();
657
			}
658
		}
659
	}
660
661
662
	/**
663
	 * @param string $mimeType
664
	 * @param string $parsed
665
	 *
666
	 * @throws KnownFileMimeTypeException
667
	 */
668
	private function parseMimeTypePDF(string $mimeType, string &$parsed) {
669
670
		if ($mimeType === 'application/pdf') {
671
			$parsed = self::MIMETYPE_PDF;
672
			throw new KnownFileMimeTypeException();
673
		}
674
	}
675
676
677
	/**
678
	 * @param string $mimeType
679
	 * @param string $parsed
680
	 *
681
	 * @throws KnownFileMimeTypeException
682
	 */
683
	private function parseMimeTypeOffice(string $mimeType, string &$parsed) {
684
685
		$officeMimes = [
686
			'application/msword',
687
			'application/vnd.oasis.opendocument',
688
			'application/vnd.sun.xml',
689
			'application/vnd.openxmlformats-officedocument',
690
			'application/vnd.ms-word',
691
			'application/vnd.ms-powerpoint',
692
			'application/vnd.ms-excel'
693
		];
694
695 View Code Duplication
		foreach ($officeMimes as $mime) {
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...
696
			if (strpos($mimeType, $mime) === 0) {
697
				$parsed = self::MIMETYPE_OFFICE;
698
				throw new KnownFileMimeTypeException();
699
			}
700
		}
701
	}
702
703
704
	/**
705
	 * @param FilesDocument $document
706
	 * @param File $file
707
	 *
708
	 * @throws NotPermittedException
709
	 */
710
	private function extractContentFromFileText(FilesDocument $document, File $file) {
711
712
		if ($this->parseMimeType($document->getMimeType()) !== self::MIMETYPE_TEXT) {
713
			return;
714
		}
715
716
		if (!$this->isSourceIndexable($document)) {
717
			return;
718
		}
719
720
		$document->setContent(
721
			base64_encode($file->getContent()), IndexDocument::ENCODED_BASE64
722
		);
723
	}
724
725
726
	/**
727
	 * @param FilesDocument $document
728
	 * @param File $file
729
	 *
730
	 * @throws NotPermittedException
731
	 */
732 View Code Duplication
	private function extractContentFromFilePDF(FilesDocument $document, File $file) {
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...
733
		if ($this->parseMimeType($document->getMimeType()) !== self::MIMETYPE_PDF) {
734
			return;
735
		}
736
737
		$this->configService->setDocumentIndexOption($document, ConfigService::FILES_PDF);
738
		if (!$this->isSourceIndexable($document)) {
739
			return;
740
		}
741
742
		if ($this->configService->getAppValue(ConfigService::FILES_PDF) !== '1') {
743
			$document->setContent('');
744
745
			return;
746
		}
747
748
		$document->setContent(
749
			base64_encode($file->getContent()), IndexDocument::ENCODED_BASE64
750
		);
751
	}
752
753
754
	/**
755
	 * @param FilesDocument $document
756
	 * @param File $file
757
	 *
758
	 * @throws NotPermittedException
759
	 */
760 View Code Duplication
	private function extractContentFromFileOffice(FilesDocument $document, File $file) {
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...
761
		if ($this->parseMimeType($document->getMimeType()) !== self::MIMETYPE_OFFICE) {
762
			return;
763
		}
764
765
		$this->configService->setDocumentIndexOption($document, ConfigService::FILES_OFFICE);
766
		if (!$this->isSourceIndexable($document)) {
767
			return;
768
		}
769
770
		if ($this->configService->getAppValue(ConfigService::FILES_OFFICE) !== '1') {
771
			$document->setContent('');
772
773
			return;
774
		}
775
776
		$document->setContent(
777
			base64_encode($file->getContent()), IndexDocument::ENCODED_BASE64
778
		);
779
	}
780
781
782
	/**
783
	 * @param FilesDocument $document
784
	 *
785
	 * @return bool
786
	 */
787
	private function isSourceIndexable(FilesDocument $document): bool {
788
		$this->configService->setDocumentIndexOption($document, $document->getSource());
789
		if ($this->configService->getAppValue($document->getSource()) !== '1') {
790
			$document->setContent('');
791
792
			return false;
793
		}
794
795
		return true;
796
	}
797
798
799
	/**
800
	 * @param IIndex $index
801
	 */
802
	private function impersonateOwner(IIndex $index) {
803
		if ($index->getOwnerId() !== '') {
804
			return;
805
		}
806
807
		$this->groupFoldersService->impersonateOwner($index);
808
		$this->externalFilesService->impersonateOwner($index);
809
	}
810
811
812
	/**
813
	 * @param $action
814
	 * @param bool $force
815
	 *
816
	 * @throws Exception
817
	 */
818
	private function updateRunnerAction(string $action, bool $force = false) {
819
		if ($this->runner === null) {
820
			return;
821
		}
822
823
		$this->runner->updateAction($action, $force);
824
	}
825
826
827
	/**
828
	 * @param array $data
829
	 */
830
	private function updateRunnerInfo($data) {
831
		if ($this->runner === null) {
832
			return;
833
		}
834
835
		$this->runner->setInfoArray($data);
836
	}
837
838
	/**
839
	 * @param IndexDocument $document
840
	 * @param Throwable $t
841
	 */
842
	private function manageContentErrorException(IndexDocument $document, Throwable $t) {
843
		$document->getIndex()
844
				 ->addError(
845
					 'Error while getting file content', $t->getMessage(), IIndex::ERROR_SEV_3
846
				 );
847
		$this->updateNewIndexError(
848
			$document->getIndex(), 'Error while getting file content', $t->getMessage(),
849
			IIndex::ERROR_SEV_3
850
		);
851
		$this->miscService->log(json_encode($t->getTrace()), 0);
852
	}
853
854
855
	/**
856
	 * @param IIndex $index
857
	 * @param string $message
858
	 * @param string $exception
859
	 * @param int $sev
860
	 */
861
	private function updateNewIndexError(IIndex $index, string $message, string $exception, int $sev
862
	) {
863
		if ($this->runner === null) {
864
			return;
865
		}
866
867
		$this->runner->newIndexError($index, $message, $exception, $sev);
868
	}
869
}
870
871