-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImageUploadExecutor.java
More file actions
199 lines (170 loc) · 6.68 KB
/
ImageUploadExecutor.java
File metadata and controls
199 lines (170 loc) · 6.68 KB
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
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.util.Log;
import android.util.Pair;
import android.webkit.MimeTypeMap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import id.zelory.compressor.Compressor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
public class ImageUploadExecutor {
private static final String TAG = ImageUploadExecutor.class.getName();
public static final int MAX_SIZE = 1024;
public static final int QUALITY = 60;
private final Executor background;
private final Executor foreground;
private final IApiRequest api;
private final List<OnImagesUploadedListener> listeners;
public ImageUploadExecutor(IApiRequest api) {
this(api, new UIExecutor(), Executors.newSingleThreadExecutor());
}
public ImageUploadExecutor(IApiRequest api, Executor foreground, Executor background) {
this.api = api;
this.foreground = foreground;
this.background = background;
listeners = Collections.synchronizedList(new ArrayList<OnImagesUploadedListener>());
}
public void addOnImagesUploadedListener(OnImagesUploadedListener listener) {
listeners.add(listener);
}
public void removeOnImagesUploadedListener(OnImagesUploadedListener listener) {
listeners.remove(listener);
}
public void removeAllOnImagesUploadedListener() {
listeners.clear();
}
private void executeOnUI(Runnable runnable) {
foreground.execute(runnable);
}
public Pair<String, String> getFileName(Context context, Uri uri) {
String prefix = String.valueOf(System.currentTimeMillis() % 10000000);
String suffix = getFileExtension(context, uri);
return new Pair<>(prefix, suffix);
}
public String getFileExtension(Context context, Uri uri) {
String extension;
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
final MimeTypeMap mime = MimeTypeMap.getSingleton();
extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
} else {
extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
}
return extension;
}
private File createTemporaryFile(Context context, Uri uri) {
OutputStream outputStream = null;
try(InputStream inputStream = context.getContentResolver().openInputStream(uri)) {
Pair<String, String> fileName = getFileName(context, uri);
File file = File.createTempFile(fileName.first, fileName.second, context.getCacheDir());
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
outputStream.write(buffer);
return new Compressor(context)
.setMaxHeight(MAX_SIZE)
.setMaxWidth(MAX_SIZE)
.setQuality(QUALITY)
.setCompressFormat(Bitmap.CompressFormat.PNG)
.compressToFile(file);
} catch (IOException e) {
Logger.e(TAG, e.getMessage());
return null;
} finally {
if (outputStream != null) try {
outputStream.close();
outputStream.flush();
} catch (IOException e) {
Logger.e(TAG, e.getMessage());
}
}
}
private PhotoEntity uploadPhoto(Context context, Uri uri) throws IOException {
File file = createTemporaryFile(context, uri);
if (file == null) {
throw new IOException("Temporary file creation failed");
}
// creating multipart file
ContentResolver resolver = context.getContentResolver();
MediaType fileType = MediaType.parse(resolver.getType(uri));
RequestBody requestFile = RequestBody.create(fileType, file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body = MultipartBody.Part.createFormData(
"file",
file.getName(),
requestFile
);
try {
return api.uploadFile(body).execute().body();
} finally {
file.delete();
}
}
private PhotoEntity[] uploadPhotosToServer(Context context, Uri... uris) throws IOException {
final List<PhotoEntity> idList = new ArrayList<>();
for (Uri uri : uris) {
PhotoEntity entity = uploadPhoto(context, uri);
if (entity != null) {
idList.add(entity);
}
}
return idList.toArray(new PhotoEntity[idList.size()]);
}
public void uploadImages(final Context context, final Uri... uris) {
background.execute(new Runnable() {
@Override
public void run() {
try {
final PhotoEntity[] uploadedPhotos = uploadPhotosToServer(context, uris);
executeOnUI(new Runnable() {
@Override
public void run() {
for (OnImagesUploadedListener listener : listeners) {
listener.onImagesUploaded(uploadedPhotos);
}
}
});
} catch (final IOException e) {
Logger.e(TAG, e.getMessage());
executeOnUI(new Runnable() {
@Override
public void run() {
for (OnImagesUploadedListener listener : listeners) {
listener.onUploadingError(e);
}
}
});
}
}
});
}
static class UIExecutor implements Executor {
final Handler uiHandler;
UIExecutor() {
uiHandler = new Handler(Looper.getMainLooper());
}
@Override
public void execute(@NonNull Runnable command) {
uiHandler.post(command);
}
}
public interface OnImagesUploadedListener {
void onImagesUploaded(PhotoEntity... ids);
void onUploadingError(Throwable t);
}
}