Passed
Pull Request — master (#258)
by
unknown
03:34
created

GmailConnection::stopWatch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 5
rs 10
1
<?php
2
3
namespace Dacastro4\LaravelGmail;
4
5
use Dacastro4\LaravelGmail\Traits\Configurable;
6
use Dacastro4\LaravelGmail\Traits\HasLabels;
7
use Google_Client;
8
use Google_Service_Gmail;
9
use Google_Service_Gmail_WatchRequest;
10
use Illuminate\Container\Container;
11
use Illuminate\Support\Facades\Request;
12
use Illuminate\Support\Facades\Storage;
13
14
class GmailConnection extends Google_Client
15
{
16
	use HasLabels;
0 ignored issues
show
Bug introduced by
The trait Dacastro4\LaravelGmail\Traits\HasLabels requires the property $users_labels which is not provided by Dacastro4\LaravelGmail\GmailConnection.
Loading history...
17
	use Configurable {
0 ignored issues
show
Bug introduced by
The trait Dacastro4\LaravelGmail\Traits\Configurable requires the property $id which is not provided by Dacastro4\LaravelGmail\GmailConnection.
Loading history...
18
		__construct as configConstruct;
19
	}
20
21
22
	protected $emailAddress;
23
	protected $refreshToken;
24
	protected $app;
25
	protected $accessToken;
26
	protected $token;
27
	private $configuration;
28
	public $userId;
29
30
	public function __construct($config = null, $userId = null)
31
	{
32
		$this->app = Container::getInstance();
33
34
		$this->userId = $userId;
35
36
		$this->configConstruct($config);
37
38
		$this->configuration = $config;
39
40
		parent::__construct($this->getConfigs());
41
42
		$this->configApi();
43
44
		if ($this->checkPreviouslyLoggedIn()) {
45
			$this->refreshTokenIfNeeded();
46
		}
47
48
	}
49
50
	/**
51
	 * Check and return true if the user has previously logged in without checking if the token needs to refresh
52
	 *
53
	 * @return bool
54
	 */
55
	public function checkPreviouslyLoggedIn()
56
	{
57
		$fileName = $this->getFileName();
58
		$file = "gmail/tokens/$fileName.json";
59
		$allowJsonEncrypt = $this->_config['gmail.allow_json_encrypt'];
60
61
		if (Storage::disk('local')->exists($file)) {
62
			if ($allowJsonEncrypt) {
63
				$savedConfigToken = json_decode(decrypt(Storage::disk('local')->get($file)), true);
64
			} else {
65
				$savedConfigToken = json_decode(Storage::disk('local')->get($file), true);
66
			}
67
68
			return !empty($savedConfigToken['access_token']);
69
70
		}
71
72
		return false;
73
	}
74
75
	/**
76
	 * Refresh the auth token if needed
77
	 *
78
	 * @return mixed|null
79
	 */
80
	private function refreshTokenIfNeeded()
81
	{
82
		if ($this->isAccessTokenExpired()) {
83
			$this->fetchAccessTokenWithRefreshToken($this->getRefreshToken());
84
			$token = $this->getAccessToken();
85
			$this->setBothAccessToken($token);
86
87
			return $token;
88
		}
89
90
		return $this->token;
91
	}
92
93
	/**
94
	 * Check if token exists and is expired
95
	 * Throws an AuthException when the auth file its empty or with the wrong token
96
	 *
97
	 *
98
	 * @return bool Returns True if the access_token is expired.
99
	 */
100
	public function isAccessTokenExpired()
101
	{
102
		$token = $this->getToken();
103
104
		if ($token) {
105
			$this->setAccessToken($token);
106
		}
107
108
		return parent::isAccessTokenExpired();
109
	}
110
111
	public function getToken()
112
	{
113
		return parent::getAccessToken() ?: $this->config();
114
	}
115
116
	public function setToken($token)
117
	{
118
		$this->setAccessToken($token);
119
	}
120
121
	public function getAccessToken()
122
	{
123
		$token = parent::getAccessToken() ?: $this->config();
124
125
		return $token;
126
	}
127
128
	/**
129
	 * @param array|string $token
130
	 */
131
	public function setAccessToken($token)
132
	{
133
		parent::setAccessToken($token);
134
	}
135
136
	/**
137
	 * @param $token
138
	 */
139
	public function setBothAccessToken($token)
140
	{
141
		$this->setAccessToken($token);
142
		$this->saveAccessToken($token);
143
	}
144
145
	/**
146
	 * Save the credentials in a file
147
	 *
148
	 * @param array $config
149
	 */
150
	public function saveAccessToken(array $config)
151
	{
152
		$disk = Storage::disk('local');
153
		$fileName = $this->getFileName();
154
		$file = "gmail/tokens/$fileName.json";
155
		$allowJsonEncrypt = $this->_config['gmail.allow_json_encrypt'];
156
		$config['email'] = $this->emailAddress;
157
158
		if ($disk->exists($file)) {
159
160
			if (empty($config['email'])) {
161
				if ($allowJsonEncrypt) {
162
					$savedConfigToken = json_decode(decrypt($disk->get($file)), true);
163
				} else {
164
					$savedConfigToken = json_decode($disk->get($file), true);
165
				}
166
				if (isset($savedConfigToken['email'])) {
167
					$config['email'] = $savedConfigToken['email'];
168
				}
169
			}
170
171
			$disk->delete($file);
172
		}
173
174
		if ($allowJsonEncrypt) {
175
			$disk->put($file, encrypt(json_encode($config)));
176
		} else {
177
			$disk->put($file, json_encode($config));
178
		}
179
180
	}
181
182
	/**
183
	 * @return array|string
184
	 * @throws \Exception
185
	 */
186
	public function makeToken($saveFile = true)
187
	{
188
		if (!$this->check()) {
189
			$request = Request::capture();
190
			$code = (string)$request->input('code', null);
191
			if (!is_null($code) && !empty($code)) {
0 ignored issues
show
introduced by
The condition is_null($code) is always false.
Loading history...
192
				$accessToken = $this->fetchAccessTokenWithAuthCode($code);
193
				if ($this->haveReadScope()) {
194
					$me = $this->getProfile();
195
					if (property_exists($me, 'emailAddress')) {
196
						$this->emailAddress = $me->emailAddress;
197
						$accessToken['email'] = $me->emailAddress;
198
					}
199
				}
200
				if ($saveFile) {
201
					$this->setBothAccessToken($accessToken);
202
				} else {
203
					$this->setAccessToken($accessToken);
204
				}
205
206
				return $accessToken;
207
			} else {
208
				throw new \Exception('No access token');
209
			}
210
		} else {
211
			return $this->getAccessToken();
212
		}
213
	}
214
215
	/**
216
	 * Check
217
	 *
218
	 * @return bool
219
	 */
220
	public function check()
221
	{
222
		return !$this->isAccessTokenExpired();
223
	}
224
225
	/**
226
	 * Gets user profile from Gmail
227
	 *
228
	 * @return \Google_Service_Gmail_Profile
229
	 */
230
	public function getProfile()
231
	{
232
		$service = new Google_Service_Gmail($this);
233
234
		return $service->users->getProfile('me');
235
	}
236
237
	/**
238
	 * Revokes user's permission and logs them out
239
	 */
240
	public function logout()
241
	{
242
		$this->revokeToken();
243
	}
244
245
	/**
246
	 * Delete the credentials in a file
247
	 */
248
	public function deleteAccessToken()
249
	{
250
		$disk = Storage::disk('local');
251
		$fileName = $this->getFileName();
252
		$file = "gmail/tokens/$fileName.json";
253
254
		$allowJsonEncrypt = $this->_config['gmail.allow_json_encrypt'];
255
256
		if ($disk->exists($file)) {
257
			$disk->delete($file);
258
		}
259
260
		if ($allowJsonEncrypt) {
261
			$disk->put($file, encrypt(json_encode([])));
262
		} else {
263
			$disk->put($file, json_encode([]));
264
		}
265
266
	}
267
268
	private function haveReadScope()
269
	{
270
		$scopes = $this->getUserScopes();
271
272
		return in_array(Google_Service_Gmail::GMAIL_READONLY, $scopes);
273
	}
274
275
	/**
276
	 * users.stop receiving push notifications for the given user mailbox.
277
	 *
278
	 * @param string $userEmail Email address
279
	 * @param array $optParams
280
	 * @return \Google_Service_Gmail_Stop
0 ignored issues
show
Bug introduced by
The type Google_Service_Gmail_Stop was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
281
	 */
282
	public function stopWatch($userEmail, $optParams = [])
283
	{
284
		$service = new Google_Service_Gmail($this);
285
286
		return $service->users->stop($userEmail, $optParams);
287
	}
288
289
	/**
290
	 * Set up or update a push notification watch on the given user mailbox.
291
	 *
292
	 * @param string $userEmail Email address
293
	 * @param Google_Service_Gmail_WatchRequest $postData
294
	 *
295
	 * @return \Google_Service_Gmail_WatchResponse
296
	 */
297
	public function setWatch($userEmail, \Google_Service_Gmail_WatchRequest $postData): \Google_Service_Gmail_WatchResponse
298
	{
299
		$service = new Google_Service_Gmail($this);
300
301
		return $service->users->watch($userEmail, $postData);
302
	}
303
304
	/**
305
	 * Lists the history of all changes to the given mailbox. History results are returned in chronological order (increasing historyId).
306
	 * @param $userEmail
307
	 * @param $params
308
	 * @return \Google\Service\Gmail\ListHistoryResponse
309
	 */
310
	public function historyList($userEmail, $params)
311
	{
312
		$service = new Google_Service_Gmail($this);
313
314
		return $service->users_history->listUsersHistory($userEmail, $params);
315
	}
316
}
317