• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

patrickfav / rocketchat-exporter / 43

pending completion
43

push

travis-ci-com

web-flow
Merge pull request #6 from iweiss/master

21 of 21 new or added lines in 3 files covered. (100.0%)

142 of 322 relevant lines covered (44.1%)

0.44 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/main/java/at/favre/tools/rocketexporter/cli/Export.java
1
package at.favre.tools.rocketexporter.cli;
2

3
import at.favre.tools.rocketexporter.Config;
4
import at.favre.tools.rocketexporter.RocketExporter;
5
import at.favre.tools.rocketexporter.TooManyRequestException;
6
import at.favre.tools.rocketexporter.converter.ExportFormat;
7
import at.favre.tools.rocketexporter.converter.SlackCsvFormat;
8
import at.favre.tools.rocketexporter.dto.Conversation;
9
import at.favre.tools.rocketexporter.dto.LoginDto;
10
import at.favre.tools.rocketexporter.dto.LoginResponseDto;
11
import at.favre.tools.rocketexporter.dto.TokenDto;
12
import at.favre.tools.rocketexporter.model.Message;
13
import picocli.CommandLine;
14

15
import java.io.File;
16
import java.io.PrintStream;
17
import java.net.URL;
18
import java.time.Instant;
19
import java.time.ZoneId;
20
import java.time.format.DateTimeFormatter;
21
import java.util.*;
22
import java.util.stream.Collectors;
23

24
@CommandLine.Command(description = "Exports rocket chat messages from a specific group/channel.",
25
        name = "export", mixinStandardHelpOptions = true, version = "1.0")
