-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.gradle
244 lines (215 loc) · 9.78 KB
/
build.gradle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "com.discord4j:discord4j-core:3.3.0-RC1"
}
}
import discord4j.common.util.Snowflake
import discord4j.core.DiscordClient
import discord4j.core.event.domain.lifecycle.ReadyEvent
import discord4j.core.object.entity.channel.MessageChannel
import discord4j.core.object.entity.channel.ForumChannel
import discord4j.core.spec.ForumThreadMessageCreateSpec
import discord4j.core.spec.MessageCreateFields
import discord4j.core.spec.StartThreadInForumChannelSpec
import discord4j.discordjson.json.ChannelData
import discord4j.discordjson.json.ListThreadsData
import discord4j.rest.entity.RestChannel
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import discord4j.core.object.ThreadListPart
import java.time.Instant
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import java.util.function.Function
import java.util.function.LongFunction
import java.util.function.ToIntFunction
import java.util.function.ToLongFunction;
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
def discordFileLimit = 10240;
@FunctionalInterface
interface InstantFunction<R> {
/**
* Applies this function to the given argument.
*
* @param value the function argument
* @return the function result
*/
R apply(long s, long n)
}
@FunctionalInterface
public interface ToInstantFunction<T> {
/**
* Applies this function to the given argument.
*
* @param value the function argument
* @return the function result
*/
Instant applyAsInstant(T value);
}
class FixRestChannel {
static <T> Comparator<T> comparingInstant(ToInstantFunction<? super T> keyExtractor) {
Objects.requireNonNull(keyExtractor);
return {c1, c2 -> (keyExtractor.applyAsInstant(c1) <=> keyExtractor.applyAsInstant(c2)) }
}
private static <T> Flux<T> paginate(final InstantFunction<Flux<T>> nextPage, final ToInstantFunction<T> keyExtractor,
final Instant startAt, final boolean reverse) {
final ToLongFunction<List<T>> updateLast = { list ->
list.isEmpty() ? startAt.getEpochSecond() : keyExtractor.applyAsInstant(list.get(list.size() - 1)).getEpochSecond()
}
final ToIntFunction<List<T>> updateLast_ns = { list ->
list.isEmpty() ? startAt.getNano() : keyExtractor.applyAsInstant(list.get(list.size() - 1)).getNano()
}
final Comparator<T> comparator = comparingInstant(keyExtractor);
final AtomicLong previousStart = new AtomicLong(startAt.getEpochSecond());
final AtomicInteger previousStart_ns = new AtomicInteger(startAt.getNano());
return Flux.defer { nextPage.apply(previousStart.get(), previousStart_ns.get()) }
.sort(reverse ? comparator.reversed() : comparator)
.collectList()
.doOnNext{list -> previousStart.set(updateLast.applyAsLong(list)); previousStart_ns.set(updateLast_ns.applyAsInt(list)) }
.flatMapMany(Flux.&fromIterable)
.repeat { previousStart.get() != startAt.getEpochSecond() && previousStart_ns.get() != startAt.getNano() };
}
private static Flux<ListThreadsData> listThreads(Function<Map<String, Object>, Mono<ListThreadsData>> doRequest) {
ToInstantFunction<ListThreadsData> getLastThreadId = { response ->
List<ChannelData> threads = response.threads();
return (!response.hasMore() || threads.isEmpty()) ? Instant.ofEpochSecond(0) : Instant.parse(threads.get(threads.size() - 1).threadMetadata().get().archiveTimestamp().replace('+00:00', "Z"));
}
final InstantFunction<Flux<ListThreadsData>> nextPage = { long s, long n ->
final Map<String, Object> parameters = new HashMap<>(2);
parameters.put("limit", 100);
parameters.put("before", Instant.ofEpochSecond(s, n).toString());
return doRequest.andThen{ it.flux() }.apply(parameters);
}
return paginate(nextPage, getLastThreadId, Instant.now(), true);
}
static Flux<ListThreadsData> getPublicArchivedThreads(RestChannel self) {
listThreads{params -> self.restClient.getChannelService().listPublicArchivedThreads(self.@id, params)};
}
}
RestChannel.mixin(FixRestChannel)
def splitFile(byte[] file, int maxSize=8192) {
int parts = (int) Math.ceil((float) file.size() / (1024 * maxSize))
ByteArrayInputStream[] sections = new ByteArrayInputStream[parts]
printf("Parts: %s\n", parts)
for (int i = 0; i < parts; i++) {
int k = i*maxSize*1024
byte[] partFile
if (i == (parts - 1)) {
partFile = new byte[file.size() - k]
} else {
partFile = new byte[maxSize*1024]
}
for (int j = 0; j < partFile.size(); j++) {
partFile[j] = file[k + j]
}
printf("Part %s, Size %s\n", i, partFile.size())
sections[i] = new ByteArrayInputStream(partFile)
}
return sections
}
task publishToDiscord() {
doFirst {
def files = new ArrayList<File>()
def sections = new ArrayList<InputStream[]>()
fileTree("../build/libs").each {
if (it.size() > discordFileLimit*1024) {
ByteArrayOutputStream baOS = new ByteArrayOutputStream()
ZipOutputStream zOS = new ZipOutputStream(baOS)
zOS.putNextEntry(new ZipEntry(it.name))
zOS.write(it.readBytes())
zOS.close()
sections.add(splitFile(baOS.toByteArray(), discordFileLimit))
} else {
def section = new InputStream[1]
section[0] = it.newInputStream()
sections.add(section)
}
files.add(it)
}
def fullRef = System.getenv("WORKFLOW_GITHUB_REF").split("/", 2)
def org = fullRef[0]
def githubRef = fullRef[1]
def thirdParty = org != 'ForgeEssentials'
println("$org : $githubRef")
final def token = System.getenv("DISCORD_TOKEN")
final def client = DiscordClient.create(token)
final def channelId;
if (System.getenv("BUILD_NUMBER").startsWith("UNOFFICIAL")) {
channelId = Long.parseLong(System.getenv("DEV_BUILD_CHANNEL_ID"))
} else {
channelId = Long.parseLong(System.getenv("RELEASE_CHANNEL_ID"))
}
println("ChannelId: $channelId")
def login = client.withGateway { gateway ->
gateway.on(ReadyEvent.class, { event ->
def self = event.getSelf()
printf("Logged in as %s#%s%n", self.getUsername(), self.getDiscriminator())
println("Sending...")
def tmp = gateway.getChannelById(Snowflake.of(channelId)).block()
def channel = null
def guildID = Snowflake.of(tmp.data.guildId().get())
if (tmp instanceof ForumChannel) {
def threads = gateway.getGuildById(guildID).block().getActiveThreads().block().threads
def branch = githubRef.split("/", 2)[1];
def threadName = (thirdParty ? org + " -- " : "") + branch
channel = threads.find{ it.name == threadName && it.parentId.get() == tmp.getId()}
if (channel == null) {
def aThreads = tmp.restChannel.getPublicArchivedThreads().map{data -> new ThreadListPart(gateway, data)}.blockFirst()
def found = aThreads.threads.findAll {it.name == threadName }.sort {a, b -> (b.archiveTimestamp <=> a.archiveTimestamp) }
if (found.size() > 0) {
channel = found.get(0)
channel.edit().withArchived(false).block()
}
}
if (channel == null) {
def builder = StartThreadInForumChannelSpec.builder()
.name(threadName)
.addAppliedTag(tmp.availableTags.find {it.name == "Build"}.id)
.message(ForumThreadMessageCreateSpec.builder()
.content("Builds for Ref: $githubRef")
.build())
if (branch.endsWith("develop")) {
builder.addAppliedTag(tmp.availableTags.find {it.name == "Stable"}.id)
}
channel = tmp.startThread (builder.build()).block()
}
} else {
channel = tmp as MessageChannel
}
println(channel.getType())
Mono prev = null
for (int i = 0; i < sections.size(); i++) {
boolean zipFiles = sections[i].size() > 1 || sections[i][0] instanceof ByteArrayInputStream
for (int j = 0; j < sections[i].size(); j++) {
String archiveName = files[i].name
if (zipFiles) {
archiveName += ".zip${sections[i].size() > 1 ? ".${String.format("%03d", j + 1)}" : ""}"
}
def content = "Forge Essentials build for${thirdParty ? " Third Party: `$org` --" : ""} Ref\\: `$githubRef` -- `$archiveName`"
println(content)
Mono cur = channel.createMessage()
.withContent(content)
.withFiles(MessageCreateFields.File.of(archiveName, sections[i][j])).then()
cur.doOnError({ error ->
println("Error sending Message")
})
if (prev != null) {
prev &= cur
} else {
prev = cur
}
}
}
return prev
}).then()
}
login.subscribe()
println("Message Sending...")
Thread.sleep(15000)
println("Complete")
}
}