Skip to content

Commit 564c177

Browse files
author
iAldrich23xX
committed
[Release] add verifying to correct format on PHP & fix embed format
1 parent 9ceefdf commit 564c177

File tree

12 files changed

+105
-81
lines changed

12 files changed

+105
-81
lines changed

libasynDiscordWebHook-API/pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<parent>
66
<groupId>com.ialdrich23xx</groupId>
77
<artifactId>libasynwebhook</artifactId>
8-
<version>1.0.0</version>
8+
<version>1.0.1</version>
99
</parent>
1010

1111
<groupId>com.ialdrich23xx.libasynwebhook.api</groupId>

libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/Loader.java

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
package com.ialdrich23xx.libasynwebhook.api;
22

3+
import com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base.BodyException;
34
import lombok.Getter;
4-
import org.apache.commons.validator.UrlValidator;
5+
import org.apache.commons.validator.routines.UrlValidator;
6+
7+
import java.lang.reflect.Array;
8+
import java.util.Map;
9+
import java.util.Set;
510

611
public class Loader {
712

@@ -17,4 +22,45 @@ public Boolean isValidUrl(String url)
1722
UrlValidator urlValidator = new UrlValidator();
1823
return urlValidator.isValid(url);
1924
}
25+
26+
public String quote(String string) {
27+
return "\"" + string + "\"";
28+
}
29+
30+
public String formatToJson(Set<Map.Entry<String, Object>> format) {
31+
StringBuilder builder = new StringBuilder();
32+
33+
builder.append("{");
34+
35+
int i = 0;
36+
37+
for (Map.Entry<String, Object> entry : format) {
38+
Object value = entry.getValue();
39+
builder.append(quote(entry.getKey())).append(":");
40+
41+
if (value instanceof String) {
42+
builder.append(quote(String.valueOf(value)));
43+
} else if (value instanceof Integer) {
44+
builder.append(Integer.valueOf(String.valueOf(value)));
45+
} else if (value instanceof Boolean) {
46+
builder.append(value);
47+
} else if (value.getClass().isArray()) {
48+
builder.append("[");
49+
50+
int len = Array.getLength(value);
51+
52+
for (int j = 0; j < len; j++) {
53+
builder.append(Array.get(value, j).toString()).append(j != len - 1 ? "," : "");
54+
}
55+
56+
builder.append("]");
57+
} else {
58+
throw new BodyException((Throwable) value);
59+
}
60+
61+
builder.append(++i == format.size() ? "}" : ",");
62+
}
63+
64+
return builder.toString();
65+
}
2066
}

libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/Base.java

