From a9232db5d5fca6426591910fdc57c58813747fe0 Mon Sep 17 00:00:00 2001 From: matthias Date: Mon, 30 Mar 2020 23:32:37 +0200 Subject: [PATCH] allow for avatar downloads from social networks Signed-off-by: call-me-matt --- README.md | 2 +- appinfo/app.php | 26 +++ appinfo/info.xml | 4 + appinfo/routes.php | 4 +- css/icons.scss | 8 + img/facebook.svg | 1 + img/instagram.svg | 1 + img/license.txt | 6 + img/mastodon.svg | 1 + img/sync.svg | 3 + img/tumblr.svg | 76 +++++++ img/twitter.svg | 1 + l10n/uk.json | 2 +- lib/AppInfo/Application.php | 37 ++++ lib/Controller/PageController.php | 14 +- lib/Controller/SocialApiController.php | 95 +++++++++ .../Social/CompositeSocialProvider.php | 95 +++++++++ lib/Service/Social/FacebookProvider.php | 99 ++++++++++ lib/Service/Social/ISocialProvider.php | 45 +++++ lib/Service/Social/InstagramProvider.php | 87 ++++++++ lib/Service/Social/MastodonProvider.php | 78 ++++++++ lib/Service/Social/TumblrProvider.php | 57 ++++++ lib/Service/Social/TwitterProvider.php | 95 +++++++++ lib/Service/SocialApiService.php | 185 ++++++++++++++++++ lib/Settings/AdminSettings.php | 78 ++++++++ package-lock.json | 16 +- package.json | 1 + src/adminSettings.js | 34 ++++ src/components/AdminSettings.vue | 35 ++++ src/components/ContactDetails.vue | 4 +- .../ContactDetails/ContactDetailsAvatar.vue | 86 +++++++- src/store/contacts.js | 4 +- templates/settings/admin.php | 5 + tests/unit/Controller/PageControllerTest.php | 16 +- tests/unit/Service/SocialApiServiceTest.php | 132 +++++++++++++ webpack.common.js | 7 +- 36 files changed, 1413 insertions(+), 27 deletions(-) create mode 100644 appinfo/app.php create mode 100644 img/facebook.svg create mode 100644 img/instagram.svg create mode 100644 img/license.txt create mode 100644 img/mastodon.svg create mode 100644 img/sync.svg create mode 100644 img/tumblr.svg create mode 100644 img/twitter.svg create mode 100644 lib/AppInfo/Application.php create mode 100644 lib/Controller/SocialApiController.php create mode 100644 lib/Service/Social/CompositeSocialProvider.php create mode 100644 lib/Service/Social/FacebookProvider.php create mode 100644 lib/Service/Social/ISocialProvider.php create mode 100644 lib/Service/Social/InstagramProvider.php create mode 100644 lib/Service/Social/MastodonProvider.php create mode 100644 lib/Service/Social/TumblrProvider.php create mode 100644 lib/Service/Social/TwitterProvider.php create mode 100644 lib/Service/SocialApiService.php create mode 100644 lib/Settings/AdminSettings.php create mode 100644 src/adminSettings.js create mode 100644 src/components/AdminSettings.vue create mode 100644 templates/settings/admin.php create mode 100644 tests/unit/Service/SocialApiServiceTest.php diff --git a/README.md b/README.md index c9a8c992f..4de478854 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # Nextcloud Contacts -![Downloads](https://img.shields.io/github/downloads/nextcloud/contacts/total?style=flat-square) +![Downloads](https://img.shields.io/github/downloads/nextcloud/contacts/total.svg?style=flat-square) [![Codacy Badge](https://img.shields.io/codacy/grade/ea24ea9fccb942419d73ec05105938aa.svg?style=flat-square)](https://app.codacy.com/app/skjnldsv/contacts) [![Code coverage](https://img.shields.io/codecov/c/github/nextcloud/contacts.svg?style=flat-square)](https://codecov.io/gh/nextcloud/contacts/) [![Dependabot status](https://img.shields.io/badge/Dependabot-enabled-brightgreen.svg?longCache=true&style=flat-square&logo=dependabot)](https://dependabot.com) diff --git a/appinfo/app.php b/appinfo/app.php new file mode 100644 index 000000000..69901b4f4 --- /dev/null +++ b/appinfo/app.php @@ -0,0 +1,26 @@ + + * + * @author John Molakvoæ + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +use OCA\Contacts\AppInfo\Application; + +$app = \OC::$server->query(Application::class); diff --git a/appinfo/info.xml b/appinfo/info.xml index a3f7bdce3..5fa7b3bff 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -50,4 +50,8 @@ 4 + + + OCA\Contacts\Settings\AdminSettings + diff --git a/appinfo/routes.php b/appinfo/routes.php index e09de7636..647b8f27d 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -25,6 +25,8 @@ 'routes' => [ ['name' => 'page#index', 'url' => '/', 'verb' => 'GET'], ['name' => 'page#index', 'url' => '/{group}', 'verb' => 'GET', 'postfix' => 'group'], - ['name' => 'page#index', 'url' => '/{group}/{contact}', 'verb' => 'GET', 'postfix' => 'group.contact'] + ['name' => 'page#index', 'url' => '/{group}/{contact}', 'verb' => 'GET', 'postfix' => 'group.contact'], + ['name' => 'social_api#update_contact', 'url' => '/api/v1/social/avatar/{network}/{addressbookId}/{contactId}', 'verb' => 'PUT'], + ['name' => 'social_api#set_app_config', 'url' => '/api/v1/social/config/{key}', 'verb' => 'POST'], ] ]; diff --git a/css/icons.scss b/css/icons.scss index 0d7c99d04..0685ea095 100644 --- a/css/icons.scss +++ b/css/icons.scss @@ -30,6 +30,14 @@ @include icon-black-white('no-calendar', 'contacts', 1); @include icon-black-white('language', 'contacts', 2); @include icon-black-white('clone', 'contacts', 2); +@include icon-black-white('sync', 'contacts', 2); + +// social network icons: +@include icon-black-white('facebook', 'contacts', 2); // “facebook (fab)” by fontawesome.com is licensed under CC BY 4.0. (https://fontawesome.com/icons/facebook?style=brands) +@include icon-black-white('instagram', 'contacts', 2); // “instagram (fab)” by fontawesome.com is licensed under CC BY 4.0. (https://fontawesome.com/icons/instagram?style=brands) +@include icon-black-white('mastodon', 'contacts', 2); // “mastodon (fab)” by fontawesome.com is licensed under CC BY 4.0. (https://fontawesome.com/icons/mastodon?style=brands) +@include icon-black-white('tumblr', 'contacts', 2); // “tumblr (fab)” by fontawesome.com is licensed under CC BY 4.0. (https://fontawesome.com/icons/tumblr?style=brands) +@include icon-black-white('twitter', 'contacts', 2); // “twitter (fab)” by fontawesome.com is licensed under CC BY 4.0. (https://fontawesome.com/icons/twitter?style=brands) .icon-up-force-white { // using #fffffe to trick the accessibility dark theme icon invert diff --git a/img/facebook.svg b/img/facebook.svg new file mode 100644 index 000000000..649b49451 --- /dev/null +++ b/img/facebook.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/instagram.svg b/img/instagram.svg new file mode 100644 index 000000000..53ab31190 --- /dev/null +++ b/img/instagram.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/license.txt b/img/license.txt new file mode 100644 index 000000000..d4e74fdbe --- /dev/null +++ b/img/license.txt @@ -0,0 +1,6 @@ +# social network icons: +* “facebook (fab)” by fontawesome.com is licensed under CC BY 4.0. (https://fontawesome.com/icons/facebook?style=brands) +* “instagram (fab)” by fontawesome.com is licensed under CC BY 4.0. (https://fontawesome.com/icons/instagram?style=brands) +* “mastodon (fab)” by fontawesome.com is licensed under CC BY 4.0. (https://fontawesome.com/icons/mastodon?style=brands) +* “tumblr (fab)” by fontawesome.com is licensed under CC BY 4.0. (https://fontawesome.com/icons/tumblr?style=brands) +* “twitter (fab)” by fontawesome.com is licensed under CC BY 4.0. (https://fontawesome.com/icons/twitter?style=brands) diff --git a/img/mastodon.svg b/img/mastodon.svg new file mode 100644 index 000000000..4257e7c64 --- /dev/null +++ b/img/mastodon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/sync.svg b/img/sync.svg new file mode 100644 index 000000000..6cecc8d0a --- /dev/null +++ b/img/sync.svg @@ -0,0 +1,3 @@ + + + diff --git a/img/tumblr.svg b/img/tumblr.svg new file mode 100644 index 000000000..763bc4739 --- /dev/null +++ b/img/tumblr.svg @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/img/twitter.svg b/img/twitter.svg new file mode 100644 index 000000000..9ac9e0b99 --- /dev/null +++ b/img/twitter.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/l10n/uk.json b/l10n/uk.json index 1dfd14b7b..11bc8b188 100644 --- a/l10n/uk.json +++ b/l10n/uk.json @@ -155,4 +155,4 @@ "Your web browser is out of date" : "Ваш бразуер застарів", "This application is not compatible with Internet Explorer" : "Застосунок не сумісний з Internet Explorer" },"pluralForm" :"nplurals=4; plural=(n % 1 == 0 && n % 10 == 1 && n % 100 != 11 ? 0 : n % 1 == 0 && n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14) ? 1 : n % 1 == 0 && (n % 10 ==0 || (n % 10 >=5 && n % 10 <=9) || (n % 100 >=11 && n % 100 <=14 )) ? 2: 3);" -} \ No newline at end of file +} diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php new file mode 100644 index 000000000..565fe5b75 --- /dev/null +++ b/lib/AppInfo/Application.php @@ -0,0 +1,37 @@ + + * + * @author John Molakvoæ + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ +namespace OCA\Contacts\AppInfo; + +use OCP\AppFramework\App; + +class Application extends App { + public const APP_ID = 'contacts'; + + public function __construct() { + parent::__construct(self::APP_ID); + } + + public const AVAIL_SETTINGS = [ + 'allowSocialSync' => 'yes', + ]; +} diff --git a/lib/Controller/PageController.php b/lib/Controller/PageController.php index 0ea64fd33..d40b74ce3 100644 --- a/lib/Controller/PageController.php +++ b/lib/Controller/PageController.php @@ -23,10 +23,11 @@ namespace OCA\Contacts\Controller; +use OCA\Contacts\Service\SocialApiService; use OCP\AppFramework\Controller; use OCP\AppFramework\Http\TemplateResponse; -use OCP\IInitialStateService; use OCP\IConfig; +use OCP\IInitialStateService; use OCP\IRequest; use OCP\L10N\IFactory; use OCP\Util; @@ -43,17 +44,22 @@ class PageController extends Controller { /** @var IFactory */ private $languageFactory; + /** @var SocialApiService */ + private $socialApiService; + public function __construct(string $appName, IRequest $request, IConfig $config, IInitialStateService $initialStateService, - IFactory $languageFactory) { + IFactory $languageFactory, + SocialApiService $socialApiService) { parent::__construct($appName, $request); $this->appName = $appName; $this->config = $config; $this->initialStateService = $initialStateService; $this->languageFactory = $languageFactory; + $this->socialApiService = $socialApiService; } /** @@ -65,10 +71,12 @@ public function __construct(string $appName, public function index(): TemplateResponse { $locales = $this->languageFactory->findAvailableLocales(); $defaultProfile = $this->config->getAppValue($this->appName, 'defaultProfile', 'HOME'); + $supportedNetworks = $this->socialApiService->getSupportedNetworks(); $this->initialStateService->provideInitialState($this->appName, 'locales', $locales); $this->initialStateService->provideInitialState($this->appName, 'defaultProfile', $defaultProfile); - + $this->initialStateService->provideInitialState($this->appName, 'supportedNetworks', $supportedNetworks); + Util::addScript($this->appName, 'contacts'); Util::addStyle($this->appName, 'contacts'); diff --git a/lib/Controller/SocialApiController.php b/lib/Controller/SocialApiController.php new file mode 100644 index 000000000..4898d9151 --- /dev/null +++ b/lib/Controller/SocialApiController.php @@ -0,0 +1,95 @@ + + * + * @author Matthias Heinisch + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Contacts\Controller; + +use OCA\Contacts\AppInfo\Application; +use OCA\Contacts\Service\SocialApiService; +use OCP\AppFramework\ApiController; +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\JSONResponse; +use OCP\IConfig; +use OCP\IRequest; + +class SocialApiController extends ApiController { + + /** @var IConfig */ + private $config; + + /** @var SocialApiService */ + private $socialApiService; + + public function __construct(IRequest $request, + IConfig $config, + SocialApiService $socialApiService) { + parent::__construct(Application::APP_ID, $request); + + $this->config = $config; + $this->socialApiService = $socialApiService; + } + + + /** + * update appconfig (admin setting) + * + * @param {String} key the identifier to change + * @param {String} allow the value to set + * + * @returns {JSONResponse} an empty JSONResponse with respective http status code + */ + public function setAppConfig($key, $allow) { + $permittedKeys = ['allowSocialSync']; + if (!in_array($key, $permittedKeys)) { + return new JSONResponse([], Http::STATUS_FORBIDDEN); + } + $this->config->setAppValue(Application::APP_ID, $key, $allow); + return new JSONResponse([], Http::STATUS_OK); + } + + /** + * @NoAdminRequired + * + * returns an array of supported social networks + * + * @returns {array} array of the supported social networks + */ + public function getSupportedNetworks() : array { + return $this->socialApiService->getSupportedNetworks(); + } + + + /** + * @NoAdminRequired + * + * Retrieves social profile data for a contact and updates the entry + * + * @param {String} addressbookId the addressbook identifier + * @param {String} contactId the contact identifier + * @param {String} network the social network to use (if unkown: take first match) + * + * @returns {JSONResponse} an empty JSONResponse with respective http status code + */ + public function updateContact(string $addressbookId, string $contactId, string $network) : JSONResponse { + return $this->socialApiService->updateContact($addressbookId, $contactId, $network); + } +} diff --git a/lib/Service/Social/CompositeSocialProvider.php b/lib/Service/Social/CompositeSocialProvider.php new file mode 100644 index 000000000..a5f6e484b --- /dev/null +++ b/lib/Service/Social/CompositeSocialProvider.php @@ -0,0 +1,95 @@ + + * + * @author Matthias Heinisch + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Contacts\Service\Social; + +/** + * Composition of all social providers for easier usage + */ +class CompositeSocialProvider { + + /** @var ISocialProvider[] */ + private $providers; + + public function __construct(InstagramProvider $instagramProvider, + MastodonProvider $mastodonProvider, + FacebookProvider $facebookProvider, + TwitterProvider $twitterProvider, + TumblrProvider $tumblrProvider) { + + // This determines the priority of known providers + $this->providers = [ + 'instagram' => $instagramProvider, + 'mastodon' => $mastodonProvider, + 'twitter' => $twitterProvider, + 'facebook' => $facebookProvider, + 'tumblr' => $tumblrProvider, + ]; + } + + /** + * returns an array of supported social providers + * + * @returns String[] array of the supported social networks + */ + public function getSupportedNetworks() : array { + return array_keys($this->providers); + } + + + /** + * generate download url for a social entry + * + * @param array socialEntries all social data from the contact + * @param String network the choice which network to use (fallback: take first available) + * + * @returns String the url to the requested information or null in case of errors + */ + public function getSocialConnector(array $socialEntries, string $network) : ?string { + $connector = null; + $selection = $this->providers; + // check if dedicated network selected + if (isset($this->providers[$network])) { + $selection = [$network => $this->providers[$network]]; + } + + // check selected providers in order + foreach ($selection as $type => $socialProvider) { + + // search for this network in user's profile + foreach ($socialEntries as $socialEntry) { + if (strtolower($type) === strtolower($socialEntry['type'])) { + $profileId = $socialProvider->cleanupId($socialEntry['value']); + if (!is_null($profileId)) { + $connector = $socialProvider->getImageUrl($profileId); + } + break; + } + } + if ($connector) { + break; + } + } + return ($connector); + } +} diff --git a/lib/Service/Social/FacebookProvider.php b/lib/Service/Social/FacebookProvider.php new file mode 100644 index 000000000..8d2ca26b8 --- /dev/null +++ b/lib/Service/Social/FacebookProvider.php @@ -0,0 +1,99 @@ + + * + * @author Matthias Heinisch + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Contacts\Service\Social; + +use OCP\Http\Client\IClientService; + +class FacebookProvider implements ISocialProvider { + + /** @var IClientService */ + private $httpClient; + + public function __construct(IClientService $httpClient) { + $this->httpClient = $httpClient->NewClient(); + } + + /** + * Returns the profile-id + * + * @param {string} the value from the contact's x-socialprofile + * + * @return string + */ + public function cleanupId(string $candidate):string { + $candidate = basename($candidate); + if (!is_numeric($candidate)) { + $candidate = $this->findFacebookId($candidate); + } + return $candidate; + } + + /** + * Returns the profile-picture url + * + * @param {string} profileId the profile-id + * + * @return string + */ + public function getImageUrl(string $profileId):string { + $recipe = 'https://graph.facebook.com/{socialId}/picture?width=720'; + $connector = str_replace("{socialId}", $profileId, $recipe); + return $connector; + } + + /** + * Tries to get the facebook id from facebook profile name + * e. g. "zuck" --> "4" + * Fallback: return profile name + * (will give oauth error from facebook except if profile is public) + * + * @param {string} profileName the user's profile name + * + * @return string + */ + protected function findFacebookId(string $profileName):string { + try { + $result = $this->httpClient->get("https://facebook.com/".$profileName); + if($result->getStatusCode() !== 200) { + return $profileName; + } + $htmlResult = new \DOMDocument(); + $htmlResult->loadHTML($result->getBody()); + $metas = $htmlResult->getElementsByTagName('meta'); + foreach ($metas as $meta) { + foreach ($meta->attributes as $attr) { + $value = $attr->nodeValue; + if (strpos($value, "/profile/")) { + $value = str_replace('fb://profile/', '', $value); + return($value); + } + } + } + // keyword not found - page changed? + return $profileName; + } catch (\Exception $e) { + return $profileName; + } + } +} diff --git a/lib/Service/Social/ISocialProvider.php b/lib/Service/Social/ISocialProvider.php new file mode 100644 index 000000000..1415f4d09 --- /dev/null +++ b/lib/Service/Social/ISocialProvider.php @@ -0,0 +1,45 @@ + + * + * @author Matthias Heinisch + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Contacts\Service\Social; + +interface ISocialProvider { + + /** + * Returns the profile-id + * + * @param {string} the value from the contact's x-socialprofile + * + * @return string + */ + public function cleanupId(string $candidate):?string ; + + /** + * Returns the profile-picture url + * + * @param {string} profileId the profile-id + * + * @return string|null + */ + public function getImageUrl(string $profileId):?string ; +} diff --git a/lib/Service/Social/InstagramProvider.php b/lib/Service/Social/InstagramProvider.php new file mode 100644 index 000000000..36c5a3d6d --- /dev/null +++ b/lib/Service/Social/InstagramProvider.php @@ -0,0 +1,87 @@ + + * + * @author Matthias Heinisch + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Contacts\Service\Social; + +use OCP\Http\Client\IClientService; + +class InstagramProvider implements ISocialProvider { + + /** @var IClientService */ + private $httpClient; + + public function __construct(IClientService $httpClient) { + $this->httpClient = $httpClient->NewClient(); + } + + /** + * Returns the profile-id + * + * @param {string} the value from the contact's x-socialprofile + * + * @return string + */ + public function cleanupId(string $candidate):string { + return basename($candidate); + } + + /** + * Returns the profile-picture url + * + * @param {string} profileId the profile-id + * + * @return string|null + */ + public function getImageUrl(string $profileId):?string { + $recipe = 'https://www.instagram.com/{socialId}/?__a=1'; + $connector = str_replace("{socialId}", $profileId, $recipe); + $connector = $this->getFromJson($connector, 'graphql->user->profile_pic_url_hd'); + return $connector; + } + + /** + * extracts desired value from a json + * + * @param {string} url the target from where to fetch the json + * @param {String} the desired key to filter for (nesting possible with '->') + * + * @returns {String} the extracted value or null if not present + */ + protected function getFromJson(string $url, string $desired) : ?string { + try { + $result = $this->httpClient->get($url); + + $jsonResult = json_decode($result->getBody(),true); + $location = explode('->' , $desired); + foreach ($location as $loc) { + if (!isset($jsonResult[$loc])) { + return null; + } + $jsonResult = $jsonResult[$loc]; + } + return $jsonResult; + } catch (Exception $e) { + return null; + } + } +} diff --git a/lib/Service/Social/MastodonProvider.php b/lib/Service/Social/MastodonProvider.php new file mode 100644 index 000000000..bcbde9f32 --- /dev/null +++ b/lib/Service/Social/MastodonProvider.php @@ -0,0 +1,78 @@ + + * + * @author Matthias Heinisch + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Contacts\Service\Social; + +use OCP\Http\Client\IClientService; + +class MastodonProvider implements ISocialProvider { + + /** @var IClientService */ + private $httpClient; + + public function __construct(IClientService $httpClient) { + $this->httpClient = $httpClient->NewClient(); + } + + /** + * Returns the profile-id + * + * @param {string} the value from the contact's x-socialprofile + * + * @return string + */ + public function cleanupId(string $candidate):?string { + try { + if (strpos($candidate, '@') === 0) { + $user_server = explode('@', $candidate); + $candidate = 'https://' . $user_server[2] . '/@' . $user_server[1]; + } + } catch (Exception $e) { + $candidate = null; + } + return $candidate; + } + + /** + * Returns the profile-picture url + * + * @param {string} profileUrl link to the profile + * + * @return string|null + */ + public function getImageUrl(string $profileUrl):?string { + try { + $result = $this->httpClient->get($profileUrl); + + $htmlResult = new \DOMDocument(); + $htmlResult->loadHTML($result->getBody()); + $img = $htmlResult->getElementById('profile_page_avatar'); + if (!is_null($img)) { + return $img->getAttribute("data-original"); + } + return null; + } catch (Exception $e) { + return null; + } + } +} diff --git a/lib/Service/Social/TumblrProvider.php b/lib/Service/Social/TumblrProvider.php new file mode 100644 index 000000000..71f2fa71a --- /dev/null +++ b/lib/Service/Social/TumblrProvider.php @@ -0,0 +1,57 @@ + + * + * @author Matthias Heinisch + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Contacts\Service\Social; + +class TumblrProvider implements ISocialProvider { + public function __construct() { + } + + /** + * Returns the profile-id + * + * @param {string} the value from the contact's x-socialprofile + * + * @return string + */ + public function cleanupId(string $candidate):?string { + $subdomain = '/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i'; // subdomain + if (preg_match($subdomain, $candidate, $matches)) { + $candidate = $matches[1]; + } + return $candidate; + } + + /** + * Returns the profile-picture url + * + * @param {string} profileId the profile-id + * + * @return string|null + */ + public function getImageUrl(string $profileId):?string { + $recipe = 'https://api.tumblr.com/v2/blog/{socialId}/avatar/512'; + $connector = str_replace("{socialId}", $profileId, $recipe); + return $connector; + } +} diff --git a/lib/Service/Social/TwitterProvider.php b/lib/Service/Social/TwitterProvider.php new file mode 100644 index 000000000..953eb1a09 --- /dev/null +++ b/lib/Service/Social/TwitterProvider.php @@ -0,0 +1,95 @@ + + * + * @author Matthias Heinisch + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Contacts\Service\Social; + +use OCP\Http\Client\IClientService; + +class TwitterProvider implements ISocialProvider { + + /** @var IClientService */ + private $httpClient; + + public function __construct(IClientService $httpClient) { + $this->httpClient = $httpClient->NewClient(); + } + + /** + * Returns the profile-id + * + * @param {string} the value from the contact's x-socialprofile + * + * @return string + */ + public function cleanupId(string $candidate):string { + $candidate = basename($candidate); + if ($candidate[0] === '@') { + $candidate = substr($candidate, 1); + } + return $candidate; + } + + /** + * Returns the profile-picture url + * + * @param {string} profileId the profile-id + * + * @return string|null + */ + public function getImageUrl(string $profileId):?string { + $recipe = 'https://mobile.twitter.com/{socialId}'; + $connector = str_replace("{socialId}", $profileId, $recipe); + $connector = $this->getFromHtml($connector, '_normal'); + return $connector; + } + + /** + * extracts desired value from an html page + * + * @param {string} url the target from where to fetch the content + * @param {String} the desired catchword to filter for + * + * @returns {String} the extracted value (first match) or null if not present + */ + protected function getFromHtml(string $url, string $desired) : ?string { + try { + $result = $this->httpClient->get($url); + + $htmlResult = new \DOMDocument(); + $htmlResult->loadHTML($result->getBody()); + $imgs = $htmlResult->getElementsByTagName('img'); + foreach ($imgs as $img) { + foreach ($img->attributes as $attr) { + $value = $attr->nodeValue; + if (strpos($value, $desired)) { + $value = str_replace("normal", "400x400", $value); + return $value; + } + } + } + return null; + } catch (Exception $e) { + return null; + } + } +} diff --git a/lib/Service/SocialApiService.php b/lib/Service/SocialApiService.php new file mode 100644 index 000000000..154e0295a --- /dev/null +++ b/lib/Service/SocialApiService.php @@ -0,0 +1,185 @@ + + * + * @author Matthias Heinisch + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Contacts\Service; + +use OCA\Contacts\Service\Social\CompositeSocialProvider; +use OCA\Contacts\AppInfo\Application; + +use OCP\Contacts\IManager; +use OCP\IAddressBook; + +use OCP\IConfig; +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\JSONResponse; +use OCP\Http\Client\IClientService; + +class SocialApiService { + + /** @var CompositeSocialProvider */ + private $socialProvider; + /** @var IManager */ + private $manager; + /** @var IConfig */ + private $config; + /** @var IClientService */ + private $clientService; + + public function __construct( + CompositeSocialProvider $socialProvider, + IManager $manager, + IConfig $config, + IClientService $clientService) { + $this->socialProvider = $socialProvider; + $this->manager = $manager; + $this->config = $config; + $this->clientService = $clientService; + } + + + /** + * @NoAdminRequired + * + * returns an array of supported social networks + * + * @returns {array} array of the supported social networks + */ + public function getSupportedNetworks() : array { + $isAdminEnabled = $this->config->getAppValue(Application::APP_ID, 'allowSocialSync', 'yes'); + if ($isAdminEnabled !== 'yes') { + return []; + } + return $this->socialProvider->getSupportedNetworks(); + } + + + /** + * @NoAdminRequired + * + * Adds/updates photo for contact + * + * @param {pointer} contact reference to the contact to update + * @param {string} imageType the image type of the photo + * @param {string} photo the photo as base64 string + */ + protected function addPhoto(array &$contact, string $imageType, string $photo) { + $version = $contact['VERSION']; + + if (!empty($contact['PHOTO'])) { + // overwriting without notice! + } + + if ($version >= 4.0) { + // overwrite photo + $contact['PHOTO'] = "data:" . $imageType . ";base64," . $photo; + } elseif ($version >= 3.0) { + // add new photo + $imageType = str_replace('image/', '', $imageType); + $contact['PHOTO;ENCODING=b;TYPE=' . $imageType . ';VALUE=BINARY'] = $photo; + + // remove previous photo (necessary as new attribute is not equal to 'PHOTO') + $contact['PHOTO'] = ''; + } + } + + + /** + * @NoAdminRequired + * + * Gets the addressbook of an addressbookId + * + * @param {String} addressbookId the identifier of the addressbook + * + * @returns {IAddressBook} the corresponding addressbook or null + */ + protected function getAddressBook(string $addressbookId) : ?IAddressBook { + $addressBook = null; + $addressBooks = $this->manager->getUserAddressBooks(); + foreach ($addressBooks as $ab) { + if ($ab->getUri() === $addressbookId) { + $addressBook = $ab; + } + } + return $addressBook; + } + + + /** + * @NoAdminRequired + * + * Retrieves social profile data for a contact and updates the entry + * + * @param {String} addressbookId the addressbook identifier + * @param {String} contactId the contact identifier + * @param {String} network the social network to use (if unkown: take first match) + * + * @returns {JSONResponse} an empty JSONResponse with respective http status code + */ + public function updateContact(string $addressbookId, string $contactId, string $network) : JSONResponse { + $url = null; + + try { + // get corresponding addressbook + $addressBook = $this->getAddressBook($addressbookId); + if (is_null($addressBook)) { + return new JSONResponse([], Http::STATUS_BAD_REQUEST); + } + + // search contact in that addressbook, get social data + $contact = $addressBook->search($contactId, ['UID'], ['types' => true])[0]; + if (!isset($contact['X-SOCIALPROFILE'])) { + return new JSONResponse([], Http::STATUS_PRECONDITION_FAILED); + } + $socialprofiles = $contact['X-SOCIALPROFILE']; + // retrieve data + $url = $this->socialProvider->getSocialConnector($socialprofiles, $network); + + if (empty($url)) { + return new JSONResponse([], Http::STATUS_BAD_REQUEST); + } + + $httpResult = $this->clientService->NewClient()->get($url); + $socialdata = $httpResult->getBody(); + $imageType = $httpResult->getHeader('content-type'); + + if (!$socialdata || $imageType === null) { + return new JSONResponse([], Http::STATUS_NOT_FOUND); + } + + // update contact + $changes = []; + $changes['URI'] = $contact['URI']; + $changes['VERSION'] = $contact['VERSION']; + $this->addPhoto($changes, $imageType, base64_encode($socialdata)); + + if (isset($contact['PHOTO']) && $changes['PHOTO'] === $contact['PHOTO']) { + return new JSONResponse([], Http::STATUS_NOT_MODIFIED); + } + + $addressBook->createOrUpdate($changes, $addressbookId); + } catch (Exception $e) { + return new JSONResponse([], Http::STATUS_INTERNAL_SERVER_ERROR); + } + return new JSONResponse([], Http::STATUS_OK); + } +} diff --git a/lib/Settings/AdminSettings.php b/lib/Settings/AdminSettings.php new file mode 100644 index 000000000..c84609179 --- /dev/null +++ b/lib/Settings/AdminSettings.php @@ -0,0 +1,78 @@ + + * + * @author Matthias Heinisch + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Contacts\Settings; + +use OCA\Contacts\AppInfo\Application; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\IConfig; +use OCP\IInitialStateService; +use OCP\Settings\ISettings; + +class AdminSettings implements ISettings { + + /** @var IConfig */ + private $config; + + /** @var IInitialStateService */ + private $initialStateService; + + /** + * Admin constructor. + * + * @param IConfig $config + * @param IL10N $l + */ + public function __construct(IConfig $config, IInitialStateService $initialStateService) { + $this->appName = Application::APP_ID; + $this->config = $config; + $this->initialStateService = $initialStateService; + } + + /** + * @return TemplateResponse + */ + public function getForm() { + foreach (Application::AVAIL_SETTINGS as $key => $default) { + $data = $this->config->getAppValue($this->appName, $key, $default); + $this->initialStateService->provideInitialState($this->appName, $key, $data); + } + return new TemplateResponse($this->appName, 'settings/admin'); + } + + /** + * @return string the section ID, e.g. 'sharing' + */ + public function getSection() { + return 'groupware'; + } + + /** + * @return int whether the form should be rather on the top or bottom of + * the admin section. The forms are arranged in ascending order of the + * priority values. It is required to return a value between 0 and 100. + */ + public function getPriority() { + return 75; + } +} diff --git a/package-lock.json b/package-lock.json index ee8359c86..25e97a787 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5946,6 +5946,11 @@ "brace-expansion": "^1.1.7" } }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=" + }, "minipass": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/minipass/-/minipass-2.9.0.tgz", @@ -5972,6 +5977,14 @@ "optional": true, "requires": { "minimist": "^1.2.5" + }, + "dependencies": { + "minimist": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", + "optional": true + } } }, "ms": { @@ -7920,7 +7933,8 @@ "minimist": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", + "dev": true }, "minimist-options": { "version": "3.0.2", diff --git a/package.json b/package.json index 2a2e58a89..5c4043be5 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ "@nextcloud/paths": "^1.1.2", "@nextcloud/router": "^1.1.0", "@nextcloud/vue": "2.0.0", + "@nextcloud/axios": "^1.3.2", "axios": "^0.19.2", "cdav-library": "git+https://github.com/nextcloud/cdav-library.git", "core-js": "^3.6.5", diff --git a/src/adminSettings.js b/src/adminSettings.js new file mode 100644 index 000000000..d9635b2a4 --- /dev/null +++ b/src/adminSettings.js @@ -0,0 +1,34 @@ +/** + * @copyright Copyright (c) 2020 Gary Kim + * + * @author Gary Kim + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +import Vue from 'vue' +import AdminSettings from './components/AdminSettings' + +document.addEventListener('DOMContentLoaded', main) + +function main() { + Vue.prototype.t = t + + const View = Vue.extend(AdminSettings) + const view = new View() + view.$mount('#contacts-settings') +} diff --git a/src/components/AdminSettings.vue b/src/components/AdminSettings.vue new file mode 100644 index 000000000..ac840085d --- /dev/null +++ b/src/components/AdminSettings.vue @@ -0,0 +1,35 @@ + + + diff --git a/src/components/ContactDetails.vue b/src/components/ContactDetails.vue index 9553bb1c2..6d4c6fd90 100644 --- a/src/components/ContactDetails.vue +++ b/src/components/ContactDetails.vue @@ -39,7 +39,9 @@
- + diff --git a/src/components/ContactDetails/ContactDetailsAvatar.vue b/src/components/ContactDetails/ContactDetailsAvatar.vue index 7b211c8c5..3fc6f1ec9 100644 --- a/src/components/ContactDetails/ContactDetailsAvatar.vue +++ b/src/components/ContactDetails/ContactDetailsAvatar.vue @@ -3,6 +3,7 @@ - - @author Team Popcorn - @author John Molakvoæ + - @author Matthias Heinisch - - @license GNU AGPL version 3 or any later version - @@ -25,6 +26,7 @@
+
- - + + {{ t('contacts', 'Upload a new picture') }} - + {{ t('contacts', 'Choose from files') }} + + {{ t('contacts', 'Get from ' + network) }} +
@@ -93,11 +102,14 @@ import ActionButton from '@nextcloud/vue/dist/Components/ActionButton' import Modal from '@nextcloud/vue/dist/Components/Modal' import { getFilePickerBuilder } from '@nextcloud/dialogs' -import { generateRemoteUrl } from '@nextcloud/router' +import { generateUrl, generateRemoteUrl } from '@nextcloud/router' import { getCurrentUser } from '@nextcloud/auth' +import { loadState } from '@nextcloud/initial-state' import sanitizeSVG from '@mattkrick/sanitize-svg' -const axios = () => import('axios') +import axios from '@nextcloud/axios' + +const supportedNetworks = loadState('contacts', 'supportedNetworks') export default { name: 'ContactDetailsAvatar', @@ -133,6 +145,16 @@ export default { } return false }, + supportedSocial() { + // get social networks set for the current contact + const available = this.contact.vCard.getAllProperties('x-socialprofile') + .map(a => a.jCal[1].type.toString().toLowerCase()) + // get list of social networks that allow for avatar download + const supported = supportedNetworks.map(v => v.toLowerCase()) + // return supported social networks which are set + return supported.filter(i => available.includes(i)) + .map(j => this.capitalize(j)) + }, }, mounted() { // update image size on window resize @@ -215,7 +237,15 @@ export default { this.$refs.uploadInput.value = '' this.loading = false }, - + /** + * Return the word with (only) the first letter capitalized + * + * @param {string} word the word to handle + * @returns {string} the word with the first letter capitalized + */ + capitalize(word) { + return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() + }, /** * Return the mimetype based on the first magix byte * @@ -314,8 +344,7 @@ export default { if (file) { this.loading = true try { - const { get } = await axios() - const response = await get(`${this.root}${file}`, { + const response = await axios.get(`${this.root}${file}`, { responseType: 'arraybuffer', }) const type = response.headers['content-type'] @@ -330,6 +359,47 @@ export default { } }, + /** + * Downloads the Avatar from social media + * + * @param {String} network the social network to use (or 'any' for first match) + */ + async getSocialAvatar(network) { + + if (!this.loading) { + + this.loading = true + try { + const response = await axios.put(generateUrl('/apps/contacts/api/v1/social/avatar/{network}/{id}/{uid}', { + network: network.toLowerCase(), + id: this.contact.addressbook.id, + uid: this.contact.uid, + })) + if (response.status !== 200) { + throw new URIError('Download of social profile avatar failed') + } + + // Fetch newly updated contact + await this.$store.dispatch('fetchFullContact', { contact: this.contact, forceReFetch: true }) + + // Update local clone + const contact = this.$store.getters.getContact(this.contact.key) + await this.$emit('updateLocalContact', contact) + + // Notify user + OC.Notification.showTemporary(t('contacts', 'Avatar downloaded from social network')) + } catch (error) { + if (error.response.status === 304) { + OC.Notification.showTemporary(t('contacts', 'Avatar already up to date')) + } else { + OC.Notification.showTemporary(t('contacts', 'Avatar download failed')) + console.debug(error) + } + } + } + this.loading = false + }, + /** * Menu handling */ diff --git a/src/store/contacts.js b/src/store/contacts.js index f2602f36f..fed655873 100644 --- a/src/store/contacts.js +++ b/src/store/contacts.js @@ -372,11 +372,11 @@ const actions = { * @param {string} data.etag the contact etag to override in case of conflict * @returns {Promise} */ - async fetchFullContact(context, { contact, etag = '' }) { + async fetchFullContact(context, { contact, etag = '', forceReFetch = false }) { if (etag.trim() !== '') { await context.commit('updateContactEtag', { contact, etag }) } - return contact.dav.fetchCompleteData() + return contact.dav.fetchCompleteData(forceReFetch) .then((response) => { const newContact = new Contact(contact.dav.data, contact.addressbook) context.commit('updateContact', newContact) diff --git a/templates/settings/admin.php b/templates/settings/admin.php new file mode 100644 index 000000000..347b1b168 --- /dev/null +++ b/templates/settings/admin.php @@ -0,0 +1,5 @@ + + +
diff --git a/tests/unit/Controller/PageControllerTest.php b/tests/unit/Controller/PageControllerTest.php index d86f055b0..c492ecdf4 100644 --- a/tests/unit/Controller/PageControllerTest.php +++ b/tests/unit/Controller/PageControllerTest.php @@ -29,6 +29,7 @@ use OCP\IInitialStateService; use OCP\IRequest; use OCP\L10N\IFactory; +use OCA\Contacts\Service\SocialApiService; use ChristophWurst\Nextcloud\Testing\TestCase; class PageControllerTest extends TestCase { @@ -37,31 +38,34 @@ class PageControllerTest extends TestCase { /** @var IRequest|MockObject */ private $request; + /** @var IConfig|MockObject*/ + private $config; + /** @var IInitialStateService|MockObject */ private $initialStateService; /** @var IFactory|MockObject */ private $languageFactory; - /** @var IConfig|MockObject*/ - private $config; - + /** @var SocialApiService|MockObject*/ + private $socialApi; public function setUp() { parent::setUp(); $this->request = $this->createMock(IRequest::class); + $this->config = $this->createMock(IConfig::class); $this->initialStateService = $this->createMock(IInitialStateService::class); $this->languageFactory = $this->createMock(IFactory::class); - $this->config = $this->createMock(IConfig::class); + $this->socialApi = $this->createMock(SocialApiService::class); $this->controller = new PageController( 'contacts', $this->request, $this->config, $this->initialStateService, - $this->languageFactory - + $this->languageFactory, + $this->socialApi ); } diff --git a/tests/unit/Service/SocialApiServiceTest.php b/tests/unit/Service/SocialApiServiceTest.php new file mode 100644 index 000000000..076162d22 --- /dev/null +++ b/tests/unit/Service/SocialApiServiceTest.php @@ -0,0 +1,132 @@ + + * + * @author Matthias Heinisch + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + + +namespace OCA\Contacts\Service; + +use OCA\Contacts\Service\Social\CompositeSocialProvider; + +use OCP\AppFramework\Http; +use OCP\Http\Client\IClient; +use OCP\Http\Client\IResponse; +use OCP\Http\Client\IClientService; +use OCP\IConfig; +use OCP\Contacts\IManager; +use OCP\IAddressBook; + +use PHPUnit\Framework\MockObject\MockObject; +use ChristophWurst\Nextcloud\Testing\TestCase; + +class SocialApiServiceTest extends TestCase { + private $service; + + /** @var CompositeSocialProvider */ + private $socialProvider; + /** @var IManager|MockObject */ + private $manager; + /** @var IConfig|MockObject */ + private $config; + /** @var IClientService|MockObject */ + private $clientService; + + public function socialProfileProvider() { + return [ + 'no social profiles set' => [null, 'someConnector', 'someResult', Http::STATUS_PRECONDITION_FAILED], + 'valid social profile' => [[['type' => 'someNetwork', 'value' => 'someId']], 'someConnector', 'someResult', Http::STATUS_OK], + 'bad formatted profile id' => [[['type' => 'someNetwork', 'value' => 'someId']], null, 'someResult', Http::STATUS_BAD_REQUEST], + 'not existing profile id' => [[['type' => 'someNetwork', 'value' => 'someId']], 'someConnector', '', Http::STATUS_NOT_FOUND], + 'unchanged data' => [[['type' => 'someNetwork', 'value' => 'someId']], 'someConnector', 'thePhoto', Http::STATUS_NOT_MODIFIED], + ]; + } + + public function setUp() { + parent::setUp(); + + $this->manager = $this->createMock(IManager::class); + $this->config = $this->createMock(IConfig::class); + $this->socialProvider = $this->createMock(CompositeSocialProvider::class); + $this->clientService = $this->createMock(IClientService::class); + $this->service = new SocialApiService( + $this->socialProvider, + $this->manager, + $this->config, + $this->clientService + ); + } + + public function testDeactivatedSocial() { + $this->config + ->method('getAppValue') + ->willReturn('no'); + + $result = $this->service->getSupportedNetworks(); + $this->assertEmpty($result); + } + + + /** + * @dataProvider socialProfileProvider + */ + public function testUpdateContact($social, $connector, $httpResult, $expected) { + $contact = [ + 'URI' => '3225c0d5-1bd2-43e5-a08c-4e65eaa406b0', + 'VERSION' => '4.0', + 'PHOTO' => "data:" . $httpResult . ";base64," . base64_encode('thePhoto'), + 'X-SOCIALPROFILE' => $social, + ]; + $addressbook = $this->createMock(IAddressBook::class); + $addressbook + ->method('getUri') + ->willReturn('contacts'); + $addressbook + ->method('search') + ->willReturn([$contact]); + + $this->manager + ->method('getUserAddressBooks') + ->willReturn([$addressbook]); + + $this->socialProvider + ->method('getSocialConnector') + ->willReturn($connector); + + $response = $this->createMock(IResponse::class); + $response + ->method('getBody') + ->willReturn($httpResult); + $response + ->method('getHeader') + ->willReturn($httpResult); + $client = $this->createMock(IClient::class); + $client + ->method('get') + ->willReturn($response); + $this->clientService + ->method('NewClient') + ->willReturn($client); + + $result = $this->service->updateContact('contacts', '3225c0d5-1bd2-43e5-a08c-4e65eaa406b0', 'theSocialNetwork'); + + $this->assertEquals($expected, $result->getStatus()); + } +} diff --git a/webpack.common.js b/webpack.common.js index 63df5680e..8aff48847 100644 --- a/webpack.common.js +++ b/webpack.common.js @@ -3,15 +3,16 @@ const webpack = require('webpack') const { VueLoaderPlugin } = require('vue-loader') const StyleLintPlugin = require('stylelint-webpack-plugin') const packageJson = require('./package.json') -const appName = packageJson.name const appVersion = JSON.stringify(packageJson.version) module.exports = { - entry: path.join(__dirname, 'src', 'main.js'), + entry: { + adminSettings: path.join(__dirname, 'src', 'adminSettings.js'), + contacts: path.join(__dirname, 'src', 'main.js'), + }, output: { path: path.resolve(__dirname, './js'), publicPath: '/js/', - filename: `${appName}.js`, chunkFilename: 'chunks/[name]-[hash].js' }, module: {