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

GmailConnection::historyList()   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
		if (!empty($this->configObject)) {
0 ignored issues
show
Bug introduced by
The property configObject does not exist on Dacastro4\LaravelGmail\GmailConnection. Did you mean config?
Loading history...
61
			return !empty($this->configObject['access_token']);
62
		}
63
		if (Storage::disk('local')->exists($file)) {
64
			if ($allowJsonEncrypt) {
65
				$savedConfigToken = json_decode(decrypt(Storage::disk('local')->get($file)), true);
66
			} else {
67
				$savedConfigToken = json_decode(Storage::disk('local')->get($file), true);
68
			}
69
70
			return !empty($savedConfigToken['access_token']);
71
72
		}
73
74
		return false;
75
	}
76
77
	/**
78
	 * Refresh the auth token if needed
79
	 *
80
	 * @return mixed|null
81
	 */
82
	private function refreshTokenIfNeeded()
83
	{
84
		if ($this->isAccessTokenExpired()) {
85
			$this->fetchAccessTokenWithRefreshToken($this->getRefreshToken());
86
			$token = $this->getAccessToken();
87
			$this->setBothAccessToken($token);
88
89
			return $token;
90
		}
91
92
		return $this->token;
93
	}
94
95
	/**
96
	 * Check if token exists and is expired
97
	 * Throws an AuthException when the auth file its empty or with the wrong token
98
	 *
99
	 *
100
	 * @return bool Returns True if the access_token is expired.
101
	 */
102
	public function isAccessTokenExpired()
103
	{
104
		$token = $this->getToken();
105
106
		if ($token) {
107
			$this->setAccessToken($token);
108
		}
109
110
		return parent::isAccessTokenExpired();
111
	}
112
113
	public function getToken()
114
	{
115
		return parent::getAccessToken() ?: $this->config();
116
	}
117
118
	public function setToken($token)
119
	{
120
		$this->setAccessToken($token);
121
	}
122
123
	public function getAccessToken()
124
	{
125
		$token = parent::getAccessToken() ?: $this->config();
126
127
		return $token;
128
	}
129
130
	/**
131
	 * @param array|string $token
132
	 */
133
	public function setAccessToken($token)
134
	{
135
		parent::setAccessToken($token);
136
	}
137
138
	/**
139
	 * @param $token
140
	 */
141
	public function setBothAccessToken($token)
142
	{
143
		$this->setAccessToken($token);
144
		$this->saveAccessToken($token);
145
	}
146
147
	/**
148
	 * Save the credentials in a file
149
	 *
150
	 * @param array $config
151
	 */
152
	public function saveAccessToken(array $config)
153
	{
154
		$disk = Storage::disk('local');
155
		$fileName = $this->getFileName();
156
		$file = "gmail/tokens/$fileName.json";
157
		$allowJsonEncrypt = $this->_config['gmail.allow_json_encrypt'];
158
		$config['email'] = $this->emailAddress;
159
160
		if ($disk->exists($file)) {
161
162
			if (empty($config['email'])) {
163
				if ($allowJsonEncrypt) {
164
					$savedConfigToken = json_decode(decrypt($disk->get($file)), true);
165
				} else {
166
					$savedConfigToken = json_decode($disk->get($file), true);
167
				}
168
				if (isset($savedConfigToken['email'])) {
169
					$config['email'] = $savedConfigToken['email'];
170
				}
171
			}
172
173
			$disk->delete($file);
174
		}
175
176
		if ($allowJsonEncrypt) {
177
			$disk->put($file, encrypt(json_encode($config)));
178
		} else {
179
			$disk->put($file, json_encode($config));
180
		}
181
182
	}
183
184
	/**
185
	 * @return array|string
186
	 * @throws \Exception
187
	 */
188
	public function makeToken($saveFile = true)
189
	{
190
		if (!$this->check()) {
191
			$request = Request::capture();
192
			$code = (string)$request->input('code', null);
193
			if (!is_null($code) && !empty($code)) {
0 ignored issues
show
introduced by
The condition is_null($code) is always false.
Loading history...
194
				$accessToken = $this->fetchAccessTokenWithAuthCode($code);
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