Lines changed: 7 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,10 @@ public List<EmbedManager> getEmbeds() {
8181
@Override
8282
public Boolean build() {
8383
if (this.getAvatar() != null && !Loader.getInstance().isValidUrl(this.getAvatar())) return false;
84+
if (this.getContent() == null && this.getEmbeds().isEmpty()) return false;
85+
if (this.getContent() != null && this.getContent().length() == 0) return false;
8486

85-
return (this.getContent() != null || !this.getContent().isEmpty()) || !this.getEmbeds().isEmpty();
87+
return true;
8688
}
8789

8890
@Override
@@ -95,14 +97,12 @@ public Map<String, Object> toArray() {
9597
if (this.getUsername() != null) result.put("username", this.getUsername());
9698
if (this.getAvatar() != null) result.put("avatar_url", this.getAvatar());
9799

98-
List<Map<String, Object>> embedList = new ArrayList<>();
100+
List<Object> embedList = new ArrayList<>();
99101

100-
this.getEmbeds().forEach(embed -> {
101-
embedList.add(embed.toArray());
102-
});
102+
this.getEmbeds().forEach(embed -> embedList.add(Loader.getInstance().formatToJson(embed.toArray().entrySet())));
103103

104104
if (!embedList.isEmpty()) {
105-
result.put("embeds", embedList);
105+
result.put("embeds", embedList.toArray());
106106
}
107107

108108
return result;
@@ -115,39 +115,7 @@ public String toString() {
115115
}
116116

117117
public String toJson() {
118-
StringBuilder builder = new StringBuilder();
119-
120-
Set<Map.Entry<String, Object>> entrySet = this.toArray().entrySet();
121-
builder.append("{");
122-
123-
int i = 0;
124-
125-
for (Map.Entry<String, Object> entry : entrySet) {
126-
Object value = entry.getValue();
127-
builder.append(quote(entry.getKey())).append(":");
128-
129-
if (value instanceof String) {
130-
builder.append(quote(String.valueOf(value)));
131-
} else if (value instanceof Integer) {
132-
builder.append(Integer.valueOf(String.valueOf(value)));
133-
} else if (value instanceof Boolean) {
134-
builder.append(value);
135-
} else if (value.getClass().isArray()) {
136-
builder.append("[");
137-
138-
int len = Array.getLength(value);
139-
140-
for (int j = 0; j < len; j++) {
141-
builder.append(Array.get(value, j).toString()).append(j != len - 1 ? "," : "");
142-
}
143-
144-
builder.append("]");
145-
}
146-
147-
builder.append(++i == entrySet.size() ? "}" : ",");
148-
}
149-
150-
return builder.toString();
118+
return Loader.getInstance().formatToJson(this.toArray().entrySet());
151119
}
152120

153121
private String quote(String string) {

libasynDiscordWebHook-API/src/main/java/com/ialdrich23xx/libasynwebhook/api/discord/body/embed/EmbedManager.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.ialdrich23xx.libasynwebhook.api.discord.body.embed;
22

3+
import com.ialdrich23xx.libasynwebhook.api.Loader;
34
import com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base.BodyException;
45
import com.ialdrich23xx.libasynwebhook.api.discord.body.embed.base.Structure;
56
import com.ialdrich23xx.libasynwebhook.api.discord.body.embed.components.*;
@@ -194,14 +195,12 @@ public Map<String, Object> toArray() {
194195
if (this.getImage() != null) result.put("image", this.getImage().toArray());
195196
if (this.getTimestamp() != null) result.put("timestamp", this.getTimestamp().getFormat().format(this.getTimestamp().getDate()));
196197

197-
List<Map<String, Object>> fieldList = new ArrayList<>();
198+
List<Object> fieldList = new ArrayList<>();
198199

199-
this.getFields().forEach(field -> {
200-
fieldList.add(field.toArray());
201-
});
200+
this.getFields().forEach(field -> fieldList.add(Loader.getInstance().formatToJson(field.toArray().entrySet())));
202201

203202
if (!fieldList.isEmpty()) {
204-
result.put("fields", fieldList);
203+
result.put("fields", fieldList.toArray());
205204
}
206205

207206
return result;

libasynDiscordWebHook-PM/src/ialdrich23xx/libasynwebhook/Loader.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010
use pocketmine\Server;
1111
use pocketmine\utils\SingletonTrait;
1212
use ialdrich23xx\libasynwebhook\thread\Pool;
13+
use function filter_var;
1314
use function is_null;
15+
use const FILTER_VALIDATE_URL;
1416

1517
class Loader
1618
{

libasynDiscordWebHook-PM/src/ialdrich23xx/libasynwebhook/discord/WebHook.php

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use ialdrich23xx\libasynwebhook\discord\body\Base;
99
use ialdrich23xx\libasynwebhook\Loader;
1010
use ialdrich23xx\libasynwebhook\thread\SendWebHookTask;
11+
use function is_null;
1112

1213
class WebHook
1314
{
@@ -38,18 +39,20 @@ public function setBody(Base $body): self
3839
return $this;
3940
}
4041

41-
/**
42-
* @throws JsonException
43-
*/
44-
public function send(): void
42+
/**
43+
* @throws JsonException
44+
*/
45+
public function send(): void
4546
{
4647
if (is_null($this->getBody())) {
4748
Loader::getInstance()->getPlugin()->getLogger()->error("Body of webhook is null");
4849
return;
4950
}
5051

5152
if (Loader::getInstance()->isValidUrl($this->getUrl())) {
52-
Loader::getInstance()->getThread()->submitTask(new SendWebHookTask($this));
53+
if ($this->getBody()->build()) {
54+
Loader::getInstance()->getThread()->submitTask(new SendWebHookTask($this));
55+
} else Loader::getInstance()->getPlugin()->getLogger()->error("Webhook build failed");
5356
} else Loader::getInstance()->getPlugin()->getLogger()->error("Url not valid: " . $this->getUrl());
5457
}
5558
}

libasynDiscordWebHook-PM/src/ialdrich23xx/libasynwebhook/discord/body/Base.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,10 @@ public function getEmbeds(): array
100100
public function build(): bool
101101
{
102102
if (!is_null($this->getAvatar()) && !Loader::getInstance()->isValidUrl($this->getAvatar())) return false;
103+
if (is_null($this->getContent()) && empty($this->getEmbeds())) return false;
104+
if (!is_null($this->getContent()) && strlen($this->getContent()) === 0) return false;
103105

104-
return (!is_null($this->getContent()) && strlen($this->getContent()) !== 0) || !empty($this->getEmbeds());
106+
return true;
105107
}
106108

107109
public function jsonSerialize(): array
@@ -129,6 +131,6 @@ public function toArray(): array
129131
public function toString(): string
130132
{
131133
return "Base(content=" . $this->getContent() . ",username=" . $this->getUsername() . ",avatar=" . $this->getAvatar() .
132-
";embeds=Array(" . count($this->getEmbeds()) . ")";
134+
";embeds=Array(" . count($this->getEmbeds()) . ")";
133135
}
134136
}

libasynDiscordWebHook-PM/src/ialdrich23xx/libasynwebhook/discord/body/embed/EmbedManager.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,7 @@ public function toArray(): array
237237
public function toString(): string
238238
{
239239
return "EmbedManager(title=" . $this->getTitle() . ",description=" . $this->getDescription() . ",color=" . $this->getColor() .
240-
",author=" . $this->getAuthor()?->toString() . ",footer=" . $this->getFooter()?->toString() . ",thumbnail=" . $this->getThumbnail()?->toString() .
241-
",image=" . $this->getImage()?->toString() . ",timestamp=" . $this->getTimestamp()?->toString() . ")";
240+
",author=" . $this->getAuthor()?->toString() . ",footer=" . $this->getFooter()?->toString() . ",thumbnail=" . $this->getThumbnail()?->toString() .
241+
",image=" . $this->getImage()?->toString() . ",timestamp=" . $this->getTimestamp()?->toString() . ")";
242242
}
243243
}

libasynDiscordWebHook-PM/src/ialdrich23xx/libasynwebhook/thread/Pool.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use pocketmine\scheduler\AsyncPool;
88
use pocketmine\scheduler\DumpWorkerMemoryTask;
99
use pocketmine\scheduler\GarbageCollectionTask;
10+
use function gc_collect_cycles;
1011

1112
class Pool extends AsyncPool
1213
{

libasynDiscordWebHook-PM/src/ialdrich23xx/libasynwebhook/thread/SendWebHookTask.php

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -9,47 +9,50 @@
99
use pocketmine\scheduler\AsyncTask;
1010
use pocketmine\utils\Internet;
1111
use ialdrich23xx\libasynwebhook\discord\WebHook;
12+
use function igbinary_serialize;
13+
use function igbinary_unserialize;
1214
use function is_null;
1315
use function json_encode;
16+
use const JSON_THROW_ON_ERROR;
1417

1518
class SendWebHookTask extends AsyncTask
1619
{
17-
private string $page;
18-
private int $timeout;
19-
private string $args;
20-
private string $headers;
21-
22-
/**
23-
* @throws JsonException
24-
*/
25-
public function __construct(WebHook $webHook) {
20+
private string $page;
21+
private int $timeout;
22+
private string $args;
23+
private string $headers;
24+
25+
/**
26+
* @throws JsonException
27+
*/
28+
public function __construct(WebHook $webHook) {
2629
if (is_null($webHook->getBody())) {
2730
$this->cancelRun();
2831

2932
return;
3033
}
3134

32-
$this->args = json_encode($webHook->getBody()->jsonSerialize(), JSON_THROW_ON_ERROR);
35+
$this->args = json_encode($webHook->getBody()->jsonSerialize(), JSON_THROW_ON_ERROR);
3336

34-
$this->page = $webHook->getUrl();
35-
$this->timeout = 10;
37+
$this->page = $webHook->getUrl();
38+
$this->timeout = 10;
3639

37-
$serialized_headers = igbinary_serialize(["Content-Type: application/json"]);
40+
$serialized_headers = igbinary_serialize(["Content-Type: application/json"]);
3841

39-
if ($serialized_headers === null) {
40-
throw new InvalidArgumentException("Headers cannot be serialized");
41-
}
42+
if ($serialized_headers === null) {
43+
throw new InvalidArgumentException("Headers cannot be serialized");
44+
}
4245

43-
$this->headers = $serialized_headers;
44-
}
46+
$this->headers = $serialized_headers;
47+
}
4548

46-
public function getHeaders(): array
47-
{
48-
/** @var array $headers */
49-
$headers = igbinary_unserialize($this->headers);
49+
public function getHeaders(): array
50+
{
51+
/** @var array $headers */
52+
$headers = igbinary_unserialize($this->headers);
5053

51-
return $headers;
52-
}
54+
return $headers;
55+
}
5356

5457
public function onRun(): void
5558
{

0 commit comments

Comments
 (0)