-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathSyncSubmissionsWithLinkedFileJob.php
More file actions
90 lines (78 loc) · 2.47 KB
/
Copy pathSyncSubmissionsWithLinkedFileJob.php
File metadata and controls
90 lines (78 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Forms\BackgroundJob;
use OCA\Forms\Db\FormMapper;
use OCA\Forms\Service\FormsService;
use OCA\Forms\Service\SubmissionService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\BackgroundJob\QueuedJob;
use OCP\Files\NotFoundException;
use OCP\IUserManager;
use OCP\IUserSession;
use Psr\Log\LoggerInterface;
use Throwable;
class SyncSubmissionsWithLinkedFileJob extends QueuedJob {
public const MAX_ATTEMPTS = 10;
public function __construct(
ITimeFactory $time,
private readonly FormMapper $formMapper,
private readonly FormsService $formsService,
private readonly SubmissionService $submissionService,
private readonly LoggerInterface $logger,
private readonly IUserManager $userManager,
private readonly IUserSession $userSession,
private readonly IJobList $jobList,
) {
parent::__construct($time);
}
/**
* @param array $argument
*/
public function run($argument): void {
$oldUser = $this->userSession->getUser();
$formId = $argument['form_id'];
$attempt = $argument['attempt'] ?? 1;
try {
$form = $this->formMapper->findById($formId);
$ownerId = $form->getOwnerId();
$user = $this->userManager->get($ownerId);
$this->userSession->setUser($user);
$fileFormat = $form->getFileFormat();
$filePath = $this->formsService->getFilePath($form);
$this->submissionService->writeFileToCloud($form, $filePath, $fileFormat, $ownerId);
} catch (NotFoundException) {
$this->logger->notice('Form {formId} linked to a file that doesn\'t exist anymore', [
'formId' => $formId
]);
} catch (Throwable $e) {
$this->logger->warning(
'Failed to synchronize form {formId} with the file (attempt {attempt} of {maxAttempts}), reason: {message}',
[
'formId' => $formId,
'message' => $e->getMessage(),
'attempt' => $attempt,
'maxAttempts' => self::MAX_ATTEMPTS,
]
);
if ($attempt < self::MAX_ATTEMPTS) {
$this->jobList->scheduleAfter(
SyncSubmissionsWithLinkedFileJob::class,
$this->nextAttempt($attempt),
['form_id' => $formId, 'attempt' => $attempt + 1]
);
}
} finally {
$this->userSession->setUser($oldUser);
}
}
/**
* Calculates exponential delay (cubic growth) in seconds.
*/
private function nextAttempt(int $numberOfAttempt): int {
return $this->time->getTime() + $numberOfAttempt ** 3 * 60;
}
}