Passed
Pull Request — master (#255)
by
unknown
13:15
created

GmailConnection::check()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
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, array $configObject = [])
31
	{
32
		$this->app = Container::getInstance();
33
		$this->userId = $userId;
34
		if (!empty($configObject)) {
35
			$this->configObject = $configObject;
36
		}
37
		$this->configConstruct($config);
38
39
		$this->configuration = $config;
40
		parent::__construct($this->getConfigs());
41
42
		$this->configApi();
43
44
		if ($this->checkPreviouslyLoggedIn()) {
45
			$this->refreshTokenIfNeeded();
46
		}
47
	}
48
49
	/**
50
	 * Check and return true if the user has previously logged in without checking if the token needs to refresh
51
	 *
52
	 * @return bool
53
	 */
54
	public function checkPreviouslyLoggedIn()
55
	{
56
		$fileName = $this->getFileName();
57
		$file = "gmail/tokens/$fileName.json";
0 ignored issues
show
Unused Code introduced by
The assignment to $file is dead and can be removed.
Loading history...
58
		$allowJsonEncrypt = $this->_config['gmail.allow_json_encrypt'];
0 ignored issues
show
Unused Code introduced by
The assignment to $allowJsonEncrypt is dead and can be removed.
Loading history...
59
		if (!empty($this->configObject)) {
60
			return !empty($this->configObject['access_token']);
61
		}
62
		// if (Storage::disk('local')->exists($file)) {
63
		// 	if ($allowJsonEncrypt) {
64
		// 		$savedConfigToken = json_decode(decrypt(Storage::disk('local')->get($file)), true);
65
		// 	} else {
66
		// 		$savedConfigToken = json_decode(Storage::disk('local')->get($file), true);
67
		// 	}
68
69
		// 	return !empty($savedConfigToken['access_token']);
70
71
		// }
72
73
		return false;
74
	}
75
76
	/**
77
	 * Refresh the auth token if needed
78
	 *
79
	 * @return mixed|null
80
	 */
81
	private function refreshTokenIfNeeded()
82
	{
83
		if ($this->isAccessTokenExpired()) {
84
			$this->fetchAccessTokenWithRefreshToken($this->getRefreshToken());
85
			$token = $this->getAccessToken();
86
			$this->setBothAccessToken($token);
87
88
			return $token;
89
		}
90
91
		return $this->token;
92
	}
93
94
	/**
95
	 * Check if token exists and is expired
96
	 * Throws an AuthException when the auth file its empty or with the wrong token
97
	 *
98
	 *
99
	 * @return bool Returns True if the access_token is expired.
100
	 */
101
	public function isAccessTokenExpired()
102
	{
103
		$token = $this->getToken();
104
105
		if ($token) {
106
			$this->setAccessToken($token);
107
		}
108
109
		return parent::isAccessTokenExpired();
110
	}
111
112
	public function getToken()
113
	{
114
		return parent::getAccessToken() ?: $this->config();
115
	}
116
117
	public function setToken($token)
118
	{
119
		$this->setAccessToken($token);
120
	}
121
122
	public function getAccessToken()
123
	{
124
		$token = parent::getAccessToken() ?: $this->config();
125
126
		return $token;
127
	}
128
129
	/**
130
	 * @param array|string $token
131
	 */
132
	public function setAccessToken($token)
133
	{
134
		parent::setAccessToken($token);
135
	}
136
137
	/**
138
	 * @param $token
139
	 */
140
	public function setBothAccessToken($token)
141
	{
142
		$this->setAccessToken($token);
143
		$this->saveAccessToken($token);
144
	}
145
146
	/**
147
	 * Save the credentials in a file
148
	 *
149
	 * @param array $config
150
	 */
151
	public function saveAccessToken(array $config)
152
	{
153
		$disk = Storage::disk('local');
154
		$fileName = $this->getFileName();
155
		$file = "gmail/tokens/$fileName.json";
156
		$allowJsonEncrypt = $this->_config['gmail.allow_json_encrypt'];
157
		$config['email'] = $this->emailAddress;
158
159
		if ($disk->exists($file)) {
160
161
			if (empty($config['email'])) {
162
				if ($allowJsonEncrypt) {
163
					$savedConfigToken = json_decode(decrypt($disk->get($file)), true);
164
				} else {
165
					$savedConfigToken = json_decode($disk->get($file), true);
166
				}
167
				if (isset($savedConfigToken['email'])) {
168
					$config['email'] = $savedConfigToken['email'];
169
				}
170
			}
171
172
			$disk->delete($file);
173
		}
174
175
		if ($allowJsonEncrypt) {
176
			$disk->put($file, encrypt(json_encode($config)));
177
		} else {
178
			$disk->put($file, json_encode($config));
179
		}
180
181
	}
