aboutsummaryrefslogtreecommitdiff
path: root/src/com/cyanogenmod/filemanager/commands/shell/CompressCommand.java
blob: 54e8131554af59b2b1e1b2c0ff64c7e3564fed13 (plain)
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
/*
 * Copyright (C) 2012 The CyanogenMod Project
 *
 * 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 com.cyanogenmod.filemanager.commands.shell;

import com.cyanogenmod.filemanager.commands.AsyncResultListener;
import com.cyanogenmod.filemanager.commands.CompressExecutable;
import com.cyanogenmod.filemanager.commands.SIGNAL;
import com.cyanogenmod.filemanager.console.CommandNotFoundException;
import com.cyanogenmod.filemanager.console.ExecutionException;
import com.cyanogenmod.filemanager.console.InsufficientPermissionsException;
import com.cyanogenmod.filemanager.preferences.CompressionMode;
import com.cyanogenmod.filemanager.util.FileHelper;

import java.io.File;

/**
 * A class for compress file system objects
 *
 * {@link "http://unixhelp.ed.ac.uk/CGI/man-cgi?tar"}
 * {@link "http://unixhelp.ed.ac.uk/CGI/man-cgi?gzip"}
 * {@link "http://unixhelp.ed.ac.uk/CGI/man-cgi?bzip2"}
 */
public class CompressCommand extends AsyncResultProgram implements CompressExecutable {

    /**
     * An enumeration of implemented compression modes.
     */
    private enum Mode {
        /**
         * Archive using Tar algorithm
         */
        A_TAR(TAR_ID, "", CompressionMode.A_TAR), //$NON-NLS-1$
        /**
         * Archive and compress using Gzip algorithm
         */
        AC_GZIP(TAR_ID, "z", CompressionMode.AC_GZIP), //$NON-NLS-1$
        /**
         * Archive and compress using Gzip algorithm
         */
        AC_GZIP2(TAR_ID, "z", CompressionMode.AC_GZIP2), //$NON-NLS-1$
        /**
         * Archive and compress using Bzip algorithm
         */
        AC_BZIP(TAR_ID, "j", CompressionMode.AC_BZIP), //$NON-NLS-1$
        /**
         * Compress using Gzip algorithm
         */
        C_GZIP(GZIP_ID, "z", CompressionMode.C_GZIP), //$NON-NLS-1$
        /**
         * Compress using Bzip algorithm
         */
        C_BZIP(BZIP_ID, "j", CompressionMode.C_BZIP), //$NON-NLS-1$
        /**
         * Archive using Zip algorithm
         */
        A_ZIP(ZIP_ID, "", CompressionMode.A_ZIP); //$NON-NLS-1$

        final String mId;
        final String mFlag;
        final CompressionMode mMode;

        /**
         * Constructor of <code>Mode</code>
         *
         * @param id The command identifier
         * @param flag The tar compression flag
         * @param mode The compression mode
         */
        private Mode(String id, String flag, CompressionMode mode) {
            this.mId = id;
            this.mFlag = flag;
            this.mMode = mode;
        }

        /**
         * Method that return the mode from his compression mode
         *
         * @param mode The compression mode
         * @return Mode The mode
         */
        public static Mode fromCompressionMode(CompressionMode mode) {
            Mode[] modes = Mode.values();
            int cc = modes.length;
            for (int i = 0; i < cc; i++) {
                if (modes[i].mMode.compareTo(mode) == 0) {
                    return modes[i];
                }
            }
            return null;
        }
    }

    private static final String TAR_ID = "tar"; //$NON-NLS-1$
    private static final String GZIP_ID = "gzip"; //$NON-NLS-1$
    private static final String BZIP_ID = "bzip"; //$NON-NLS-1$
    private static final String ZIP_ID = "zip"; //$NON-NLS-1$

    private Boolean mResult;
    private String mPartial;

    private final Mode mMode;
    private final String mOutFile;

    /**
     * Constructor of <code>CompressCommand</code>. This method creates an archive-compressed
     * file from one or various file system objects.
     *
     * @param mode The compression mode
     * @param dst The absolute path of the new compress file
     * @param src An array of file system objects to compress
     * @param asyncResultListener The partial result listener
     * @throws InvalidCommandDefinitionException If the command has an invalid definition
     */
    public CompressCommand(
            CompressionMode mode, String dst, String[] src, AsyncResultListener asyncResultListener)
            throws InvalidCommandDefinitionException {
        super(Mode.fromCompressionMode(mode).mId,
              asyncResultListener,
              resolveArchiveArgs(Mode.fromCompressionMode(mode), dst));
        this.mMode = Mode.fromCompressionMode(mode);

        if (!this.mMode.mMode.mArchive) {
            throw new InvalidCommandDefinitionException(
                            "Unsupported archive mode"); //$NON-NLS-1$
        }

        //Convert the arguments from absolute to relative
        addExpandedArguments(
                convertAbsolutePathsToRelativePaths(dst, src), true);

        // Create the output file
        this.mOutFile = dst;
    }

