Completed
Push — master ( 8024bc...f8f0d2 )
by Vitor
14s
created

HuaweiE3531::send()   A

Complexity

Conditions 4
Paths 10

Size

Total Lines 31
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 31
ccs 0
cts 23
cp 0
rs 9.568
c 0
b 0
f 0
cc 4
nc 10
nop 2
crap 20
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * SPDX-FileCopyrightText: 2024 Martin Keßler <[email protected]>
7
 * SPDX-License-Identifier: AGPL-3.0-or-later
8
 */
9
10
namespace OCA\TwoFactorGateway\Provider\Channel\SMS\Provider\Drivers;
11
12
use Exception;
13
use OCA\TwoFactorGateway\Exception\MessageTransmissionException;
14
use OCA\TwoFactorGateway\Provider\Channel\SMS\Provider\AProvider;
15
use OCA\TwoFactorGateway\Provider\FieldDefinition;
16
use OCA\TwoFactorGateway\Provider\Settings;
17
use OCP\Http\Client\IClient;
18
use OCP\Http\Client\IClientService;
19
20
/**
21
 * @method string getApi()
22
 * @method static setApi(string $api)
23
 */
24
class HuaweiE3531 extends AProvider {
25
	private IClient $client;
26
27 1
	public function __construct(
28
		IClientService $clientService,
29
	) {
30 1
		$this->client = $clientService->newClient();
31
	}
32
33 1
	public function createSettings(): Settings {
34 1
		return new Settings(
35 1
			id: 'huawei_e3531',
36 1
			name: 'Huawei E3531',
37 1
			fields: [
38 1
				new FieldDefinition(
39 1
					field: 'api',
40 1
					prompt: 'Please enter the base URL of the Huawei E3531 stick: ',
41 1
					default: 'http://192.168.8.1/api',
42 1
				),
43 1
			]
44 1
		);
45
	}
46
47
	#[\Override]
48
	public function send(string $identifier, string $message) {
49
		$url = $this->getApi();
50
51
		try {
52
			$sessionTokenResponse = $this->client->get("$url/webserver/SesTokInfo");
53
			$sessionTokenXml = simplexml_load_string((string)$sessionTokenResponse->getBody());
54
			if ($sessionTokenXml === false) {
55
				throw new Exception();
56
			}
57
58
			$date = date('Y-m-d H:i:s');
59
			$messageEscaped = htmlspecialchars($message, ENT_XML1);
60
61
			$sendResponse = $this->client->post("$url/sms/send-sms", [
62
				'body' => "<request><Index>-1</Index><Phones><Phone>$identifier</Phone></Phones><Sca/><Content>$messageEscaped</Content><Length>-1</Length><Reserved>1</Reserved><Date>$date</Date></request>",
63
				'headers' => [
64
					'Cookie' => (string)$sessionTokenXml->SesInfo,
65
					'X-Requested-With' => 'XMLHttpRequest',
66
					'__RequestVerificationToken' => (string)$sessionTokenXml->TokInfo,
67
					'Content-Type' => 'text/xml',
68
				],
69
			]);
70
			$body = (string)$sendResponse->getBody();
71
			$sendXml = simplexml_load_string($body);
72
		} catch (Exception $ex) {
73
			throw new MessageTransmissionException();
74
		}
75
76
		if ((string)$sendXml !== 'OK') {
77
			throw new MessageTransmissionException();
78
		}
79
	}
80
}
81