Passed
Push — master ( 9e97df...8652e1 )
by Robert
04:22
created

LiveEngageLaravel::messagingHistory()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4.0047

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 14
cts 15
cp 0.9333
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 15
nc 2
nop 2
crap 4.0047
1
<?php
2
3
namespace LivePersonInc\LiveEngageLaravel;
4
5
use Carbon\Carbon;
6
use GuzzleHttp\Client;
7
use GuzzleHttp\HandlerStack;
8
use GuzzleHttp\Subscriber\Oauth\Oauth1;
9
use LivePersonInc\LiveEngageLaravel\Models\Info;
10
use LivePersonInc\LiveEngageLaravel\Models\MetaData;
11
use LivePersonInc\LiveEngageLaravel\Models\MessagingInfo;
12
use LivePersonInc\LiveEngageLaravel\Models\Payload;
13
use LivePersonInc\LiveEngageLaravel\Models\Visitor;
14
use LivePersonInc\LiveEngageLaravel\Models\Agent;
15
use LivePersonInc\LiveEngageLaravel\Models\Campaign;
16
use LivePersonInc\LiveEngageLaravel\Models\Engagement;
17
use LivePersonInc\LiveEngageLaravel\Models\Conversation;
18
use LivePersonInc\LiveEngageLaravel\Collections\EngagementHistory;
19
use LivePersonInc\LiveEngageLaravel\Collections\AgentParticipants;
20
use LivePersonInc\LiveEngageLaravel\Exceptions\LiveEngageException;
21
use LivePersonInc\LiveEngageLaravel\Collections\ConversationHistory;
22
23
class LiveEngageLaravel
24
{
25
	private $account = false;
26
	private $results = [];
27
	private $skills = [];
28
	private $next = false;
29
	private $prev = false;
30
	private $start;
31
	private $end;
32
	private $config = 'services.liveperson.default';
33
	private $version = '1.0';
34
	private $history_limit = 50;
35
	private $history = false;
36
	private $context = 'interactionHistoryRecords';
37
	private $interactive = true;
38
	private $ended = true;
39
	private $bearer = false;
40
41
	private $domain = false;
42
43
	private $retry_limit = 5;
44
	private $retry_counter = 0;
45
46 1
	public function __get($attribute)
47
	{
48 1
		return $this->$attribute;
49
	}
50
51
	public function __set($attribute, $value)
52
	{
53
		return $this->$attribute = $value;
54
	}
55
56 1
	public function __construct()
57
	{
58 1
		$this->account = config("{$this->config}.account");
59
		//$this->domain = config("{$this->config}.domain");
60 1
		$this->version = config("{$this->config}.version") ?: $this->version;
61 1
	}
62
63
	public function key($key = 'default')
64
	{
65
		$this->config = "services.liveperson.$key";
66
67
		return $this;
68
	}
69
	
70
	public function nonInteractive()
71
	{
72
		$this->interactive = false;
73
		return $this;
74
	}
75
	
76
	public function active()
77
	{
78
		$this->ended = false;
79
		return $this;
80
	}
81
82
	public function limit($limit)
83
	{
84
		$this->history_limit = $limit;
85
86
		return $this;
87
	}
88
89
	public function skills($skills)
90
	{
91
		$this->skills = $skills;
92
93
		return $this;
94
	}
95
96
	public function retry($limit)
97
	{
98
		$this->retry_limit = $limit;
99
100
		return $this;
101
	}
102
103
	public function get()
104
	{
105
		return $this->results;
106
	}
107
108
	public function account($accountid)
109
	{
110
		$this->account = $accountid;
111
112
		return $this;
113
	}
114
115 1
	public function domain($service)
116
	{
117 1
		$response = $this->requestV1("https://api.liveperson.net/api/account/{$this->account}/service/{$service}/baseURI.json?version={$this->version}", 'GET');
118
		
119 1
		$this->domain = $response->baseURI;
120
121 1
		return $this;
122
	}
123
124
	public function visitor($visitorID, $sessionID, $setData = false)
125
	{
126
		$this->domain('smt');
127
128
		if ($setData) {
129
			$url = "https://{$this->domain}/api/account/{$this->account}/monitoring/visitors/{$visitorID}/visits/current/events?v=1&sid={$sessionID}";
130
131
			return $this->requestV1($url, 'POST', $setData);
132
		} else {
133
			$url = "https://{$this->domain}/api/account/{$this->account}/monitoring/visitors/{$visitorID}/visits/current/state?v=1&sid={$sessionID}";
134
135
			return $this->requestV1($url, 'GET');
136
		}
137
	}
138
139
	final public function retrieveHistory(Carbon $start, Carbon $end, $url = false)
140
	{
141
		$this->domain('engHistDomain');
142
143
		$url = $url ?: "https://{$this->domain}/interaction_history/api/account/{$this->account}/interactions/search?limit={$this->history_limit}&offset=0";
144
145
		$start_str = $start->toW3cString();
146
		$end_str = $end->toW3cString();
147
148
		$data = [
149
			'interactive' => $this->interactive,
150
			'ended' => $this->ended,
151
			'start' => [
152
				'from' => strtotime($start_str) . '000',
153
				'to' => strtotime($end_str) . '000',
154
			],
155
		];
156
		if (count($this->skills)) {
157
			$data['skillIds'] = $this->skills;
158
		}
159
160
		$data = new Payload($data);
161
162
		return $this->requestV1($url, 'POST', $data);
163
	}
164
165
	final public function retrieveMsgHistory(Carbon $start, Carbon $end, $url = false)
166
	{
167
		$this->domain('msgHist');
168
169
		$url = $url ?: "https://{$this->domain}/messaging_history/api/account/{$this->account}/conversations/search?limit={$this->history_limit}&offset=0&sort=start:desc";
170
171
		$start_str = $start->toW3cString();
172
		$end_str = $end->toW3cString();
173
174
		$data = [
175
			'status' => $this->ended ? ['CLOSE'] : ['OPEN', 'CLOSE'],
176
			'start' => [
177
				'from' => strtotime($start_str) . '000',
178
				'to' => strtotime($end_str) . '000',
179
			],
180
		];
181
		if (count($this->skills)) {
182
			$data['skillIds'] = $this->skills;
183
		}
184
185
		$data = new Payload($data);
186
187
		return $this->requestV1($url, 'POST', $data);
188
	}
189
	
190 1
	public function getAgentStatus($skills)
191
	{
192 1
		$skills = is_array($skills) ? $skills : [$skills];
193
	
194 1
		$this->domain('msgHist');
195
		
196 1
		$url = "https://{$this->domain}/messaging_history/api/account/{$this->account}/agent-view/status";
197
		
198 1
		$data = ['skillIds' => $skills];
199
		
200 1
		$response = $this->requestV1($url, 'POST', $data);
201 1
		$collection = new AgentParticipants($response->agentStatusRecords);
202 1
		$collection->metaData = new MetaData((array) $response->_metadata);
203
		
204 1
		return $collection;
205
		
206
	}
207
208 1
	public function messagingHistory(Carbon $start = null, Carbon $end = null)
209
	{
210 1
		$this->retry_counter = 0;
211
212 1
		$start = $start ?: (new Carbon())->today();
213 1
		$end = $end ?: (new Carbon())->today()->addHours(23)->addMinutes(59);
214
215 1
		$this->start = $start;
216 1
		$this->end = $end;
217
218 1
		$results_object = $this->retrieveMsgHistory($start, $end);
219
		
220 1
		if ($results_object) {
221
		
222 1
			$results_object->_metadata->start = $this->start;
223 1
			$results_object->_metadata->end = $this->end;
224
		
225 1
			$meta = new MetaData((array) $results_object->_metadata);
226
			
227 1
			$collection = new ConversationHistory($results_object->conversationHistoryRecords);
228 1
			$collection->metaData = $meta;
229
			
230 1
			return $collection;
231
			
232
		} else {
233
			return false;
234
		}
235
	}
236
237 1
	public function history(Carbon $start = null, Carbon $end = null)
238
	{
239 1
		$this->retry_counter = 0;
240
241 1
		$start = $start ?: (new Carbon())->today();
242 1
		$end = $end ?: (new Carbon())->today()->addHours(23)->addMinutes(59);
243
244 1
		$this->start = $start;
245 1
		$this->end = $end;
246
247 1
		$results_object = $this->retrieveHistory($start, $end);
248
		
249 1
		if ($results_object) {
250
		
251 1
			$results_object->_metadata->start = $this->start;
252 1
			$results_object->_metadata->end = $this->end;
253
		
254 1
			$meta = new MetaData((array) $results_object->_metadata);
255
			
256 1
			$collection = new EngagementHistory($results_object->interactionHistoryRecords);
257 1
			$collection->metaData = $meta;
258
			
259 1
			return $collection;
260
			
261
		} else {
262
			return false;
263
		}
264
	}
265
	
266
	public function login()
267
	{
268
		$this->domain('agentVep');
269
		
270
		$consumer_key = config("{$this->config}.key");
271
		$consumer_secret = config("{$this->config}.secret");
272
		$token = config("{$this->config}.token");
273
		$secret = config("{$this->config}.token_secret");
274
		$username = config("{$this->config}.user_name");
275
		
276
		$auth = [
277
			'username'		  => $username,
278
			'appKey'			=> $consumer_key,
279
			'secret'			=> $consumer_secret,
280
			'accessToken'		=> $token,
281
			'accessTokenSecret' => $secret,
282
		];
283
		
284
		$url = "https://{$this->domain}/api/account/{$this->account}/login?v=1.3";
285
		
286
		$response = $this->requestV1($url, 'POST', $auth);
287
		
288
		$this->bearer = $response->bearer;
289
		
290
		return $this;
291
	}
292
	
293
	private function requestV2($url, $method, $payload = false)
0 ignored issues
show
Unused Code introduced by
The method requestV2() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
294
	{
295
		if (!$this->bearer) {
296
			$this->login();
297
		}
298
		
299
		$client = new Client();
300
		$args = [
301
			'headers' => [
302
				'Authorization' => $this->bearer
303
			]
304
		];
305
		
306
		if ($payload !== false) {
307
			$args['body'] = json_encode($payload);
308
		}
309
		
310
		try {
311
			$res = $client->request($method, $url, $args);
312
		} catch (\Exception $e) {
313
			throw $e;
314
		} 
315
		
316
		return json_decode($res->getBody());
317
	}
318
	
319 1
	private function requestClient()
320
	{
321 1
		$consumer_key = config("{$this->config}.key");
322 1
		$consumer_secret = config("{$this->config}.secret");
323 1
		$token = config("{$this->config}.token");
324 1
		$secret = config("{$this->config}.token_secret");
325
326 1
		$stack = HandlerStack::create();
327 1
		$auth = new Oauth1([
328 1
			'consumer_key'	=> $consumer_key,
329 1
			'consumer_secret' => $consumer_secret,
330 1
			'token'		   => $token,
331 1
			'token_secret'	=> $secret,
332 1
			'signature_method'=> Oauth1::SIGNATURE_METHOD_HMAC,
333
		]);
334 1
		$stack->push($auth);
335
336 1
		$client = new Client([
337 1
			'handler' => $stack,
338
		]);
339
		
340 1
		return $client;
341
	}
342
	
343 1
	private function requestV1($url, $method, $payload = [])
344
	{
345 1
		$client = $this->requestClient();
346
347
		$args = [
348 1
			'auth' => 'oauth',
349
			'headers' => [
350
				'content-type' => 'application/json',
351
			],
352 1
			'body' => json_encode($payload)
353
		];
354
355
		try {
356 1
			$res = $client->request($method, $url, $args);
357 1
			$response = json_decode($res->getBody());
358
		} catch (\Exception $e) {
359
			if ($this->retry_counter < $this->retry_limit || $this->retry_limit == -1) {
360
				usleep(1500);
361
				$this->retry_counter++;
362
				$response = $this->requestV1($url, $payload);
363
			} else {
364
				throw new LiveEngageException("Retry limit has been exceeded ($this->retry_limit)", 100);
365
			}
366
		}
367
368 1
		return $response;
369
	}
370
}
371