    /**
     * Constructor of <code>CompressCommand</code>. This method creates a compressed
     * file from one file.
     *
     * @param mode The compression mode
     * @param src The file to compress
     * @param asyncResultListener The partial result listener
     * @throws InvalidCommandDefinitionException If the command has an invalid definition
     */
    public CompressCommand(
            CompressionMode mode, String src, AsyncResultListener asyncResultListener)
            throws InvalidCommandDefinitionException {
        super(Mode.fromCompressionMode(mode).mId,
              asyncResultListener,
              resolveCompressArgs(mode, src));
        this.mMode = Mode.fromCompressionMode(mode);

        if (this.mMode.mMode.mArchive) {
            throw new InvalidCommandDefinitionException(
                            "Unsupported compression mode"); //$NON-NLS-1$
        }

        // Create the output file
        this.mOutFile = resolveOutputFile(mode, src);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onStartParsePartialResult() {
        this.mResult = Boolean.FALSE;
        this.mPartial = ""; //$NON-NLS-1$
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onEndParsePartialResult(boolean cancelled) {
        // Send the last partial data
        if (this.mPartial != null && this.mPartial.length() > 0) {
            if (getAsyncResultListener() != null) {
                String data = processPartialResult(this.mPartial);
                if (data != null) {
                    getAsyncResultListener().onPartialResult(data);
                }
            }
        }
        this.mPartial = ""; //$NON-NLS-1$
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onParsePartialResult(final byte[] in) {
        String partialIn = new String(in);
        if (partialIn == null || partialIn.length() ==0) return;
        boolean endsWithNewLine = partialIn.endsWith("\n"); //$NON-NLS-1$
        String[] lines = partialIn.split("\n"); //$NON-NLS-1$

        // Append the pending data to the first line
        lines[0] = this.mPartial + lines[0];

        // Return all the lines, except the last
        int cc = lines.length;
        for (int i = 0; i < cc-1; i++) {
            if (getAsyncResultListener() != null) {
                String data = processPartialResult(lines[i]);
                if (data != null) {
                    getAsyncResultListener().onPartialResult(data);
                }
            }
        }

        // Return the last line?
        if (endsWithNewLine) {
            if (getAsyncResultListener() != null) {
                String data = processPartialResult(lines[lines.length-1]);
                if (data != null) {
                    getAsyncResultListener().onPartialResult(data);
                }
            }
            this.mPartial = ""; //$NON-NLS-1$
        } else {
            // Save the partial for next calls
            this.mPartial = lines[lines.length-1];
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onParseErrorPartialResult(byte[] partialErr) {/**NON BLOCK**/}

    /**
     * {@inheritDoc}
     */
    @Override
    public SIGNAL onRequestEnd() {
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Boolean getResult() {
        return this.mResult;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void checkExitCode(int exitCode)
            throws InsufficientPermissionsException, CommandNotFoundException, ExecutionException {

        //Ignore exit code 143 (cancelled)
        //Ignore exit code 137 (kill -9)
        if (exitCode != 0 && exitCode != 1 && exitCode != 143 && exitCode != 137) {
            throw new ExecutionException(
                        "exitcode != 0 && != 143 && != 137"); //$NON-NLS-1$
        }

        // Correct
        this.mResult = Boolean.TRUE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getOutCompressedFile() {
        return this.mOutFile;
    }

    /**
     * Method that resolves the arguments for the archive mode
     *
     * @return String[] The arguments
     */
    private final static String[] resolveArchiveArgs(Mode mode, String dst) {
        if (mode.compareTo(Mode.A_ZIP) == 0) {
            return new String[]{
                    FileHelper.getParentDir(dst),
                    dst
                };
        }
        return new String[]{
                FileHelper.getParentDir(dst),
                mode.mFlag,
                dst
            };
    }

    /**
     * Method that resolves the arguments for the compression mode
     *
     * @return String[] The arguments
     */
    private static String[] resolveCompressArgs(CompressionMode mode, String src) {
        switch (mode) {
            case C_GZIP:
            case C_BZIP:
                return new String[]{src};
            default:
                return new String[]{};
        }
    }

    /**
     * Method that processes a line to determine if it's a valid partial result
     *
     * @param line The line to process
     * @return String The processed line
     */
    private String processPartialResult(String line) {
        if (this.mMode.compareTo(Mode.A_ZIP) == 0) {
            if (line.startsWith("  adding: ")) { //$NON-NLS-1$
                int pos = line.lastIndexOf('(');
                if (pos != -1) {
                    // Remove progress
                    return line.substring(10, pos).trim();
                }
                return line.substring(10).trim();
            }
            return null;
        }
        return line;
    }

    /**
     * Method that resolves the output path of the compressed file
     *
     * @return String The output path of the compressed file
     */
    private static String resolveOutputFile(CompressionMode mode, String src) {
        return String.format("%s.%s", src, mode.mExtension); //$NON-NLS-1$
    }

    /**
     * Method that converts the absolute paths of the source files to relative paths
     *
     * @param dst The destination compressed file
     * @param src The source uncompressed files
     * @return String[] The array of relative paths
     */
    private static String[] convertAbsolutePathsToRelativePaths(String dst, String[] src) {
        File parent  = new File(dst).getParentFile();
        String p = File.separator;
        if (parent != null) {
            p = parent.getAbsolutePath();
        }

        // Converts every path
        String[] out = new String[src.length];
        int cc = src.length;
        for (int i = 0; i < cc; i++) {
            out[i] = FileHelper.toRelativePath(src[i], p);
        }
        return out;
    }
}