001/*
002 * PlotSquared, a land and world management plugin for Minecraft.
003 * Copyright (C) IntellectualSites <https://intellectualsites.com>
004 * Copyright (C) IntellectualSites team and contributors
005 *
006 * This program is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
018 */
019package com.plotsquared.core.command;
020
021import com.google.inject.Inject;
022import com.plotsquared.core.configuration.Settings;
023import com.plotsquared.core.configuration.caption.StaticCaption;
024import com.plotsquared.core.configuration.caption.TranslatableCaption;
025import com.plotsquared.core.permissions.Permission;
026import com.plotsquared.core.player.PlotPlayer;
027import com.plotsquared.core.plot.Plot;
028import com.plotsquared.core.plot.flag.implementations.DoneFlag;
029import com.plotsquared.core.plot.world.PlotAreaManager;
030import com.plotsquared.core.util.PlotUploader;
031import com.plotsquared.core.util.SchematicHandler;
032import com.plotsquared.core.util.StringMan;
033import com.plotsquared.core.util.TabCompletions;
034import com.plotsquared.core.util.WorldUtil;
035import com.plotsquared.core.util.task.RunnableVal;
036import net.kyori.adventure.text.Component;
037import net.kyori.adventure.text.minimessage.tag.Tag;
038import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
039import org.checkerframework.checker.nullness.qual.NonNull;
040
041import java.net.URL;
042import java.util.Collection;
043import java.util.Collections;
044import java.util.LinkedList;
045import java.util.List;
046import java.util.stream.Collectors;
047
048@CommandDeclaration(usage = "/plot download [schem | world]",
049        command = "download",
050        aliases = {"dl"},
051        category = CommandCategory.SCHEMATIC,
052        requiredType = RequiredType.NONE,
053        permission = "plots.download")
054public class Download extends SubCommand {
055
056    private final PlotAreaManager plotAreaManager;
057    private final PlotUploader plotUploader;
058    @NonNull
059    private final SchematicHandler schematicHandler;
060    private final WorldUtil worldUtil;
061
062    @Inject
063    public Download(
064            final @NonNull PlotAreaManager plotAreaManager,
065            final @NonNull PlotUploader plotUploader,
066            final @NonNull SchematicHandler schematicHandler,
067            final @NonNull WorldUtil worldUtil
068    ) {
069        this.plotAreaManager = plotAreaManager;
070        this.plotUploader = plotUploader;
071        this.schematicHandler = schematicHandler;
072        this.worldUtil = worldUtil;
073    }
074
075    @Override
076    public boolean onCommand(final PlotPlayer<?> player, String[] args) {
077        String world = player.getLocation().getWorldName();
078        if (!this.plotAreaManager.hasPlotArea(world)) {
079            player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
080            return false;
081        }
082        final Plot plot = player.getCurrentPlot();
083        if (plot == null) {
084            player.sendMessage(TranslatableCaption.of("errors.not_in_plot"));
085            return false;
086        }
087        if (!plot.hasOwner()) {
088            player.sendMessage(TranslatableCaption.of("info.plot_unowned"));
089            return false;
090        }
091        if ((Settings.Done.REQUIRED_FOR_DOWNLOAD && !DoneFlag.isDone(plot)) && !player.hasPermission(Permission.PERMISSION_ADMIN_COMMAND_DOWNLOAD)) {
092            player.sendMessage(TranslatableCaption.of("done.done_not_done"));
093            return false;
094        }
095        if (!plot.isOwner(player.getUUID()) && !player.hasPermission(Permission.PERMISSION_ADMIN.toString())) {
096            player.sendMessage(TranslatableCaption.of("permission.no_plot_perms"));
097            return false;
098        }
099        if (plot.getRunning() > 0) {
100            player.sendMessage(TranslatableCaption.of("errors.wait_for_timer"));
101            return false;
102        }
103        if (args.length == 0 || (args.length == 1 && StringMan
104                .isEqualIgnoreCaseToAny(args[0], "sch", "schem", "schematic"))) {
105            if (plot.getVolume() > Integer.MAX_VALUE) {
106                player.sendMessage(TranslatableCaption.of("schematics.schematic_too_large"));
107                return false;
108            }
109            plot.addRunning();
110            upload(player, plot);
111        } else if (args.length == 1 && StringMan
112                .isEqualIgnoreCaseToAny(args[0], "mcr", "world", "mca")) {
113            if (!player.hasPermission(Permission.PERMISSION_DOWNLOAD_WORLD)) {
114                player.sendMessage(
115                        TranslatableCaption.of("permission.no_permission"),
116                        TagResolver.resolver(
117                                "node",
118                                Tag.inserting(Permission.PERMISSION_DOWNLOAD_WORLD)
119                        )
120                );
121                return false;
122            }
123            player.sendMessage(TranslatableCaption.of("schematics.mca_file_size"));
124            plot.addRunning();
125            this.worldUtil.saveWorld(world);
126            this.worldUtil.upload(plot, null, null, new RunnableVal<>() {
127                @Override
128                public void run(URL url) {
129                    plot.removeRunning();
130                    if (url == null) {
131                        player.sendMessage(
132                                TranslatableCaption.of("web.generating_link_failed"),
133                                TagResolver.resolver("plot", Tag.inserting(Component.text(plot.getId().toString())))
134                        );
135                        return;
136                    }
137                    player.sendMessage(
138                            TranslatableCaption.of("web.generation_link_success_legacy_world"),
139                            TagResolver.resolver("url", Tag.inserting(Component.text(url.toString())))
140                    );
141                }
142            });
143        } else {
144            sendUsage(player);
145            return false;
146        }
147        player.sendMessage(
148                TranslatableCaption.of("web.generating_link"),
149                TagResolver.resolver("plot", Tag.inserting(Component.text(plot.getId().toString())))
150        );
151        return true;
152    }
153
154    @Override
155    public Collection<Command> tab(final PlotPlayer<?> player, final String[] args, final boolean space) {
156        if (args.length == 1) {
157            final List<String> completions = new LinkedList<>();
158            if (player.hasPermission(Permission.PERMISSION_DOWNLOAD)) {
159                completions.add("schem");
160            }
161            if (player.hasPermission(Permission.PERMISSION_DOWNLOAD_WORLD)) {
162                completions.add("world");
163            }
164            final List<Command> commands = completions.stream().filter(completion -> completion
165                            .toLowerCase()
166                            .startsWith(args[0].toLowerCase()))
167                    .map(completion -> new Command(
168                            null,
169                            true,
170                            completion,
171                            "",
172                            RequiredType.NONE,
173                            CommandCategory.ADMINISTRATION
174                    ) {
175                    }).collect(Collectors.toCollection(LinkedList::new));
176            if (player.hasPermission(Permission.PERMISSION_DOWNLOAD) && args[0].length() > 0) {
177                commands.addAll(TabCompletions.completePlayers(player, args[0], Collections.emptyList()));
178            }
179            return commands;
180        }
181        return TabCompletions.completePlayers(player, String.join(",", args).trim(), Collections.emptyList());
182    }
183
184    private void upload(PlotPlayer<?> player, Plot plot) {
185        if (Settings.Web.LEGACY_WEBINTERFACE) {
186            schematicHandler
187                    .getCompoundTag(plot)
188                    .whenComplete((compoundTag, throwable) -> schematicHandler.upload(
189                            compoundTag,
190                            null,
191                            null,
192                            new RunnableVal<>() {
193                                @Override
194                                public void run(URL value) {
195                                    plot.removeRunning();
196                                    player.sendMessage(
197                                            TranslatableCaption.of("web.generation_link_success"),
198                                            TagResolver.builder()
199                                                    .tag("download", Tag.preProcessParsed(value.toString()))
200                                                    .tag("delete", Tag.preProcessParsed("Not available"))
201                                                    .build()
202                                    );
203                                    player.sendMessage(StaticCaption.of(value.toString()));
204                                }
205                            }
206                    ));
207            return;
208        }
209        // TODO legacy support
210        this.plotUploader.upload(plot)
211                .whenComplete((result, throwable) -> {
212                    if (throwable != null || !result.isSuccess()) {
213                        player.sendMessage(
214                                TranslatableCaption.of("web.generating_link_failed"),
215                                TagResolver.resolver("plot", Tag.inserting(Component.text(plot.getId().toString())))
216                        );
217                    } else {
218                        player.sendMessage(
219                                TranslatableCaption.of("web.generation_link_success"),
220                                TagResolver.builder()
221                                        .tag("download", Tag.preProcessParsed(result.getDownloadUrl()))
222                                        .tag("delete", Tag.preProcessParsed(result.getDeletionUrl()))
223                                        .build()
224                        );
225                    }
226                });
227    }
228
229}