This repository has been archived by the owner on Feb 3, 2024. It is now read-only.
/
PermissionsEx.java
431 lines (383 loc) · 17.5 KB
/
PermissionsEx.java
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/**
* PermissionsEx
* Copyright (C) zml and PermissionsEx contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ninja.leaping.permissionsex;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.sk89q.squirrelid.resolver.HttpRepositoryService;
import com.sk89q.squirrelid.resolver.ProfileService;
import ninja.leaping.permissionsex.backend.DataStore;
import ninja.leaping.permissionsex.backend.memory.MemoryDataStore;
import ninja.leaping.permissionsex.command.PermissionsExCommands;
import ninja.leaping.permissionsex.command.RankingCommands;
import ninja.leaping.permissionsex.config.PermissionsExConfiguration;
import ninja.leaping.permissionsex.data.CacheListenerHolder;
import ninja.leaping.permissionsex.data.Caching;
import ninja.leaping.permissionsex.exception.PEBKACException;
import ninja.leaping.permissionsex.logging.TranslatableLogger;
import ninja.leaping.permissionsex.subject.CalculatedSubject;
import ninja.leaping.permissionsex.data.ContextInheritance;
import ninja.leaping.permissionsex.data.ImmutableSubjectData;
import ninja.leaping.permissionsex.data.RankLadderCache;
import ninja.leaping.permissionsex.data.SubjectCache;
import ninja.leaping.permissionsex.subject.SubjectDataBaker;
import ninja.leaping.permissionsex.exception.PermissionsLoadingException;
import ninja.leaping.permissionsex.util.Util;
import ninja.leaping.permissionsex.util.command.CommandSpec;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import static com.google.common.base.Preconditions.checkNotNull;
import static ninja.leaping.permissionsex.util.Translations.*;
public class PermissionsEx implements ImplementationInterface, Caching<ContextInheritance> {
public static final String SUBJECTS_USER = "user";
public static final String SUBJECTS_GROUP = "group";
public static final String SUBJECTS_DEFAULTS = "default";
public static final ImmutableSet<Map.Entry<String, String>> GLOBAL_CONTEXT = ImmutableSet.of();
private final Map<String, Function<String, String>> nameTransformerMap = new ConcurrentHashMap<>();
private final TranslatableLogger logger;
private final ImplementationInterface impl;
private final MemoryDataStore transientData;
private volatile boolean debug;
private final AtomicReference<State> state = new AtomicReference<>();
private final ConcurrentMap<String, SubjectCache> subjectCaches = new ConcurrentHashMap<>(), transientSubjectCaches = new ConcurrentHashMap<>();
private RankLadderCache rankLadderCache;
private final LoadingCache<Map.Entry<String, String>, CalculatedSubject> calculatedSubjects = CacheBuilder.newBuilder().maximumSize(512).build(new CacheLoader<Map.Entry<String, String>, CalculatedSubject>() {
@Override
public CalculatedSubject load(Map.Entry<String, String> key) throws Exception {
return new CalculatedSubject(SubjectDataBaker.inheritance(), key, PermissionsEx.this);
}
});
private volatile ContextInheritance cachedInheritance;
private final CacheListenerHolder<Boolean, ContextInheritance> cachedInheritanceListeners = new CacheListenerHolder<>();
private static class State {
private final PermissionsExConfiguration config;
private final DataStore activeDataStore;
private State(PermissionsExConfiguration config, DataStore activeDataStore) {
this.config = config;
this.activeDataStore = activeDataStore;
}
}
public PermissionsEx(final PermissionsExConfiguration config, ImplementationInterface impl) throws PermissionsLoadingException {
this.impl = impl;
this.logger = TranslatableLogger.forLogger(impl.getLogger());
this.transientData = new MemoryDataStore();
this.transientData.initialize(this);
this.debug = config.isDebugEnabled();
initialize(config);
convertUuids();
registerCommand(PermissionsExCommands.createRootCommand(this));
registerCommand(RankingCommands.getPromoteCommand(this));
registerCommand(RankingCommands.getDemoteCommand(this));
}
private State getState() throws IllegalStateException {
State ret = this.state.get();
if (ret == null) {
throw new IllegalStateException("Manager has already been closed!");
}
return ret;
}
private void convertUuids() {
try {
InetAddress.getByName("api.mojang.com");
getState().activeDataStore.performBulkOperation(input -> {
Iterable<String> toConvert = Iterables.filter(input.getAllIdentifiers(SUBJECTS_USER), input1 -> {
if (input1 == null || input1.length() != 36) {
return true;
}
try {
UUID.fromString(input1);
return false;
} catch (IllegalArgumentException e) {
return true;
}
});
if (toConvert.iterator().hasNext()) {
getLogger().info(t("Trying to convert users stored by name to UUID"));
} else {
return 0;
}
final ProfileService service = HttpRepositoryService.forMinecraft();
try {
final int[] converted = {0};
service.findAllByName(toConvert, profile -> {
final String newIdentifier = profile.getUniqueId().toString();
if (input.isRegistered(SUBJECTS_USER, newIdentifier)) {
getLogger().warn(t("Duplicate entry for %s found while converting to UUID", newIdentifier + "/" + profile.getName()));
return false; // We already have a registered UUID, this is a duplicate.
}
String lookupName = profile.getName();
if (!input.isRegistered(SUBJECTS_USER, lookupName)) {
lookupName = lookupName.toLowerCase();
}
if (!input.isRegistered(SUBJECTS_USER, lookupName)) {
return false;
}
converted[0]++;
ImmutableSubjectData oldData = input.getData(SUBJECTS_USER, profile.getName(), null);
final String finalLookupName = lookupName;
input.setData(SUBJECTS_USER, newIdentifier, oldData.setOption(GLOBAL_CONTEXT, "name", profile.getName()))
.thenAccept(result -> input.setData(SUBJECTS_USER, finalLookupName, null)
.exceptionally(t -> {
t.printStackTrace();
return null;
}));
return true;
});
return converted[0];
} catch (IOException | InterruptedException e) {
getLogger().error(t("Error while fetching UUIDs for users"), e);
return 0;
}
}).thenAccept(result -> {
if (result != null && result > 0) {
getLogger().info(tn("%s user successfully converted from name to UUID",
"%s users successfully converted from name to UUID!",
result, result));
}
}).exceptionally(t -> {
getLogger().error(t("Error converting users to UUID"), t);
return null;
});
} catch (UnknownHostException e) {
getLogger().warn(t("Unable to resolve Mojang API for UUID conversion. Do you have an internet connection? UUID conversion will not proceed (but may not be necessary)."));
}
}
public SubjectCache getSubjects(String type) {
checkNotNull(type, "type");
SubjectCache cache = subjectCaches.get(type);
if (cache == null) {
cache = new SubjectCache(type, getState().activeDataStore);
SubjectCache newCache = subjectCaches.putIfAbsent(type, cache);
if (newCache != null) {
cache = newCache;
}
}
return cache;
}
public SubjectCache getTransientSubjects(String type) {
checkNotNull(type, "type");
SubjectCache cache = transientSubjectCaches.get(type);
if (cache == null) {
cache = new SubjectCache(type, transientData);
SubjectCache newCache = transientSubjectCaches.putIfAbsent(type, cache);
if (newCache != null) {
cache = newCache;
}
}
return cache;
}
public void uncache(String type, String identifier) {
SubjectCache cache = subjectCaches.get(type);
if (cache != null) {
cache.invalidate(identifier);
}
cache = transientSubjectCaches.get(type);
if (cache != null) {
cache.invalidate(identifier);
}
calculatedSubjects.invalidate(Maps.immutableEntry(type, identifier));
}
/**
* Access rank ladders through a cached interface
*
* @return Access to rank ladders
*/
public RankLadderCache getLadders() {
return this.rankLadderCache;
}
/**
* Imports data into the currently active backend from the backend identified by the provided identifier
*
* @param dataStoreIdentifier The identifier of the backend to import from
* @return A future that completes once the import operation is complete
*/
public CompletableFuture<Void> importDataFrom(String dataStoreIdentifier) {
final State state = getState();
final DataStore expected = state.config.getDataStore(dataStoreIdentifier);
if (expected == null) {
return Util.failedFuture(new IllegalArgumentException("Data store " + dataStoreIdentifier + " is not present"));
}
try {
expected.initialize(this);
} catch (PermissionsLoadingException e) {
return Util.failedFuture(e);
}
return state.activeDataStore.performBulkOperation(store -> {
CompletableFuture<Void> ret = CompletableFuture.allOf(Iterables.toArray(Iterables.transform(expected.getAll(),
input -> store.setData(input.getKey().getKey(), input.getKey().getValue(), input.getValue())), CompletableFuture.class))
.thenCombine(store.setContextInheritance(expected.getContextInheritance(null)), (v, a) -> null);
for (String ladder : store.getAllRankLadders()) {
ret = ret.thenCombine(store.setRankLadder(ladder, expected.getRankLadder(ladder, null)), (v, a) -> null);
}
return ret;
}).thenCompose(val -> Util.failableFuture(val::get));
}
public Set<String> getRegisteredSubjectTypes() {
return getState().activeDataStore.getRegisteredTypes();
}
public void setDebugMode(boolean debug) {
this.debug = debug;
}
public boolean hasDebugMode() {
return this.debug;
}
private void reloadSync() throws PEBKACException, PermissionsLoadingException {
try {
PermissionsExConfiguration config = getState().config.reload();
config.validate();
initialize(config);
getSubjects(SUBJECTS_GROUP).cacheAll();
} catch (IOException e) {
throw new PEBKACException(t("Error while loading configuration: %s", e.getLocalizedMessage()));
}
}
private void initialize(PermissionsExConfiguration config) throws PermissionsLoadingException {
State newState = new State(config, config.getDefaultDataStore());
newState.activeDataStore.initialize(this);
State oldState = this.state.getAndSet(newState);
if (oldState != null) {
try {
oldState.activeDataStore.close();
} catch (Exception e) {} // TODO maybe warn?
}
getSubjects(SUBJECTS_GROUP).cacheAll();
this.rankLadderCache = new RankLadderCache(this.rankLadderCache, newState.activeDataStore);
this.subjectCaches.replaceAll((key, existing) -> new SubjectCache(existing, newState.activeDataStore));
if (this.cachedInheritance != null) {
this.cachedInheritance = null;
this.cachedInheritanceListeners.call(true, getContextInheritance(null));
}
// Migrate over legacy subject data
newState.activeDataStore.moveData("system", SUBJECTS_DEFAULTS, SUBJECTS_DEFAULTS, SUBJECTS_DEFAULTS).thenRun(() -> {
getLogger().info(t("Successfully migrated old-style default data to new location"));
});
}
public CompletableFuture<Void> reload() {
return Util.asyncFailableFuture(() -> {
reloadSync();
return null;
}, getAsyncExecutor());
}
public void close() {
State state = this.state.getAndSet(null);
state.activeDataStore.close();
}
@Override
public Path getBaseDirectory() {
return impl.getBaseDirectory();
}
@Override
public TranslatableLogger getLogger() {
return this.logger;
}
@Override
public DataSource getDataSourceForURL(String url) {
return impl.getDataSourceForURL(url);
}
/**
* Get an executor to run tasks asynchronously on.
*
* @return The async executor
*/
@Override
public Executor getAsyncExecutor() {
return impl.getAsyncExecutor();
}
@Override
public void registerCommand(CommandSpec command) {
impl.registerCommand(command);
}
@Override
public Set<CommandSpec> getImplementationCommands() {
return impl.getImplementationCommands();
}
@Override
public String getVersion() {
return impl.getVersion();
}
/**
* Returns a function that can be applied to a friendly name to convert it into a valid subject identifier.
* If no function is explicitly registered, an identity function ({@link Function#identity()}) should be used.
*
* @param type The type of subject
* @return The transformation function
*/
public Function<String, String> getNameTransformer(String type) {
Function<String, String> xform = nameTransformerMap.get(type);
if (xform == null) {
xform = Function.identity();
}
return xform;
}
/**
* Register a name transformer for a subject type if none is present
* @param type The subject type to register a name transformer for
* @param func The transformer function
* @return true if the transformer was successfully registered
*/
public boolean registerNameTransformer(String type, Function<String, String> func) {
return this.nameTransformerMap.putIfAbsent(checkNotNull(type, "type"), checkNotNull(func, "func")) == null;
}
public PermissionsExConfiguration getConfig() {
return getState().config;
}
public CalculatedSubject getCalculatedSubject(String type, String identifier) throws PermissionsLoadingException {
try {
return calculatedSubjects.get(Maps.immutableEntry(type, identifier));
} catch (ExecutionException e) {
throw new PermissionsLoadingException(t("While calculating subject data for %s:%s", type, identifier), e);
}
}
public Iterable<? extends CalculatedSubject> getActiveCalculatedSubjects() {
return Collections.unmodifiableCollection(calculatedSubjects.asMap().values());
}
public ContextInheritance getContextInheritance(Caching<ContextInheritance> listener) {
if (this.cachedInheritance == null) {
this.cachedInheritance = getState().activeDataStore.getContextInheritance(this);
}
if (listener != null) {
this.cachedInheritanceListeners.addListener(true, listener);
}
return this.cachedInheritance;
}
public CompletableFuture<ContextInheritance> setContextInheritance(ContextInheritance newInheritance) {
return getState().activeDataStore.setContextInheritance(newInheritance);
}
@Override
public void clearCache(ContextInheritance newData) {
this.cachedInheritance = newData;
this.cachedInheritanceListeners.call(true, newData);
}
}