182
183
	/**
184
	 * @return array|string
185
	 * @throws \Exception
186
	 */
187
	public function makeToken($saveFile = true)
188
	{
189
		if (!$this->check()) {
190
			$request = Request::capture();
191
			$code = (string)$request->input('code', null);
192
			if (!is_null($code) && !empty($code)) {
0 ignored issues
show
introduced by
The condition is_null($code) is always false.
Loading history...
193
				$accessToken = $this->fetchAccessTokenWithAuthCode($code);
194
                $this->configObject = $accessToken;
195
				if ($this->haveReadScope()) {
196
					$me = $this->getProfile();
197
					if (property_exists($me, 'emailAddress')) {
198
						$this->emailAddress = $me->emailAddress;
199
						$accessToken['email'] = $me->emailAddress;
200
					}
201
				}
202
				if ($saveFile) {
203
					$this->setBothAccessToken($accessToken);
204
				} else {
205
					$this->setAccessToken($accessToken);
206
				}
207
208
				return $accessToken;
209
			} else {
210
				throw new \Exception('No access token');
211
			}
212
		} else {
213
			return $this->getAccessToken();
214
		}
215
	}
216
217
	/**
218
	 * Check
219
	 *
220
	 * @return bool
221
	 */
222
	public function check()
223
	{
224
		return !$this->isAccessTokenExpired();
225
	}
226
227
	/**
228
	 * Gets user profile from Gmail
229
	 *
230
	 * @return \Google_Service_Gmail_Profile
231
	 */
232
	public function getProfile()
233
	{
234
		$service = new Google_Service_Gmail($this);
235
236
		return $service->users->getProfile('me');
237
	}
238
239
	/**
240
	 * Revokes user's permission and logs them out
241
	 */
242
	public function logout()
243
	{
244
		$this->revokeToken();
245
	}
246
247
	/**
248
	 * Delete the credentials in a file
249
	 */
250
	public function deleteAccessToken()
251
	{
252
		$disk = Storage::disk('local');
253
		$fileName = $this->getFileName();
254
		$file = "gmail/tokens/$fileName.json";
255
256
		$allowJsonEncrypt = $this->_config['gmail.allow_json_encrypt'];
257
258
		if ($disk->exists($file)) {
259
			$disk->delete($file);
260
		}
261
262
		if ($allowJsonEncrypt) {
263
			$disk->put($file, encrypt(json_encode([])));
264
		} else {
265
			$disk->put($file, json_encode([]));
266
		}
267
268
	}
269
270
	private function haveReadScope()
271
	{
272
		$scopes = $this->getUserScopes();
273
274
		return in_array(Google_Service_Gmail::GMAIL_READONLY, $scopes);
275
	}
276
277
	/**
278
	 * users.stop receiving push notifications for the given user mailbox.
279
	 *
280
	 * @param string $userEmail Email address
281
	 * @param array $optParams
282
	 * @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...
283
	 */
284
	public function stopWatch($userEmail, $optParams = [])
285
	{
286
		$service = new Google_Service_Gmail($this);
287
288
		return $service->users->stop($userEmail, $optParams);
289
	}
290
291
	/**
292
	 * Set up or update a push notification watch on the given user mailbox.
293
	 *
294
	 * @param string $userEmail Email address
295
	 * @param Google_Service_Gmail_WatchRequest $postData
296
	 *
297
	 * @return \Google_Service_Gmail_WatchResponse
298
	 */
299
	public function setWatch($userEmail, \Google_Service_Gmail_WatchRequest $postData): \Google_Service_Gmail_WatchResponse
300
	{
301
		$service = new Google_Service_Gmail($this);
302
303
		return $service->users->watch($userEmail, $postData);
304
	}
305
306
	/**
307
	 * Lists the history of all changes to the given mailbox. History results are returned in chronological order (increasing historyId).
308
	 * @param $userEmail
309
	 * @param $params
310
	 * @return \Google\Service\Gmail\ListHistoryResponse
311
	 */
312
	public function historyList($userEmail, $params)
313
	{
314
		$service = new Google_Service_Gmail($this);
315
316
		return $service->users_history->listUsersHistory($userEmail, $params);
317
	}
318
}
319