firefly-iii/app/Repositories/ImportJob/ImportJobRepository.php

471 lines
13 KiB
PHP
Raw Normal View History

2016-06-10 14:00:00 -05:00
<?php
/**
* ImportJobRepository.php
2017-10-21 01:40:00 -05:00
* Copyright (c) 2017 thegrumpydictator@gmail.com
2016-06-10 14:00:00 -05:00
*
2017-10-21 01:40:00 -05:00
* This file is part of Firefly III.
*
2017-10-21 01:40:00 -05:00
* Firefly III is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Firefly III is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
2017-12-17 07:44:05 -06:00
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
2016-06-10 14:00:00 -05:00
*/
declare(strict_types=1);
2016-06-10 14:00:00 -05:00
namespace FireflyIII\Repositories\ImportJob;
use Crypt;
2016-09-17 02:50:40 -05:00
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Attachment;
2016-06-10 14:00:00 -05:00
use FireflyIII\Models\ImportJob;
2018-05-03 10:23:16 -05:00
use FireflyIII\Models\Tag;
2016-06-10 14:00:00 -05:00
use FireflyIII\User;
2018-05-10 16:01:21 -05:00
use Illuminate\Support\Collection;
use Illuminate\Support\MessageBag;
2016-06-10 14:00:00 -05:00
use Illuminate\Support\Str;
use Log;
use Storage;
use Symfony\Component\HttpFoundation\File\UploadedFile;
2016-06-10 14:00:00 -05:00
/**
2017-11-15 05:25:49 -06:00
* Class ImportJobRepository.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
2016-06-10 14:00:00 -05:00
*/
class ImportJobRepository implements ImportJobRepositoryInterface
{
/** @var \Illuminate\Contracts\Filesystem\Filesystem */
protected $uploadDisk;
2018-05-10 16:01:21 -05:00
/** @var int */
private $maxUploadSize;
/** @var User */
private $user;
public function __construct()
{
$this->maxUploadSize = (int)config('firefly.maxUploadSize');
$this->uploadDisk = Storage::disk('upload');
if ('testing' === config('app.env')) {
2019-06-07 11:20:15 -05:00
Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this)));
}
}
2016-06-10 14:00:00 -05:00
2018-05-10 16:01:21 -05:00
/**
* Add message to job.
*
* @param ImportJob $job
* @param string $error
*
* @return ImportJob
*/
public function addErrorMessage(ImportJob $job, string $error): ImportJob
{
$errors = $job->errors;
$errors[] = $error;
$job->errors = $errors;
$job->save();
return $job;
}
/**
* Append transactions to array instead of replacing them.
*
* @param ImportJob $job
* @param array $transactions
*
* @return ImportJob
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function appendTransactions(ImportJob $job, array $transactions): ImportJob
{
Log::debug(sprintf('Now in appendTransactions(%s)', $job->key));
$existingTransactions = $this->getTransactions($job);
$new = array_merge($existingTransactions, $transactions);
Log::debug(sprintf('Old transaction count: %d', count($existingTransactions)));
Log::debug(sprintf('To be added transaction count: %d', count($transactions)));
Log::debug(sprintf('New count: %d', count($new)));
$this->setTransactions($job, $new);
return $job;
}
/**
* @param ImportJob $job
*
* @return int
*/
public function countTransactions(ImportJob $job): int
{
$info = $job->transactions ?? [];
if (isset($info['count'])) {
return (int)$info['count'];
}
return 0;
}
2016-06-10 14:00:00 -05:00
/**
* @param string $importProvider
2016-06-10 14:00:00 -05:00
*
* @return ImportJob
2017-11-15 05:25:49 -06:00
*
2016-10-09 00:58:27 -05:00
* @throws FireflyException
2016-06-10 14:00:00 -05:00
*/
public function create(string $importProvider): ImportJob
2016-06-10 14:00:00 -05:00
{
$count = 0;
$importProvider = strtolower($importProvider);
2016-09-17 02:50:40 -05:00
2016-06-10 14:00:00 -05:00
while ($count < 30) {
$key = Str::random(12);
$existing = $this->findByKey($key);
2018-07-24 13:30:52 -05:00
if (null === $existing) {
$importJob = ImportJob::create(
[
'user_id' => $this->user->id,
2018-05-03 10:23:16 -05:00
'tag_id' => null,
'provider' => $importProvider,
'file_type' => '',
'key' => Str::random(12),
'status' => 'new',
'stage' => 'new',
'configuration' => [],
'extended_status' => [],
'transactions' => [],
2018-05-03 10:23:16 -05:00
'errors' => [],
]
);
2016-06-10 14:00:00 -05:00
// breaks the loop:
return $importJob;
}
2017-11-15 05:25:49 -06:00
++$count;
2016-06-10 14:00:00 -05:00
}
throw new FireflyException('Could not create an import job with a unique key after 30 tries.');
2016-06-10 14:00:00 -05:00
}
2018-12-21 03:11:18 -06:00
/**
* @param int $jobId
*
* @return ImportJob|null
*/
public function find(int $jobId): ?ImportJob
{
return $this->user->importJobs()->find($jobId);
}
2016-06-10 14:00:00 -05:00
/**
* @param string $key
*
2018-07-24 13:30:52 -05:00
* @return ImportJob|null
2016-06-10 14:00:00 -05:00
*/
2018-07-24 13:30:52 -05:00
public function findByKey(string $key): ?ImportJob
2016-06-10 14:00:00 -05:00
{
2018-01-04 11:34:51 -06:00
/** @var ImportJob $result */
$result = $this->user->importJobs()->where('key', $key)->first(['import_jobs.*']);
2017-11-15 05:25:49 -06:00
if (null === $result) {
2018-07-24 13:30:52 -05:00
return null;
2016-06-10 14:00:00 -05:00
}
return $result;
}
2017-01-30 09:46:30 -06:00
2018-12-08 01:22:53 -06:00
/**
* Return all import jobs.
*
* @return Collection
*/
public function get(): Collection
{
return $this->user->importJobs()->get();
}
2018-05-10 16:01:21 -05:00
/**
* Return all attachments for job.
*
* @param ImportJob $job
*
* @return Collection
*/
public function getAttachments(ImportJob $job): Collection
{
return $job->attachments()->get();
}
2018-01-04 11:34:51 -06:00
/**
* Return configuration of job.
*
* @param ImportJob $job
*
* @return array
*/
public function getConfiguration(ImportJob $job): array
{
2018-07-26 21:46:21 -05:00
return $job->configuration;
2018-01-04 11:34:51 -06:00
}
2018-01-05 10:29:42 -06:00
/**
* Return extended status of job.
*
* @param ImportJob $job
*
* @return array
*/
public function getExtendedStatus(ImportJob $job): array
{
$status = $job->extended_status;
if (is_array($status)) {
2018-01-05 10:29:42 -06:00
return $status;
}
return [];
}
/**
* Return transactions from attachment.
*
* @param ImportJob $job
*
* @return array
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function getTransactions(ImportJob $job): array
{
// this will overwrite all transactions currently in the job.
$disk = Storage::disk('upload');
$filename = sprintf('%s-%s.crypt.json', $job->created_at->format('Ymd'), $job->key);
$array = [];
if ($disk->exists($filename)) {
$json = Crypt::decrypt($disk->get($filename));
$array = json_decode($json, true);
}
if (false === $array) {
$array = [];
}
return $array;
}
2017-03-19 11:54:21 -05:00
/**
* @param ImportJob $job
* @param array $configuration
*
* @return ImportJob
*/
public function setConfiguration(ImportJob $job, array $configuration): ImportJob
{
Log::debug('Updating configuration...');
//Log::debug(sprintf('Incoming config for job "%s" is: ', $job->key), $configuration);
$currentConfig = $job->configuration;
$newConfig = array_merge($currentConfig, $configuration);
$job->configuration = $newConfig;
2017-03-19 11:54:21 -05:00
$job->save();
2018-08-06 12:14:30 -05:00
//Log::debug(sprintf('Set config of job "%s" to: ', $job->key), $newConfig);
2017-03-19 11:54:21 -05:00
return $job;
}
/**
* @param ImportJob $job
* @param string $stage
*
* @return ImportJob
*/
public function setStage(ImportJob $job, string $stage): ImportJob
{
$job->stage = $stage;
$job->save();
return $job;
}
2017-03-19 11:54:21 -05:00
/**
* @param ImportJob $job
* @param string $status
*
* @return ImportJob
*/
2018-01-10 09:49:32 -06:00
public function setStatus(ImportJob $job, string $status): ImportJob
2017-03-19 11:54:21 -05:00
{
2018-05-01 13:47:38 -05:00
Log::debug(sprintf('Set status of job "%s" to "%s"', $job->key, $status));
2017-03-19 11:54:21 -05:00
$job->status = $status;
$job->save();
return $job;
}
2018-01-08 13:20:45 -06:00
/**
* @param ImportJob $job
2018-05-10 16:01:21 -05:00
* @param Tag $tag
2018-01-08 13:20:45 -06:00
*
* @return ImportJob
*/
2018-05-10 16:01:21 -05:00
public function setTag(ImportJob $job, Tag $tag): ImportJob
2018-01-08 13:20:45 -06:00
{
2018-05-10 16:01:21 -05:00
$job->tag()->associate($tag);
2018-01-10 09:49:32 -06:00
$job->save();
2018-01-08 13:20:45 -06:00
return $job;
}
2018-01-10 09:49:32 -06:00
2018-05-03 10:23:16 -05:00
/**
* @param ImportJob $job
* @param array $transactions
*
* @return ImportJob
*/
public function setTransactions(ImportJob $job, array $transactions): ImportJob
{
// this will overwrite all transactions currently in the job.
$disk = Storage::disk('upload');
$filename = sprintf('%s-%s.crypt.json', $job->created_at->format('Ymd'), $job->key);
$json = Crypt::encrypt(json_encode($transactions));
// set count for easy access
$array = ['count' => count($transactions)];
$job->transactions = $array;
2018-05-03 10:23:16 -05:00
$job->save();
// store file.
$disk->put($filename, $json);
2018-05-03 10:23:16 -05:00
return $job;
}
/**
2018-05-10 16:01:21 -05:00
* @param User $user
*/
2018-07-22 11:50:27 -05:00
public function setUser(User $user): void
{
2018-05-10 16:01:21 -05:00
$this->user = $user;
}
/**
* Handle upload for job.
*
2018-07-22 11:50:27 -05:00
* @param ImportJob $job
* @param string $name
* @param string $fileName
*
* @return MessageBag
*/
public function storeCLIUpload(ImportJob $job, string $name, string $fileName): MessageBag
{
$messages = new MessageBag;
if (!file_exists($fileName)) {
$messages->add('notfound', sprintf('File not found: %s', $fileName));
return $messages;
}
$count = $job->attachments()->get()->filter(
function (Attachment $att) use ($name) {
return $att->filename === $name;
}
)->count();
if ($count > 0) {// don't upload, but also don't complain about it.
Log::error(sprintf('Detected duplicate upload. Will ignore second "%s" file.', $name));
return new MessageBag;
}
$content = file_get_contents($fileName);
$attachment = new Attachment; // create Attachment object.
$attachment->user()->associate($job->user);
$attachment->attachable()->associate($job);
$attachment->md5 = md5($content);
$attachment->filename = $name;
$attachment->mime = 'plain/txt';
2019-06-07 10:58:11 -05:00
$attachment->size = strlen($content);
$attachment->uploaded = false;
$attachment->save();
$encrypted = Crypt::encrypt($content);
$this->uploadDisk->put($attachment->fileName(), $encrypted);
2018-07-24 23:45:25 -05:00
$attachment->uploaded = true; // update attachment
$attachment->save();
return new MessageBag;
}
/**
* Handle upload for job.
*
* @param ImportJob $job
* @param string $name
* @param UploadedFile $file
*
* @return MessageBag
2018-09-27 06:54:59 -05:00
* @throws FireflyException
*/
public function storeFileUpload(ImportJob $job, string $name, UploadedFile $file): MessageBag
{
$messages = new MessageBag;
if ($this->validSize($file)) {
$name = e($file->getClientOriginalName());
$messages->add('size', (string)trans('validation.file_too_large', ['name' => $name]));
return $messages;
}
$count = $job->attachments()->get()->filter(
2018-05-10 16:01:21 -05:00
function (Attachment $att) use ($name) {
return $att->filename === $name;
}
)->count();
if ($count > 0) { // don't upload, but also don't complain about it.
Log::error(sprintf('Detected duplicate upload. Will ignore second "%s" file.', $name));
return new MessageBag;
}
$attachment = new Attachment; // create Attachment object.
$attachment->user()->associate($job->user);
$attachment->attachable()->associate($job);
$attachment->md5 = md5_file($file->getRealPath());
$attachment->filename = $name;
$attachment->mime = $file->getMimeType();
$attachment->size = $file->getSize();
$attachment->uploaded = false;
$attachment->save();
2019-02-16 01:05:48 -06:00
$fileObject = $file->openFile();
$fileObject->rewind();
2018-09-27 06:54:59 -05:00
if (0 === $file->getSize()) {
2018-09-27 06:54:59 -05:00
throw new FireflyException('Cannot upload empty or non-existent file.');
}
$content = $fileObject->fread($file->getSize());
$encrypted = Crypt::encrypt($content);
$this->uploadDisk->put($attachment->fileName(), $encrypted);
2018-07-24 23:45:25 -05:00
$attachment->uploaded = true; // update attachment
$attachment->save();
return new MessageBag;
}
2018-05-10 16:01:21 -05:00
/**
* @codeCoverageIgnore
*
* @param UploadedFile $file
*
* @return bool
*/
protected function validSize(UploadedFile $file): bool
{
$size = $file->getSize();
return $size > $this->maxUploadSize;
}
2016-08-12 08:10:03 -05:00
}