Skip to content

Commit

Permalink
big update
Browse files Browse the repository at this point in the history
  • Loading branch information
asbiin committed Jul 31, 2023
1 parent 34684e8 commit 97aadcf
Show file tree
Hide file tree
Showing 48 changed files with 327 additions and 136 deletions.
4 changes: 2 additions & 2 deletions app/Actions/AttemptToAuthenticateSocialite.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,10 @@ private function getSocialiteProvider(string $driver): Provider
*/
private function authenticateUser(Request $request, string $driver, SocialiteUser $socialite): User
{
if ($userToken = UserToken::where([
if ($userToken = UserToken::firstWhere([
'driver_id' => $socialite->getId(),
'driver' => $driver,
])->first()) {
])) {
// Association already exist

$user = $userToken->user;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace App\Console\Commands;
namespace App\Console\Commands\Local;

use App\Domains\Contact\DavClient\Jobs\SynchronizeAddressBooks;
use App\Models\AddressBookSubscription;
Expand All @@ -14,7 +14,8 @@ class UpdateAddressBookSubscription extends Command
* @var string
*/
protected $signature = 'monica:updateaddressbooksubscription
{--subscriptionId= : Id of the vault to add subscription to}';
{--subscriptionId= : Id of the subscription to synchronize}
{--force : Force sync}';

/**
* The console command description.
Expand All @@ -25,13 +26,11 @@ class UpdateAddressBookSubscription extends Command

/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$subscription = AddressBookSubscription::findOrFail($this->option('subscriptionId'));

SynchronizeAddressBooks::dispatch($subscription, true);
SynchronizeAddressBooks::dispatch($subscription, $this->option('force'));
}
}
61 changes: 52 additions & 9 deletions app/Console/Commands/NewAddressBookSubscription.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Models\User;
use App\Models\Vault;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class NewAddressBookSubscription extends Command
{
Expand All @@ -31,23 +32,25 @@ class NewAddressBookSubscription extends Command

/**
* Execute the console command.
*
* @return void
*/
public function handle()
public function handle(): int
{
$user = User::where('email', $this->option('email'))->firstOrFail();
$vault = Vault::findOrFail($this->option('vaultId'));
if (($user = $this->user()) === null) {
return 1;
}
if (($vault = $this->vault()) === null) {
return 2;
}

if ($user->account_id !== $vault->account_id) {
$this->error('Vault does not belong to this account');

return;
return 3;
}

$url = $this->option('url') ?? $this->ask('url', 'CardDAV url of the address book');
$login = $this->option('login') ?? $this->ask('login', 'Login name');
$password = $this->option('password') ?? $this->ask('password', 'User password');
$url = $this->option('url') ?? $this->ask('CardDAV url of the address book');
$login = $this->option('login') ?? $this->ask('Login name');
$password = $this->option('password') ?? $this->secret('User password');

try {
$addressBookSubscription = app(CreateAddressBookSubscription::class)->execute([
Expand All @@ -60,13 +63,53 @@ public function handle()
]);
} catch (\Exception $e) {
$this->error($e->getMessage());

return -1;
}

if (! isset($addressBookSubscription)) {

Check failure on line 70 in app/Console/Commands/NewAddressBookSubscription.php

View workflow job for this annotation

GitHub Actions / phpstan

Variable $addressBookSubscription in isset() always exists and is not nullable.
$this->error('Could not add subscription');

return -2;
} else {
$this->info('Subscription added');
SynchronizeAddressBooks::dispatch($addressBookSubscription, true);
}

return 0;
}

private function user(): ?User
{
if (($email = $this->option('email')) === null) {
$this->error('Please provide an email address');

return null;
}

try {
return User::where('email', $email)->firstOrFail();
} catch (ModelNotFoundException) {
$this->error('Could not find user');

return null;
}
}

private function vault(): ?Vault
{
if (($vaultId = $this->option('vaultId')) === null) {
$this->error('Please provide an vaultId');

return null;
}

try {
return Vault::findOrFail($vaultId);
} catch (ModelNotFoundException) {
$this->error('Could not find vault');

return null;
}
}
}
26 changes: 19 additions & 7 deletions app/Domains/Contact/Dav/Jobs/UpdateVCard.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use App\Domains\Contact\Dav\Services\ImportVCard;
use App\Domains\Contact\Dav\Web\Backend\CardDAV\CardDAVBackend;
use App\Interfaces\ServiceInterface;
use App\Models\Contact;
use App\Services\QueuableService;
use Closure;
use Illuminate\Bus\Batchable;
Expand All @@ -28,6 +29,7 @@ public function rules(): array
'vault_id' => 'required|uuid|exists:vaults,id',
'uri' => 'required|string',
'etag' => 'nullable|string',
'external' => 'nullable|boolean',
'card' => [
'required',
function (string $attribute, mixed $value, Closure $fail) {
Expand Down Expand Up @@ -76,16 +78,24 @@ public function execute(array $data): void
/**
* Update the contact with the carddata.
*/
private function updateCard(string $cardUri, mixed $cardData): ?string
private function updateCard(string $uri, mixed $card): ?string
{
$backend = app(CardDAVBackend::class)->withUser($this->author);

$contactId = null;
if ($cardUri) {
$contactObject = $backend->getObject($this->vault->id, $cardUri);

if ($uri) {
$contactObject = $backend->getObject($this->vault->id, $uri);
if ($contactObject) {
$contactId = $contactObject->id;
} else {
$contactObject = Contact::firstWhere([
'vault_id' => $this->vault->id,
'distant_uri' => $uri,
]);

if ($contactObject) {
$contactId = $contactObject->id;
}
}
}

Expand All @@ -95,8 +105,10 @@ private function updateCard(string $cardUri, mixed $cardData): ?string
'author_id' => $this->author->id,
'vault_id' => $this->vault->id,
'contact_id' => $contactId,
'entry' => $cardData,
'entry' => $card,
'etag' => Arr::get($this->data, 'etag'),
'uri' => $uri,
'external' => Arr::get($this->data, 'external', false),
'behaviour' => ImportVCard::BEHAVIOUR_REPLACE,
]);

Expand All @@ -110,9 +122,9 @@ private function updateCard(string $cardUri, mixed $cardData): ?string
}
} catch (\Exception $e) {
Log::error(__CLASS__.' '.__FUNCTION__.': '.$e->getMessage(), [
'contacturl' => $cardUri,
'contacturl' => $uri,
'contact_id' => $contactId,
'carddata' => $cardData,
'carddata' => $card,
$e,
]);
throw $e;
Expand Down
2 changes: 1 addition & 1 deletion app/Domains/Contact/Dav/Services/ExportVCard.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ private function export(Contact $contact): VCard
/** @var VCard */
$vcard = Reader::read($contact->vcard, Reader::OPTION_FORGIVING + Reader::OPTION_IGNORE_INVALID_LINES);
if (! $vcard->UID) {
$vcard->UID = $contact->id;
$vcard->UID = $contact->distant_uuid ?? $contact->id;
}
} catch (ParseException $e) {
// Ignore error
Expand Down
45 changes: 28 additions & 17 deletions app/Domains/Contact/Dav/Services/ImportVCard.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ class ImportVCard extends BaseService implements ServiceInterface
self::BEHAVIOUR_REPLACE,
];

public bool $external = false;

/**
* Get the validation rules that apply to the service.
*/
Expand All @@ -83,6 +85,8 @@ function (string $attribute, mixed $value, Closure $fail) {
Rule::in(self::$behaviourTypes),
],
'etag' => 'nullable|string',
'uri' => 'nullable|string',
'external' => 'nullable|boolean',
];
}

