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.builder()
140                                    .tag("url", Tag.preProcessParsed(url.toString()))
141                                    .build()
142                    );
143                }
144            });
145        } else {
146            sendUsage(player);
147            return false;
148        }
149        player.sendMessage(
150                TranslatableCaption.of("web.generating_link"),
151                TagResolver.resolver("plot", Tag.inserting(Component.text(plot.getId().toString())))
152        );
153        return true;
154    }
155
156    @Override
157    public Collection<Command> tab(final PlotPlayer<?> player, final String[] args, final boolean space) {
158        if (args.length == 1) {
159            final List<String> completions = new LinkedList<>();
160            if (player.hasPermission(Permission.PERMISSION_DOWNLOAD)) {
161                completions.add("schem");
162            }
163            if (player.hasPermission(Permission.PERMISSION_DOWNLOAD_WORLD)) {
164                completions.add("world");
165            }
166            final List<Command> commands = completions.stream().filter(completion -> completion
167                            .toLowerCase()
168                            .startsWith(args[0].toLowerCase()))
169                    .map(completion -> new Command(
170                            null,
171                            true,
172                            completion,
173                            "",
174                            RequiredType.NONE,
175                            CommandCategory.ADMINISTRATION
176                    ) {
177                    }).collect(Collectors.toCollection(LinkedList::new));
178            if (player.hasPermission(Permission.PERMISSION_DOWNLOAD) && args[0].length() > 0) {
179                commands.addAll(TabCompletions.completePlayers(player, args[0], Collections.emptyList()));
180            }
181            return commands;
182        }
183        return TabCompletions.completePlayers(player, String.join(",", args).trim(), Collections.emptyList());
184    }
185
186    private void upload(PlotPlayer<?> player, Plot plot) {
187        if (Settings.Web.LEGACY_WEBINTERFACE) {
188            schematicHandler
189                    .getCompoundTag(plot)
190                    .whenComplete((compoundTag, throwable) -> schematicHandler.upload(
191                            compoundTag,
192                            null,
193                            null,
194                            new RunnableVal<>() {
195                                @Override
196                                public void run(URL value) {
197                                    plot.removeRunning();
198                                    player.sendMessage(
199                                            TranslatableCaption.of("web.generation_link_success"),
200                                            TagResolver.builder()
201                                                    .tag("download", Tag.preProcessParsed(value.toString()))
202                                                    .tag("delete", Tag.preProcessParsed("Not available"))
203                                                    .build()
204                                    );
205                                    player.sendMessage(StaticCaption.of(value.toString()));
206                                }
207                            }
208                    ));
209            return;
210        }
211        // TODO legacy support
212        this.plotUploader.upload(plot)
213                .whenComplete((result, throwable) -> {
214                    if (throwable != null || !result.isSuccess()) {
215                        player.sendMessage(
216                                TranslatableCaption.of("web.generating_link_failed"),
217                                TagResolver.resolver("plot", Tag.inserting(Component.text(plot.getId().toString())))
218                        );
219                    } else {
220                        player.sendMessage(
221                                TranslatableCaption.of("web.generation_link_success"),
222                                TagResolver.builder()
223                                        .tag("download", Tag.preProcessParsed(result.getDownloadUrl()))
224                                        .tag("delete", Tag.preProcessParsed(result.getDeletionUrl()))
225                                        .build()
226                        );
227                    }
228                });
229    }
230
231}