Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ChunkedFileUploadRemoteOperation.java « files « resources « lib « android « owncloud « com « java « main « src « library - github.com/nextcloud/android-library.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 227d330116d1b636d6d29547c889c27474a80d68 (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
/* ownCloud Android Library is available under MIT license
 *   Copyright (C) 2015 ownCloud Inc.
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a copy
 *   of this software and associated documentation files (the "Software"), to deal
 *   in the Software without restriction, including without limitation the rights
 *   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *   copies of the Software, and to permit persons to whom the Software is
 *   furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 *   BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 *   ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 *   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *   THE SOFTWARE.
 *
 */

package com.owncloud.android.lib.resources.files;

import androidx.annotation.VisibleForTesting;

import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.network.ChunkFromFileChannelRequestEntity;
import com.owncloud.android.lib.common.network.ProgressiveDataTransfer;
import com.owncloud.android.lib.common.network.WebdavEntry;
import com.owncloud.android.lib.common.network.WebdavUtils;
import com.owncloud.android.lib.common.operations.OperationCancelledException;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.jackrabbit.webdav.DavConstants;
import org.apache.jackrabbit.webdav.MultiStatus;
import org.apache.jackrabbit.webdav.MultiStatusResponse;
import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
import org.apache.jackrabbit.webdav.client.methods.MoveMethod;
import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


public class ChunkedFileUploadRemoteOperation extends UploadFileRemoteOperation {

    public static final long CHUNK_SIZE_MOBILE = 1024000;
    public static final long CHUNK_SIZE_WIFI = 10240000;
    private static final String TAG = ChunkedFileUploadRemoteOperation.class.getSimpleName();
    private final boolean onWifiConnection;

    public final int ASSEMBLE_TIME_MIN = 30 * 1000; // 30s
    public final int ASSEMBLE_TIME_MAX = 30 * 60 * 1000; // 30min
    public final int ASSEMBLE_TIME_PER_GB = 3 * 60 * 1000; // 3 min

    public ChunkedFileUploadRemoteOperation(String storagePath,
                                            String remotePath,
                                            String mimeType,
                                            String requiredEtag,
                                            String lastModificationTimestamp,
                                            boolean onWifiConnection) {
        this(storagePath, remotePath, mimeType, requiredEtag, lastModificationTimestamp, onWifiConnection, null);
    }

    public ChunkedFileUploadRemoteOperation(String storagePath,
                                            String remotePath,
                                            String mimeType,
                                            String requiredEtag,
                                            String lastModificationTimestamp,
                                            Long creationTimestamp,
                                            boolean onWifiConnection,
                                            boolean disableRetries) {
        this(storagePath,
                remotePath,
                mimeType,
                requiredEtag,
                lastModificationTimestamp,
                onWifiConnection,
                null,
                creationTimestamp,
                disableRetries);
    }

    public ChunkedFileUploadRemoteOperation(String storagePath,
                                            String remotePath,
                                            String mimeType,
                                            String requiredEtag,
                                            String lastModificationTimestamp,
                                            boolean onWifiConnection,
                                            String token) {
        this(storagePath,
                remotePath,
                mimeType,
                requiredEtag,
                lastModificationTimestamp,
                onWifiConnection,
                token,
                null,
                true);
    }

    public ChunkedFileUploadRemoteOperation(String storagePath,
                                            String remotePath,
                                            String mimeType,
                                            String requiredEtag,
                                            String lastModificationTimestamp,
                                            boolean onWifiConnection,
                                            String token,
                                            Long creationTimestamp,
                                            boolean disableRetries) {
        super(storagePath,
                remotePath,
                mimeType,
                requiredEtag,
                lastModificationTimestamp,
                creationTimestamp,
                token,
                disableRetries);
        this.onWifiConnection = onWifiConnection;
    }

    @Override
    protected RemoteOperationResult run(OwnCloudClient client) {
        RemoteOperationResult result;
        DefaultHttpMethodRetryHandler oldRetryHandler = (DefaultHttpMethodRetryHandler) 
                client.getParams().getParameter(HttpMethodParams.RETRY_HANDLER);
        File file = new File(localPath);
        MoveMethod moveMethod = null;
        try {
            if (disableRetries) {
                // prevent that uploads are retried automatically by network library
                client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                                                new DefaultHttpMethodRetryHandler(0, false));
            }

            String uploadFolderUri = client.getUploadUri() + "/" + client.getUserId() + "/" + FileUtils.md5Sum(file);

            // create folder
            MkColMethod createFolder = new MkColMethod(uploadFolderUri);

            client.executeMethod(createFolder, 30000, 5000);
            
            // list chunks
            PropFindMethod listChunks = new PropFindMethod(uploadFolderUri,
                    WebdavUtils.getChunksPropSet(),
                                                           DavConstants.DEPTH_1);

            client.executeMethod(listChunks);
            
            if (!listChunks.succeeded()) {
                return new RemoteOperationResult(listChunks.succeeded(), listChunks);
            }
            
            List<Chunk> chunksOnServer = new ArrayList<>();

            MultiStatus dataInServer = listChunks.getResponseBodyAsMultiStatus();

            WebdavEntry we;
            for (MultiStatusResponse response : dataInServer.getResponses()) {
                we = new WebdavEntry(response, client.getUploadUri().getPath());

                if (!".file".equalsIgnoreCase(we.getName()) && !we.isDirectory()) {
                    String[] part = we.getName().split("-");
                    chunksOnServer.add(new Chunk(Long.parseLong(part[0]), Long.parseLong(part[1])));
                }
            }

            // chunk length
            long chunkSize;
            if (onWifiConnection) {
                chunkSize = CHUNK_SIZE_WIFI;
            } else {
                chunkSize = CHUNK_SIZE_MOBILE;
            }

            // check for missing chunks
            List<Chunk> missingChunks = checkMissingChunks(chunksOnServer, file.length(), chunkSize);

            // upload chunks
            for (Chunk missingChunk : missingChunks) {
                RemoteOperationResult chunkResult = uploadChunk(client, uploadFolderUri, missingChunk);
                
                if (!chunkResult.isSuccess()) {
                    return chunkResult;
                }

                if (cancellationRequested.get()) {
                    return new RemoteOperationResult(new OperationCancelledException());
                }
            }

            // assemble
            String destinationUri = client.getDavUri() + "/files/" + client.getUserId() +
                    WebdavUtils.encodePath(remotePath);
            String originUri = uploadFolderUri + "/.file";

            moveMethod = new MoveMethod(originUri, destinationUri, true);
            moveMethod.addRequestHeader(OC_X_OC_MTIME_HEADER, String.valueOf(file.lastModified() / 1000));

            if (creationTimestamp != null && creationTimestamp > 0) {
                moveMethod.addRequestHeader(OC_X_OC_CTIME_HEADER, String.valueOf(creationTimestamp));
            }

            if (token != null) {
                moveMethod.addRequestHeader(E2E_TOKEN, token);
            }

            final int DO_NOT_CHANGE_DEFAULT = -1;
            int moveResult = client.executeMethod(moveMethod, calculateAssembleTimeout(file), DO_NOT_CHANGE_DEFAULT);

            result = new RemoteOperationResult(isSuccess(moveResult), moveMethod);
        } catch (Exception e) {
            if (moveMethod != null && moveMethod.isAborted()) {
                if (cancellationRequested.get() && cancellationReason != null) {
                    result = new RemoteOperationResult(cancellationReason);
                } else {
                    result = new RemoteOperationResult(new OperationCancelledException());
                }
            } else {
                result = new RemoteOperationResult(e);
            }
        } finally {
            if (disableRetries) {
                // reset previous retry handler
                client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, oldRetryHandler);
            }
        }
        return result;
    }

    List<Chunk> checkMissingChunks(List<Chunk> chunks, long length, long chunkSize) {
        List<Chunk> missingChunks = new ArrayList<>();

        long start = 0;

        while (start <= length) {
            Chunk nextChunk = findNextFittingChunk(chunks, start, chunkSize);

            if (nextChunk == null) {
                // create new chunk
                long end;

                if (start + chunkSize <= length) {
                    end = start + chunkSize - 1;
                } else {
                    end = length;
                }

                missingChunks.add(new Chunk(start, end));
                start = end + 1;
            } else if (nextChunk.start == start) {
                // go to next
                start = start + nextChunk.length();
            } else {
                // fill the gap
                missingChunks.add(new Chunk(start, nextChunk.start - 1));
                start = nextChunk.start;
            }
        }

        return missingChunks;
    }

    private Chunk findNextFittingChunk(List<Chunk> chunks, long start, long length) {
        for (Chunk chunk : chunks) {
            if (chunk.start >= start && (chunk.start - start) <= length) {
                return chunk;
            }
        }
        return null;
    }

    private RemoteOperationResult uploadChunk(OwnCloudClient client, String uploadFolderUri, Chunk chunk)
            throws IOException {
        int status;
        RemoteOperationResult result;

        String startString = String.format(Locale.ROOT, "%016d", chunk.start);
        String endString = String.format(Locale.ROOT, "%016d", chunk.end);

        FileChannel channel = null;
        RandomAccessFile raf = null;

        File file = new File(localPath);

        try {
            raf = new RandomAccessFile(file, "r");
            channel = raf.getChannel();
            entity = new ChunkFromFileChannelRequestEntity(channel, mimeType, chunk.start, chunk.length(), file);
            
            synchronized (dataTransferListeners) {
                ((ProgressiveDataTransfer) entity).addDataTransferProgressListeners(dataTransferListeners);
            }

            String chunkUri = uploadFolderUri + "/" + startString + "-" + endString;

            if (putMethod != null) {
                putMethod.releaseConnection(); // let the connection available for other methods
            }

            putMethod = createPutMethod(chunkUri);

            if (token != null) {
                putMethod.addRequestHeader(E2E_TOKEN, token);
            }

            status = client.executeMethod(putMethod);

            result = new RemoteOperationResult(isSuccess(status), putMethod);

            client.exhaustResponse(putMethod.getResponseBodyAsStream());
            Log_OC.d(TAG, "Upload of " + localPath + " to " + remotePath + ", chunk from " + startString + " to " +
                    endString + " size: "  + chunk.length() + ", HTTP result status " + status);
        } finally {
            if (channel != null)
                try {
                    channel.close();
                } catch (IOException e) {
                    Log_OC.e(TAG, "Error closing file channel!", e);
                }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    Log_OC.e(TAG, "Error closing file access!", e);
                }
            }
            if (putMethod != null)
                putMethod.releaseConnection(); // let the connection available for other methods
        }
        return result;
    }

    private PutMethod createPutMethod(String uriPrefix) {
        putMethod = new PutMethod(uriPrefix);
        putMethod.setRequestEntity(entity);
        if (cancellationRequested.get()) {
            putMethod.abort(); // next method will throw an exception
        }

        return putMethod;
    }

    @VisibleForTesting
    public int calculateAssembleTimeout(File file) {
        final double fileSizeInGb = file.length() / 1e9;

        return Math.max(ASSEMBLE_TIME_MIN, Math.min((int) (ASSEMBLE_TIME_PER_GB * fileSizeInGb), ASSEMBLE_TIME_MAX));
    }
}