Expand Down Expand Up @@ -111,6 +115,8 @@ public function execute(array $data): array
{
$this->validateRules($data);

$this->external = Arr::get($data, 'external', false);

if (Arr::get($data, 'contact_id') !== null) {
$this->validateContactBelongsToVault($data);

Expand Down Expand Up @@ -205,16 +211,22 @@ private function processEntryContact(array $data, ?Contact $contact, VCard $entr
];
}

if ($contact !== null) {
$timestamps = $contact->timestamps;
$contact->timestamps = false;
}
$contact = $this->importEntry($contact, $entry);

$contact = $this->importEntry($contact, $entry, $vcard, Arr::get($data, 'etag'));
// Save vcard content
$contact->vcard = $vcard;

if (isset($timestamps)) {
$contact->timestamps = $timestamps;
}
$contact = Contact::withoutTimestamps(function () use ($contact, $data): Contact {
$uri = Arr::get($data, 'uri');
if (Arr::get($data, 'external', false)) {
$contact->distant_etag = Arr::get($data, 'etag');
$contact->distant_uri = $uri;
}

$contact->save();

return $contact;
});

return [
'contact_id' => $contact->id,
Expand Down Expand Up @@ -293,17 +305,22 @@ private function getExistingContact(VCard $entry): ?Contact
private function existingUuid(VCard $entry): ?Contact
{
return ! empty($uuid = (string) $entry->UID) && Uuid::isValid($uuid)
? Contact::where([
?
Contact::firstWhere([
'vault_id' => $this->vault->id,
'distant_uuid' => $uuid,
]) ??
Contact::firstWhere([
'vault_id' => $this->vault->id,
'id' => $uuid,
])->first()
])
: null;
}

/**
* Create the Contact object matching the current entry.
*/
private function importEntry(?Contact $contact, VCard $entry, string $vcard, ?string $etag): Contact
private function importEntry(?Contact $contact, VCard $entry): Contact
{
/** @var \Illuminate\Support\Collection<int, ImportVCardResource> */
$importers = collect($this->importers())
Expand All @@ -314,12 +331,6 @@ private function importEntry(?Contact $contact, VCard $entry, string $vcard, ?st
$contact = $importer->import($contact, $entry);
}

// Save vcard content
$contact->vcard = $vcard;
$contact->distant_etag = $etag;

$contact->save();

return $contact;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,10 +233,13 @@ public function getObjectUuid(?string $collectionId, string $uuid): ?Contact
throw new NotEnoughPermissionException();
}

return Contact::where([
return Contact::firstWhere([
'distant_uuid' => $uuid,
'vault_id' => $vault->id,
]) ?? Contact::firstWhere([
'id' => $uuid,
'vault_id' => $vault->id,
])->first();
]);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion app/Domains/Contact/Dav/Web/Backend/SyncDAVBackend.php
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ private function getDeleted(string $collectionId, ?Carbon $timestamp): array

protected function encodeUri($obj): string
{
return urlencode($obj->id.$this->getExtension());
return urlencode(($obj->distant_uuid ?? $obj->id).$this->getExtension());
}

private function decodeUri(string $uri): string
Expand Down
1 change: 1 addition & 0 deletions app/Domains/Contact/DavClient/Jobs/GetMultipleVCard.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ private function updateVCard(array $contact, string $href): ?UpdateVCard
'uri' => $href,
'etag' => Arr::get($contact, 'properties.200.{DAV:}getetag'),
'card' => $card,
'external' => true,
]);
}

Expand Down
1 change: 1 addition & 0 deletions app/Domains/Contact/DavClient/Jobs/GetVCard.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ private function updateVCard(string $card): UpdateVCard
'uri' => $this->contact->uri,
'etag' => $this->contact->etag,
'card' => $card,
'external' => true,
]);
}
}
Loading

0 comments on commit 97aadcf

Please sign in to comment.