Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions lib/Controller/ConfigController.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class ConfigController extends Controller {

public const DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive.readonly';
public const CONTACTS_SCOPE = 'https://www.googleapis.com/auth/contacts.readonly';
public const CONTACTS_OTHER_SCOPE = 'https://www.googleapis.com/auth/contacts.other.readonly';
public const CALENDAR_SCOPE = 'https://www.googleapis.com/auth/calendar.readonly';
public const CALENDAR_EVENTS_SCOPE = 'https://www.googleapis.com/auth/calendar.events.readonly';
public const PHOTOS_SCOPE = 'https://www.googleapis.com/auth/photoslibrary.readonly';
Expand Down Expand Up @@ -162,8 +163,8 @@ public function popupSuccessPage(string $username): TemplateResponse {
public function oauthRedirect(string $code = '', string $state = '', string $scope = '', string $error = ''): RedirectResponse {
if ($this->userId === null) {
return new RedirectResponse(
$this->urlGenerator->linkToRoute('settings.PersonalSettings.index', ['section' => 'migration']) .
'?googleToken=error&message=' . urlencode($this->l->t('No logged in user'))
$this->urlGenerator->linkToRoute('settings.PersonalSettings.index', ['section' => 'migration'])
. '?googleToken=error&message=' . urlencode($this->l->t('No logged in user'))
);
}

Expand All @@ -177,6 +178,7 @@ public function oauthRedirect(string $code = '', string $state = '', string $sco
$scopesArray = [
'can_access_drive' => in_array(self::DRIVE_SCOPE, $scopes) ? 1 : 0,
'can_access_contacts' => in_array(self::CONTACTS_SCOPE, $scopes) ? 1 : 0,
'can_access_other_contacts' => in_array(self::CONTACTS_OTHER_SCOPE, $scopes) ? 1 : 0,
'can_access_photos' => in_array(self::PHOTOS_SCOPE, $scopes) ? 1 : 0,
'can_access_calendar' => (in_array(self::CALENDAR_SCOPE, $scopes) && in_array(self::CALENDAR_EVENTS_SCOPE, $scopes)) ? 1 : 0,
];
Expand Down Expand Up @@ -214,8 +216,8 @@ public function oauthRedirect(string $code = '', string $state = '', string $sco
);
} else {
return new RedirectResponse(
$this->urlGenerator->linkToRoute('settings.PersonalSettings.index', ['section' => 'migration']) .
'?googleToken=success'
$this->urlGenerator->linkToRoute('settings.PersonalSettings.index', ['section' => 'migration'])
. '?googleToken=success'
);
}
}
Expand All @@ -228,8 +230,8 @@ public function oauthRedirect(string $code = '', string $state = '', string $sco
$result = $this->l->t('Error during OAuth exchanges');
}
return new RedirectResponse(
$this->urlGenerator->linkToRoute('settings.PersonalSettings.index', ['section' => 'migration']) .
'?googleToken=error&message=' . urlencode($result)
$this->urlGenerator->linkToRoute('settings.PersonalSettings.index', ['section' => 'migration'])
. '?googleToken=error&message=' . urlencode($result)
);
}

Expand Down
65 changes: 52 additions & 13 deletions lib/Service/GoogleContactsAPIService.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use OCA\DAV\CardDAV\CardDavBackend;
use OCA\Google\AppInfo\Application;
use OCP\Contacts\IManager as IContactManager;
use OCP\IConfig;
use Psr\Log\LoggerInterface;
use Sabre\VObject\Component\VCard;
use Throwable;
Expand All @@ -33,6 +34,7 @@ public function __construct(
private IContactManager $contactsManager,
private CardDavBackend $cdBackend,
private GoogleAPIService $googleApiService,
private IConfig $config,
) {
}

Expand Down Expand Up @@ -72,29 +74,41 @@ public function getContactGroupsById(string $userId): array {
* @return array
*/
public function getContactNumber(string $userId): array {
$nbContacts = 0;
$params = [
'personFields' => implode(',', [
'names',
]),
'pageSize' => 100,
];
do {
$result = $this->googleApiService->request($userId, 'v1/people/me/connections', $params, 'GET', 'https://people.googleapis.com/');
if (isset($result['error'])) {
return $result;
$result = [];
$contacts = $this->googleApiService->request($userId, 'v1/people/me/connections', $params, 'GET', 'https://people.googleapis.com/');
if (isset($contacts['error'])) {
return $contacts;
}
$result['nbContacts'] = $contacts['totalItems'] ?? 0;
$scopes = $this->config->getUserValue($userId, Application::APP_ID, 'user_scopes', '{}');
$scopes = json_decode($scopes, true);
if (isset($scopes['can_access_other_contacts']) && $scopes['can_access_other_contacts'] === 1) {
$params = [
'readMask' => implode(',', [
'names',
'emailAddresses',
]),
];
$otherContacts = $this->googleApiService->request($userId, 'v1/otherContacts', $params, 'GET', 'https://people.googleapis.com/');
if (isset($otherContacts['error'])) {
return $otherContacts;
}
$nbContacts += count($result['connections'] ?? []);
$params['pageToken'] = $result['nextPageToken'] ?? '';
} while (isset($result['nextPageToken']));
return ['nbContacts' => $nbContacts];
$result['nbOtherContacts'] = $otherContacts['totalSize'] ?? 0;
}
return $result;
}

/**
* @param string $userId
* @param bool $otherContacts
* @return Generator
*/
public function getContactList(string $userId): Generator {
public function getContactList(string $userId, bool $otherContacts = false): Generator {
$params = [
'personFields' => implode(',', [
'addresses',
Expand Down Expand Up @@ -127,6 +141,31 @@ public function getContactList(string $userId): Generator {
}
$params['pageToken'] = $result['nextPageToken'] ?? '';
} while (isset($result['nextPageToken']));
if ($otherContacts) {
$params = [
'readMask' => implode(',', [
'emailAddresses',
'metadata',
'names',
'phoneNumbers',
'photos',
]),
'sources' => 'READ_SOURCE_TYPE_CONTACT',
'pageSize' => 100,
];
do {
$result = $this->googleApiService->request($userId, 'v1/otherContacts', $params, 'GET', 'https://people.googleapis.com/');
if (isset($result['error'])) {
return $result;
}
if (isset($result['otherContacts']) && is_array($result['otherContacts'])) {
foreach ($result['otherContacts'] as $contact) {
yield $contact;
}
}
$params['pageToken'] = $result['nextPageToken'] ?? '';
} while (isset($result['nextPageToken']));
}
return [];
}

Expand Down Expand Up @@ -166,9 +205,9 @@ public function importContacts(string $userId, ?string $uri, int $key, ?string $
}
$existingAddressBook = $addressBook;
}

$otherContacts = $this->config->getUserValue($userId, Application::APP_ID, 'consider_other_contacts', '0') === '1';
$groupsById = $this->getContactGroupsById($userId);
$contacts = $this->getContactList($userId);
$contacts = $this->getContactList($userId, $otherContacts);
$nbAdded = 0;
$nbUpdated = 0;
$totalContactNumber = 0;
Expand Down
10 changes: 7 additions & 3 deletions lib/Settings/Personal.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@
use OCA\Google\Service\SecretService;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Services\IInitialState;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\IConfig;
use OCP\IUserManager;
use OCP\Settings\ISettings;
use Throwable;

class Personal implements ISettings {

Expand Down Expand Up @@ -45,6 +47,7 @@ public function getForm(): TemplateResponse {
$photoOutputDir = $photoOutputDir ?: '/Google Photos';
$considerSharedFiles = $this->config->getUserValue($this->userId, Application::APP_ID, 'consider_shared_files', '0') === '1';
$considerSharedAlbums = $this->config->getUserValue($this->userId, Application::APP_ID, 'consider_shared_albums', '0') === '1';
$considerOtherContacts = $this->config->getUserValue($this->userId, Application::APP_ID, 'consider_other_contacts', '0') === '1';
$documentFormat = $this->config->getUserValue($this->userId, Application::APP_ID, 'document_format', 'openxml');
if (!in_array($documentFormat, ['openxml', 'opendoc'])) {
$documentFormat = 'openxml';
Expand Down Expand Up @@ -83,6 +86,7 @@ public function getForm(): TemplateResponse {
'user_quota' => $user === null ? '' : $user->getQuota(),
'consider_shared_files' => $considerSharedFiles,
'consider_shared_albums' => $considerSharedAlbums,
'consider_other_contacts' => $considerOtherContacts,
'document_format' => $documentFormat,
'drive_output_dir' => $driveOutputDir,
'photo_output_dir' => $photoOutputDir,
Expand All @@ -101,16 +105,16 @@ public function getPriority(): int {
}

/**
* @param \OCP\Files\Folder $userRoot
* @param Folder $userRoot
* @param string $outputDir
* @return bool|float|int
* @throws NotFoundException
*/
public static function getFreeSpace(\OCP\Files\Folder $userRoot, string $outputDir) {
public static function getFreeSpace(Folder $userRoot, string $outputDir) {
try {
// OutputDir can be on an external storage which can have more free space
$freeSpace = $userRoot->get($outputDir)->getStorage()->free_space('/');
} catch (\Throwable $e) {
} catch (Throwable $e) {
$freeSpace = false;
}
return $freeSpace !== false && $freeSpace > 0 ? $freeSpace : $userRoot->getStorage()->free_space('/');
Expand Down
21 changes: 19 additions & 2 deletions src/components/PersonalSettings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,22 @@
</NcButton>
</div>
<br>
<div v-if="nbContacts > 0"
<div v-if="nbContacts + nbOtherContacts >= 0"
id="google-contacts">
<h3>{{ t('integration_google', 'Contacts') }}</h3>
<div class="line">
<NcCheckboxRadioSwitch v-if="!importingContacts && state.user_scopes.can_access_other_contacts"
:model-value="state.consider_other_contacts"
@update:model-value="onContactsConsiderOtherChange">
{{ t('integration_google', 'Include other contacts') }}
</NcCheckboxRadioSwitch>
</div>
<div class="line">
<label>
<AccountGroupIcon />
{{ t('integration_google', '{amount} Google contacts', { amount: nbContacts }) }}
{{ state.consider_other_contacts
? t('integration_google', '{amount} Google + {otherAmount} other contacts', { amount: nbContacts, otherAmount: nbOtherContacts })
: t('integration_google', '{amount} Google contacts', { amount: nbContacts }) }}
</label>
<NcButton @click="onImportContacts">
<template #icon>
Expand Down Expand Up @@ -310,8 +319,10 @@ export default {
calendars: [],
importingCalendar: {},
// contacts
considerOtherContacts: false,
addressbooks: [],
nbContacts: 0,
nbOtherContacts: 0,
showAddressBooks: false,
selectedAddressBook: 0,
newAddressBookName: 'Google Contacts import',
Expand Down Expand Up @@ -466,6 +477,7 @@ export default {
'https://www.googleapis.com/auth/contacts.readonly',
'https://www.googleapis.com/auth/photoslibrary.readonly',
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/contacts.other.readonly',
]
const requestUrl = 'https://accounts.google.com/o/oauth2/v2/auth?'
+ 'client_id=' + encodeURIComponent(this.state.client_id)
Expand Down Expand Up @@ -598,6 +610,7 @@ export default {
.then((response) => {
if (response.data && Object.keys(response.data).length > 0) {
this.nbContacts = response.data.nbContacts
this.nbOtherContacts = response.data.nbOtherContacts ?? 0
}
})
.catch((error) => {
Expand Down Expand Up @@ -816,6 +829,10 @@ export default {
myHumanFileSize(bytes, approx = false, si = false, dp = 1) {
return humanFileSize(bytes, approx, si, dp)
},
onContactsConsiderOtherChange(newValue) {
this.state.consider_other_contacts = newValue
this.saveOptions({ consider_other_contacts: this.state.consider_other_contacts ? '1' : '0' }, this.getNbGoogleContacts)
},
onDriveConsiderSharedChange(newValue) {
this.state.consider_shared_files = !newValue
this.saveOptions({ consider_shared_files: this.state.consider_shared_files ? '1' : '0' }, this.getGoogleDriveInfo)
Expand Down