Completed
Push — master ( c39f56...503fda )
by Maxence
20:47
created
lib/private/OCM/OCMDiscoveryService.php 2 patches
Indentation   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -33,185 +33,185 @@
 block discarded – undo
33 33
  * @since 28.0.0
34 34
  */
35 35
 class OCMDiscoveryService implements IOCMDiscoveryService {
36
-	private ICache $cache;
37
-	public const API_VERSION = '1.1.0';
38
-
39
-	private ?ICapabilityAwareOCMProvider $localProvider = null;
40
-	/** @var array<string, ICapabilityAwareOCMProvider> */
41
-	private array $remoteProviders = [];
42
-
43
-	public function __construct(
44
-		ICacheFactory $cacheFactory,
45
-		private IClientService $clientService,
46
-		private IEventDispatcher $eventDispatcher,
47
-		protected IConfig $config,
48
-		private IAppConfig $appConfig,
49
-		private IURLGenerator $urlGenerator,
50
-		private OCMSignatoryManager $ocmSignatoryManager,
51
-		private LoggerInterface $logger,
52
-	) {
53
-		$this->cache = $cacheFactory->createDistributed('ocm-discovery');
54
-	}
55
-
56
-	/**
57
-	 * @param string $remote
58
-	 * @param bool $skipCache
59
-	 *
60
-	 * @return ICapabilityAwareOCMProvider
61
-	 * @throws OCMProviderException
62
-	 */
63
-	public function discover(string $remote, bool $skipCache = false): ICapabilityAwareOCMProvider {
64
-		$remote = rtrim($remote, '/');
65
-		if (!str_starts_with($remote, 'http://') && !str_starts_with($remote, 'https://')) {
66
-			// if scheme not specified, we test both;
67
-			try {
68
-				return $this->discover('https://' . $remote, $skipCache);
69
-			} catch (OCMProviderException|ConnectException) {
70
-				return $this->discover('http://' . $remote, $skipCache);
71
-			}
72
-		}
73
-
74
-		if (array_key_exists($remote, $this->remoteProviders)) {
75
-			return $this->remoteProviders[$remote];
76
-		}
77
-
78
-		$provider = new OCMProvider();
79
-
80
-		if (!$skipCache) {
81
-			try {
82
-				$cached = $this->cache->get($remote);
83
-				if ($cached === false) {
84
-					throw new OCMProviderException('Previous discovery failed.');
85
-				}
86
-
87
-				if ($cached !== null) {
88
-					$provider->import(json_decode($cached, true, 8, JSON_THROW_ON_ERROR) ?? []);
89
-					$this->remoteProviders[$remote] = $provider;
90
-					return $provider;
91
-				}
92
-			} catch (JsonException|OCMProviderException $e) {
93
-				$this->logger->warning('cache issue on ocm discovery', ['exception' => $e]);
94
-			}
95
-		}
96
-
97
-		$client = $this->clientService->newClient();
98
-		try {
99
-			$options = [
100
-				'timeout' => 10,
101
-				'connect_timeout' => 10,
102
-			];
103
-			if ($this->config->getSystemValueBool('sharing.federation.allowSelfSignedCertificates') === true) {
104
-				$options['verify'] = false;
105
-			}
106
-			$urls = [
107
-				$remote . '/.well-known/ocm',
108
-				$remote . '/ocm-provider',
109
-			];
110
-
111
-
112
-			foreach ($urls as $url) {
113
-				$exception = null;
114
-				$body = null;
115
-				$status = null;
116
-				try {
117
-					$response = $client->get($url, $options);
118
-					if ($response->getStatusCode() === Http::STATUS_OK) {
119
-						$body = $response->getBody();
120
-						$status = $response->getStatusCode();
121
-						// update provider with data returned by the request
122
-						$provider->import(json_decode($body, true, 8, JSON_THROW_ON_ERROR) ?? []);
123
-						$this->cache->set($remote, $body, 60 * 60 * 24);
124
-						$this->remoteProviders[$remote] = $provider;
125
-						return $provider;
126
-					}
127
-				} catch (\Exception $e) {
128
-					$this->logger->debug("Tried unsuccesfully to do discovery at: {$url}", [
129
-						'exception' => $e,
130
-						'remote' => $remote
131
-					]);
132
-					// We want to throw only the last exception
133
-					$exception = $e;
134
-					continue;
135
-				}
136
-			}
137
-			if ($exception) {
138
-				throw $exception;
139
-			}
140
-
141
-
142
-			throw new OCMProviderException('invalid remote ocm endpoint');
143
-		} catch (JsonException|OCMProviderException) {
144
-			$this->cache->set($remote, false, 5 * 60);
145
-			throw new OCMProviderException('data returned by remote seems invalid - status: ' . ($status ?? '') . ' - body: ' . ($body ?? ''));
146
-		} catch (\Exception $e) {
147
-			$this->cache->set($remote, false, 5 * 60);
148
-			$this->logger->warning('error while discovering ocm provider', [
149
-				'exception' => $e,
150
-				'remote' => $remote
151
-			]);
152
-			throw new OCMProviderException('error while requesting remote ocm provider');
153
-		}
154
-	}
155
-
156
-	/**
157
-	 * @return ICapabilityAwareOCMProvider
158
-	 */
159
-	public function getLocalOCMProvider(bool $fullDetails = true): ICapabilityAwareOCMProvider {
160
-		if ($this->localProvider !== null) {
161
-			return $this->localProvider;
162
-		}
163
-
164
-		$provider = new OCMProvider('Nextcloud ' . $this->config->getSystemValue('version'));
165
-		if (!$this->appConfig->getValueBool('core', ConfigLexicon::OCM_DISCOVERY_ENABLED)) {
166
-			return $provider;
167
-		}
168
-
169
-		$url = $this->urlGenerator->linkToRouteAbsolute('cloud_federation_api.requesthandlercontroller.addShare');
170
-		$pos = strrpos($url, '/');
171
-		if ($pos === false) {
172
-			$this->logger->debug('generated route should contain a slash character');
173
-			return $provider;
174
-		}
175
-
176
-		$provider->setEnabled(true);
177
-		$provider->setApiVersion(self::API_VERSION);
178
-		$provider->setEndPoint(substr($url, 0, $pos));
179
-		$provider->setCapabilities(['/invite-accepted', '/notifications', '/shares']);
180
-
181
-		// The inviteAcceptDialog is available from the contacts app, if this config value is set
182
-		$inviteAcceptDialog = $this->appConfig->getValueString('core', ConfigLexicon::OCM_INVITE_ACCEPT_DIALOG);
183
-		if ($inviteAcceptDialog !== '') {
184
-			$provider->setInviteAcceptDialog($this->urlGenerator->linkToRouteAbsolute($inviteAcceptDialog));
185
-		}
186
-
187
-		$resource = $provider->createNewResourceType();
188
-		$resource->setName('file')
189
-			->setShareTypes(['user', 'group'])
190
-			->setProtocols(['webdav' => '/public.php/webdav/']);
191
-		$provider->addResourceType($resource);
192
-
193
-		if ($fullDetails) {
194
-			// Adding a public key to the ocm discovery
195
-			try {
196
-				if (!$this->appConfig->getValueBool('core', OCMSignatoryManager::APPCONFIG_SIGN_DISABLED, lazy: true)) {
197
-					/**
198
-					 * @experimental 31.0.0
199
-					 * @psalm-suppress UndefinedInterfaceMethod
200
-					 */
201
-					$provider->setSignatory($this->ocmSignatoryManager->getLocalSignatory());
202
-				} else {
203
-					$this->logger->debug('ocm public key feature disabled');
204
-				}
205
-			} catch (SignatoryException|IdentityNotFoundException $e) {
206
-				$this->logger->warning('cannot generate local signatory', ['exception' => $e]);
207
-			}
208
-		}
209
-
210
-		$event = new ResourceTypeRegisterEvent($provider);
211
-		$this->eventDispatcher->dispatchTyped($event);
212
-
213
-		$this->localProvider = $provider;
214
-		return $provider;
215
-	}
36
+    private ICache $cache;
37
+    public const API_VERSION = '1.1.0';
38
+
39
+    private ?ICapabilityAwareOCMProvider $localProvider = null;
40
+    /** @var array<string, ICapabilityAwareOCMProvider> */
41
+    private array $remoteProviders = [];
42
+
43
+    public function __construct(
44
+        ICacheFactory $cacheFactory,
45
+        private IClientService $clientService,
46
+        private IEventDispatcher $eventDispatcher,
47
+        protected IConfig $config,
48
+        private IAppConfig $appConfig,
49
+        private IURLGenerator $urlGenerator,
50
+        private OCMSignatoryManager $ocmSignatoryManager,
51
+        private LoggerInterface $logger,
52
+    ) {
53
+        $this->cache = $cacheFactory->createDistributed('ocm-discovery');
54
+    }
55
+
56
+    /**
57
+     * @param string $remote
58
+     * @param bool $skipCache
59
+     *
60
+     * @return ICapabilityAwareOCMProvider
61
+     * @throws OCMProviderException
62
+     */
63
+    public function discover(string $remote, bool $skipCache = false): ICapabilityAwareOCMProvider {
64
+        $remote = rtrim($remote, '/');
65
+        if (!str_starts_with($remote, 'http://') && !str_starts_with($remote, 'https://')) {
66
+            // if scheme not specified, we test both;
67
+            try {
68
+                return $this->discover('https://' . $remote, $skipCache);
69
+            } catch (OCMProviderException|ConnectException) {
70
+                return $this->discover('http://' . $remote, $skipCache);
71
+            }
72
+        }
73
+
74
+        if (array_key_exists($remote, $this->remoteProviders)) {
75
+            return $this->remoteProviders[$remote];
76
+        }
77
+
78
+        $provider = new OCMProvider();
79
+
80
+        if (!$skipCache) {
81
+            try {
82
+                $cached = $this->cache->get($remote);
83
+                if ($cached === false) {
84
+                    throw new OCMProviderException('Previous discovery failed.');
85
+                }
86
+
87
+                if ($cached !== null) {
88
+                    $provider->import(json_decode($cached, true, 8, JSON_THROW_ON_ERROR) ?? []);
89
+                    $this->remoteProviders[$remote] = $provider;
90
+                    return $provider;
91
+                }
92
+            } catch (JsonException|OCMProviderException $e) {
93
+                $this->logger->warning('cache issue on ocm discovery', ['exception' => $e]);
94
+            }
95
+        }
96
+
97
+        $client = $this->clientService->newClient();
98
+        try {
99
+            $options = [
100
+                'timeout' => 10,
101
+                'connect_timeout' => 10,
102
+            ];
103
+            if ($this->config->getSystemValueBool('sharing.federation.allowSelfSignedCertificates') === true) {
104
+                $options['verify'] = false;
105
+            }
106
+            $urls = [
107
+                $remote . '/.well-known/ocm',
108
+                $remote . '/ocm-provider',
109
+            ];
110
+
111
+
112
+            foreach ($urls as $url) {
113
+                $exception = null;
114
+                $body = null;
115
+                $status = null;
116
+                try {
117
+                    $response = $client->get($url, $options);
118
+                    if ($response->getStatusCode() === Http::STATUS_OK) {
119
+                        $body = $response->getBody();
120
+                        $status = $response->getStatusCode();
121
+                        // update provider with data returned by the request
122
+                        $provider->import(json_decode($body, true, 8, JSON_THROW_ON_ERROR) ?? []);
123
+                        $this->cache->set($remote, $body, 60 * 60 * 24);
124
+                        $this->remoteProviders[$remote] = $provider;
125
+                        return $provider;
126
+                    }
127
+                } catch (\Exception $e) {
128
+                    $this->logger->debug("Tried unsuccesfully to do discovery at: {$url}", [
129
+                        'exception' => $e,
130
+                        'remote' => $remote
131
+                    ]);
132
+                    // We want to throw only the last exception
133
+                    $exception = $e;
134
+                    continue;
135
+                }
136
+            }
137
+            if ($exception) {
138
+                throw $exception;
139
+            }
140
+
141
+
142
+            throw new OCMProviderException('invalid remote ocm endpoint');
143
+        } catch (JsonException|OCMProviderException) {
144
+            $this->cache->set($remote, false, 5 * 60);
145
+            throw new OCMProviderException('data returned by remote seems invalid - status: ' . ($status ?? '') . ' - body: ' . ($body ?? ''));
146
+        } catch (\Exception $e) {
147
+            $this->cache->set($remote, false, 5 * 60);
148
+            $this->logger->warning('error while discovering ocm provider', [
149
+                'exception' => $e,
150
+                'remote' => $remote
151
+            ]);
152
+            throw new OCMProviderException('error while requesting remote ocm provider');
153
+        }
154
+    }
155
+
156
+    /**
157
+     * @return ICapabilityAwareOCMProvider
158
+     */
159
+    public function getLocalOCMProvider(bool $fullDetails = true): ICapabilityAwareOCMProvider {
160
+        if ($this->localProvider !== null) {
161
+            return $this->localProvider;
162
+        }
163
+
164
+        $provider = new OCMProvider('Nextcloud ' . $this->config->getSystemValue('version'));
165
+        if (!$this->appConfig->getValueBool('core', ConfigLexicon::OCM_DISCOVERY_ENABLED)) {
166
+            return $provider;
167
+        }
168
+
169
+        $url = $this->urlGenerator->linkToRouteAbsolute('cloud_federation_api.requesthandlercontroller.addShare');
170
+        $pos = strrpos($url, '/');
171
+        if ($pos === false) {
172
+            $this->logger->debug('generated route should contain a slash character');
173
+            return $provider;
174
+        }
175
+
176
+        $provider->setEnabled(true);
177
+        $provider->setApiVersion(self::API_VERSION);
178
+        $provider->setEndPoint(substr($url, 0, $pos));
179
+        $provider->setCapabilities(['/invite-accepted', '/notifications', '/shares']);
180
+
181
+        // The inviteAcceptDialog is available from the contacts app, if this config value is set
182
+        $inviteAcceptDialog = $this->appConfig->getValueString('core', ConfigLexicon::OCM_INVITE_ACCEPT_DIALOG);
183
+        if ($inviteAcceptDialog !== '') {
184
+            $provider->setInviteAcceptDialog($this->urlGenerator->linkToRouteAbsolute($inviteAcceptDialog));
185
+        }
186
+
187
+        $resource = $provider->createNewResourceType();
188
+        $resource->setName('file')
189
+            ->setShareTypes(['user', 'group'])
190
+            ->setProtocols(['webdav' => '/public.php/webdav/']);
191
+        $provider->addResourceType($resource);
192
+
193
+        if ($fullDetails) {
194
+            // Adding a public key to the ocm discovery
195
+            try {
196
+                if (!$this->appConfig->getValueBool('core', OCMSignatoryManager::APPCONFIG_SIGN_DISABLED, lazy: true)) {
197
+                    /**
198
+                     * @experimental 31.0.0
199
+                     * @psalm-suppress UndefinedInterfaceMethod
200
+                     */
201
+                    $provider->setSignatory($this->ocmSignatoryManager->getLocalSignatory());
202
+                } else {
203
+                    $this->logger->debug('ocm public key feature disabled');
204
+                }
205
+            } catch (SignatoryException|IdentityNotFoundException $e) {
206
+                $this->logger->warning('cannot generate local signatory', ['exception' => $e]);
207
+            }
208
+        }
209
+
210
+        $event = new ResourceTypeRegisterEvent($provider);
211
+        $this->eventDispatcher->dispatchTyped($event);
212
+
213
+        $this->localProvider = $provider;
214
+        return $provider;
215
+    }
216 216
 
217 217
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -65,9 +65,9 @@  discard block
 block discarded – undo
65 65
 		if (!str_starts_with($remote, 'http://') && !str_starts_with($remote, 'https://')) {
66 66
 			// if scheme not specified, we test both;
67 67
 			try {
68
-				return $this->discover('https://' . $remote, $skipCache);
69
-			} catch (OCMProviderException|ConnectException) {
70
-				return $this->discover('http://' . $remote, $skipCache);
68
+				return $this->discover('https://'.$remote, $skipCache);
69
+			} catch (OCMProviderException | ConnectException) {
70
+				return $this->discover('http://'.$remote, $skipCache);
71 71
 			}
72 72
 		}
73 73
 
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 					$this->remoteProviders[$remote] = $provider;
90 90
 					return $provider;
91 91
 				}