26
class Export implements Runnable {
×
27

28
    @CommandLine.Option(names = {"-o", "--outFile"}, description = "The file or directory to write the export data to. Will write to current directory with auto generated filename if this arg is omitted. If you want to export multiple conversations you must pass a directory not a file.")
29
    private File file;
30

31
    @CommandLine.Option(names = {"-t", "--host"}, required = true, description = "The rocket chat server. E.g. 'https://myserver.com'")
32
    private URL host;
33

34
    @CommandLine.Option(names = {"-u", "--user"}, required = false, description = "RocketChat username for authentication.")
35
    private String username;
36

37
    @CommandLine.Option(names = {"-k", "--user-id"}, required = true, description = "RocketChat Personal Access Token user ID.")
38
    private String userId;
39

40
    @CommandLine.Option(names = {"--debug"}, description = "Add debug log output to STDOUT.")
41
    private boolean debug;
42

43
    @CommandLine.Option(names = {"-m", "--maxMsg"}, description = "How many messages should be exported.")
×
44
    private int maxMessages = 25000;
45

46
    public static void main(String[] args) {
47
        int exitCode = new CommandLine(new Export())
×
48
                .setCaseInsensitiveEnumValuesAllowed(true).execute(args);
×
49
        System.exit(exitCode);
×
50
    }
×
51

52
    @Override
53
    public void run() {
54
        PrintStream out = System.out;
×
55

56
        if (username == null && userId == null) {
×
57
            out.println("You have to use a username or a token user ID to continue.");
×
58
            System.exit(-1);
×
59
        }
60

61
        out.println("Please enter your RocketChat password or token:");
×
62

63
        String password;
64
        if (System.console() != null) {
×
65
            password = String.valueOf(System.console().readPassword());
×
66
        } else {
67
            password = new Scanner(System.in).next();
×
68
        }
69

70
        try {
71
            RocketExporter exporter = RocketExporter.newInstance(
×
72
                    Config.builder()
×
73
                            .host(host.toURI())
×
74
                            .httpDebugOutput(debug)
×
75
                            .build());
×
76

77
            LoginResponseDto loginResponse;
78
            if (username != null && !username.isEmpty()) {
×
79
                loginResponse = exporter.login(new LoginDto(username, password));
×
80
            } else {
81
                loginResponse = exporter.tokenAuth(new TokenDto(userId, password));
×
82
            }
83

84
            out.println("Authentication successful (" + username + " or " + userId + ").");
×
85

86
            CliOptionChooser typeChooser =
×
87
                    new CliOptionChooser(System.in, out,
88
                            List.of(
×
89
                                    RocketExporter.ConversationType.GROUP.name,
90
                                    RocketExporter.ConversationType.CHANNEL.name,
91
                                    RocketExporter.ConversationType.DIRECT_MESSAGES.name),
92
                            "\nWhat type do you want to export:");
93

94
            ArrayList<Conversation> conversations = new ArrayList<>();
×
95
            RocketExporter.ConversationType type = RocketExporter.ConversationType.of(typeChooser.prompt());
×
96

97
            switch (type) {
×
98
                case GROUP:
99
                    conversations.addAll(exporter.listGroups());
×
100
                    break;
×
101
                case CHANNEL:
102
                    conversations.addAll(exporter.listChannels());
×
103
                    break;
×
104
                case DIRECT_MESSAGES:
105
                    conversations.addAll(exporter.listDirectMessageChannels());
×
106
                    break;
×
107
                default:
108
                    throw new IllegalStateException();
×
109
            }
110

111
            List<Conversation> conversationSelection = new ArrayList<>();
×
112
            conversationSelection.add(new Conversation.AllConversations());
×
113

114
            List<Conversation> allConversations = conversations.stream()
×
115
                    .filter(Objects::nonNull)
×
116
                    .sorted(Comparator.comparing(Conversation::getName))
×
117
                    .collect(Collectors.toList());
×
118

119
            conversationSelection.addAll(allConversations);
×
120

121
            if (allConversations.size() == 0) {
×
122
                out.println("Nothing found to export.");
×
123
                return;
×
124
            }
125

126
            CliOptionChooser cliOptionChooser =
×
127
                    new CliOptionChooser(System.in, out,
128
                            conversationSelection.stream().map(Conversation::getName).collect(Collectors.toList()),
×
129
                            "\nPlease choose the " + type.name + " you want to export:");
130

131
            int selection = cliOptionChooser.prompt();
×
132
            List<Conversation> toExport = new ArrayList<>();
×
133

134
            if (selection == 0) {
×
135
                toExport.addAll(allConversations);
×
136
            } else {
137
                toExport.add(allConversations.get(selection));
×
138
            }
139

140
            for (int i = 0; i < toExport.size(); i++) {
×
141
                Conversation selectedGroup = toExport.get(i);
×
142

143
                final List<Message> messages;
144
                final ExportFormat format = new SlackCsvFormat();
×
145
                final int offset = 0;
×
146
                final int maxMsg = maxMessages;
×
147
                final File outFile = generateOutputFile(file, selectedGroup.getName(), type, format);
×
148

149
                try {
150
                    switch (type) {
×
151
                        case GROUP:
152
                            messages = exporter.exportPrivateGroupMessages(selectedGroup.getName(), selectedGroup.get_id(), offset, maxMsg, outFile, format);
×
153
                            break;
×
154
                        case CHANNEL:
155
                            messages = exporter.exportChannelMessages(selectedGroup.getName(), selectedGroup.get_id(), offset, maxMsg, outFile, format);
×
156
                            break;
×
157
                        case DIRECT_MESSAGES:
158
                            messages = exporter.exportDirectMessages(selectedGroup.getName(), selectedGroup.get_id(), offset, maxMsg, outFile, format);
×
159
                            break;
×
160
                        default:
161
                            throw new IllegalStateException();
×
162
                    }
163

164
                    out.println("Successfully exported " + messages.size() + " " + type.name + " messages to '" + outFile + "'");
×
165
                } catch (TooManyRequestException e) {
×
166
                    out.println("Too many requests. Slowing down...");
×
167
                    Thread.sleep(5000);
×
168
                    i--;
×
169
                }
×
170
            }
171
        } catch (Exception e) {
×
172
            throw new RuntimeException(e);
×
173
        }
×
174
    }
×
175

176
    private File generateOutputFile(File provided, String contextName, RocketExporter.ConversationType type, ExportFormat format) {
177
        if (provided == null) {
×
178
            provided = new File("./");
×
179
        }
180

181
        if (!provided.exists()) {
×
182
            provided.mkdirs();
×
183
        }
184

185
        if (provided.isDirectory()) {
×
186
            String filename = type.name.replaceAll(" ", "-") + "_" + contextName + "_" + DateTimeFormatter
×
187
                    .ofPattern("yyyyMMddHHmmss")
×
188
                    .withZone(ZoneId.of("UTC"))
×
189
                    .format(Instant.now()) + "." + format.fileExtension();
×
190
            return new File(provided, filename);
×
191
        } else {
192
            return provided;
×
193
        }
194
    }
195
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2023 Coveralls, Inc