-
Notifications
You must be signed in to change notification settings - Fork 43
/
MainActivity.java
368 lines (320 loc) · 15.6 KB
/
MainActivity.java
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
/*
* Piwigo for Android
* Copyright (C) 2016-2017 Piwigo Team http://piwigo.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.piwigo.ui.main;
import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import org.piwigo.R;
import org.piwigo.databinding.ActivityMainBinding;
import org.piwigo.databinding.DrawerHeaderBinding;
import org.piwigo.helper.CommonVars;
import org.piwigo.io.RestService;
import org.piwigo.io.model.ImageUploadResponse;
import org.piwigo.ui.about.AboutActivity;
import org.piwigo.ui.account.ManageAccountsActivity;
import org.piwigo.ui.shared.BaseActivity;
import org.piwigo.io.RestServiceFactory;
import org.piwigo.accounts.UserManager;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import javax.inject.Inject;
import javax.inject.Provider;
import dagger.android.AndroidInjection;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.HasSupportFragmentInjector;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends BaseActivity implements HasSupportFragmentInjector {
@Inject DispatchingAndroidInjector<Fragment> fragmentInjector;
@Inject MainViewModelFactory viewModelFactory;
@Inject RestServiceFactory restServiceFactory;
private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 184;
CommonVars comvars = CommonVars.getInstance();
int SELECT_PICTURES = 1;
@Override protected void onCreate(Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
DrawerHeaderBinding headerBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.drawer_header, binding.navigationView, false);
MainViewModel viewModel = ViewModelProviders.of(this, viewModelFactory).get(MainViewModel.class);
viewModel.getSelectedNavigationItemId().observe(this, this::itemSelected);
binding.setViewModel(viewModel);
headerBinding.setViewModel(viewModel);
binding.navigationView.addHeaderView(headerBinding.getRoot());
setSupportActionBar(binding.toolbar);
final Observer<Account> accountObserver = account -> {
// reload the albums on account changes
if(account != null) {
viewModel.username.set(userManager.getUsername(account));
viewModel.url.set(userManager.getSiteUrl(account));
}else{
viewModel.username.set("");
viewModel.url.set("");
}
};
userManager.getActiveAccount().observe(this, accountObserver);
if (savedInstanceState == null) {
viewModel.setTitle(getString(R.string.nav_albums));
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, new AlbumsFragment())
.commit();
}
}
@Override protected void onResume() {
super.onResume();
MainViewModel viewModel = ViewModelProviders.of(this, viewModelFactory).get(MainViewModel.class);
viewModel.navigationItemId.set(R.id.nav_albums);
}
@Override public AndroidInjector<Fragment> supportFragmentInjector() {
return fragmentInjector;
}
private void itemSelected(int itemId) {
switch (itemId) {
case R.id.nav_albums:
comvars.setCurrAlbum(0);
Toast.makeText(this,"reset to main album",Toast.LENGTH_LONG).show();
break;
case R.id.nav_manage_accounts:
startActivity(new Intent(getApplicationContext(),
ManageAccountsActivity.class));
break;
case R.id.nav_upload:
// Here, thisActivity is the current activity
/* TODO: check whether we really need the permission unconditionally
* I (ramack) could imagine, that we don't need it depending on the media chooser... */
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
// if (ActivityCompat.shouldShowRequestPermissionRationale(this,
// Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
// } else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
// }
} else {
// Permission has already been granted
selectPhoto();
}
break;
case R.id.nav_about:
startActivity(new Intent(getApplicationContext(),
AboutActivity.class));
break;
default:
Toast.makeText(this,"not yet implemented",Toast.LENGTH_LONG).show();
break;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
selectPhoto();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this,"File access denied - go to Settings - Applications - Piwigo to manually give Storage permission",Toast.LENGTH_LONG).show();
//TODO
selectPhoto();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}
private void selectPhoto(){
Intent intent = new Intent();
intent.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
getResources().getString(R.string.title_select_image)), SELECT_PICTURES);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SELECT_PICTURES) {
if(resultCode == RESULT_OK) {
if(data.getData() != null) {
String imageName = "";
Uri targetUri = data.getData();
if (data.toString().contains("content:")) {
imageName = getRealPathFromURI(targetUri);
} else if (data.toString().contains("file:")) {
imageName = targetUri.getPath();
} else {
imageName = null;
/* TODO add proper error handling */
}
byte[] content;
InputStream iStream = null;
try {
iStream = getContentResolver().openInputStream(targetUri);
content = getBytes(iStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
/* TODO add proper error handling */
content = new byte[0];
} catch (IOException e) {
e.printStackTrace();
/* TODO add proper error handling */
content = new byte[0];
} finally {
if(iStream != null){
try {
iStream.close();
} catch (IOException e) {
/* if this fails, we silently do nothing */
}
}
}
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", imageName, RequestBody.create(MediaType.parse("image/*"), content));
//do something with the image (save it to some directory or whatever you need to do with it here)
// TODO: change currentAccount
Account curAccount = comvars.getAccount();
RestService restService = restServiceFactory.createForAccount(comvars.getAccount());
String photoName;
if (imageName.indexOf(".") > 0) {
photoName = imageName.substring(0, imageName.lastIndexOf("."));
}else{
photoName = imageName;
}
AccountManager accountManager = AccountManager.get(this);
String token = accountManager.getUserData(curAccount, "token");
RequestBody imagefilenameBody = RequestBody.create(MediaType.parse("text/plain"), imageName);
RequestBody imagenameBody = RequestBody.create(MediaType.parse("text/plain"), photoName);
RequestBody tokenBody = RequestBody.create(MediaType.parse("text/plain"), token);
int catid = comvars.getValue();
if (catid > 0) {
Toast.makeText(getApplicationContext(), "Uploading Image", Toast.LENGTH_LONG).show();
//creating a call and calling the upload image method
Call<ImageUploadResponse> call = restService.uploadImage(imagefilenameBody, catid, imagenameBody, tokenBody, filePart);
//finally performing the call
call.enqueue(new Callback<ImageUploadResponse>() {
@Override
public void onResponse(Call<ImageUploadResponse> call, Response<ImageUploadResponse> response) {
if (response.raw().code() == 200) {
if (response.body().up_stat.equals("ok")) {
String uploadresp = "Uploaded: " + response.body().up_result.up_src + " to " + response.body().up_result.up_category.catlabel + "(" + Integer.toString(response.body().up_result.up_category.catid) + ")";
Toast.makeText(getApplicationContext(), uploadresp, Toast.LENGTH_LONG).show();
/* TODO: refresh the current album here */
} else {
Toast.makeText(getApplicationContext(), "Fail Response = " + response.body().up_message, Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Upload Unsuccessful = " + response.raw().message() , Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<ImageUploadResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Upload Err = " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
else
{
Toast.makeText(getApplicationContext(), "Upload - Select Album First!", Toast.LENGTH_LONG).show();
}
}
}
}
}
/* get content of an open InputStream as byte array */
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
//-
private String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
cursor = getContentResolver().query(contentUri, null, null, null,
null);
String alternative = contentUri.getLastPathSegment();
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int mediaDataIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
if(nameIndex > -1) {
return cursor.getString(nameIndex);
}else if(mediaDataIndex > -1){
return new File(cursor.getString(mediaDataIndex)).getName();
}else{
/* no usable column found, return the last Uri segment as name */
return alternative;
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}