92
-			} catch (JsonException|OCMProviderException $e) {
92
+			} catch (JsonException | OCMProviderException $e) {
93 93
 				$this->logger->warning('cache issue on ocm discovery', ['exception' => $e]);
94 94
 			}
95 95
 		}
@@ -104,8 +104,8 @@  discard block
 block discarded – undo
104 104
 				$options['verify'] = false;
105 105
 			}
106 106
 			$urls = [
107
-				$remote . '/.well-known/ocm',
108
-				$remote . '/ocm-provider',
107
+				$remote.'/.well-known/ocm',
108
+				$remote.'/ocm-provider',
109 109
 			];
110 110
 
111 111
 
@@ -140,9 +140,9 @@  discard block
 block discarded – undo
140 140
 
141 141
 
142 142
 			throw new OCMProviderException('invalid remote ocm endpoint');
143
-		} catch (JsonException|OCMProviderException) {
143
+		} catch (JsonException | OCMProviderException) {
144 144
 			$this->cache->set($remote, false, 5 * 60);
145
-			throw new OCMProviderException('data returned by remote seems invalid - status: ' . ($status ?? '') . ' - body: ' . ($body ?? ''));
145
+			throw new OCMProviderException('data returned by remote seems invalid - status: '.($status ?? '').' - body: '.($body ?? ''));
146 146
 		} catch (\Exception $e) {
147 147
 			$this->cache->set($remote, false, 5 * 60);
148 148
 			$this->logger->warning('error while discovering ocm provider', [
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 			return $this->localProvider;
162 162
 		}
163 163
 
164
-		$provider = new OCMProvider('Nextcloud ' . $this->config->getSystemValue('version'));
164
+		$provider = new OCMProvider('Nextcloud '.$this->config->getSystemValue('version'));
165 165
 		if (!$this->appConfig->getValueBool('core', ConfigLexicon::OCM_DISCOVERY_ENABLED)) {
166 166
 			return $provider;
167 167
 		}
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 				} else {
203 203
 					$this->logger->debug('ocm public key feature disabled');
204 204
 				}
205
-			} catch (SignatoryException|IdentityNotFoundException $e) {
205
+			} catch (SignatoryException | IdentityNotFoundException $e) {
206 206
 				$this->logger->warning('cannot generate local signatory', ['exception' => $e]);
207 207
 			}
208 208
 		}
Please login to merge, or discard this patch.