cached instant upload
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package eu.alefzero.owncloud.ui.activity;
20
21 import java.io.File;
22 import java.net.URLEncoder;
23 import java.util.ArrayList;
24
25 import android.accounts.Account;
26 import android.accounts.AccountManager;
27 import android.app.AlertDialog;
28 import android.app.AlertDialog.Builder;
29 import android.app.Dialog;
30 import android.content.BroadcastReceiver;
31 import android.content.ContentResolver;
32 import android.content.Context;
33 import android.content.DialogInterface;
34 import android.content.DialogInterface.OnClickListener;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.database.Cursor;
38 import android.net.Uri;
39 import android.os.Bundle;
40 import android.provider.MediaStore;
41 import android.util.Log;
42 import android.view.View;
43 import android.view.ViewGroup;
44 import android.widget.ArrayAdapter;
45 import android.widget.CheckedTextView;
46 import android.widget.EditText;
47 import android.widget.TextView;
48
49 import com.actionbarsherlock.app.ActionBar;
50 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
51 import com.actionbarsherlock.app.SherlockFragmentActivity;
52 import com.actionbarsherlock.view.Menu;
53 import com.actionbarsherlock.view.MenuInflater;
54 import com.actionbarsherlock.view.MenuItem;
55 import com.actionbarsherlock.view.Window;
56
57 import eu.alefzero.owncloud.AccountUtils;
58 import eu.alefzero.owncloud.R;
59 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
60 import eu.alefzero.owncloud.datamodel.DataStorageManager;
61 import eu.alefzero.owncloud.datamodel.FileDataStorageManager;
62 import eu.alefzero.owncloud.datamodel.OCFile;
63 import eu.alefzero.owncloud.files.services.FileUploader;
64 import eu.alefzero.owncloud.syncadapter.FileSyncService;
65 import eu.alefzero.owncloud.ui.fragment.FileDetailFragment;
66 import eu.alefzero.owncloud.ui.fragment.FileListFragment;
67 import eu.alefzero.webdav.WebdavClient;
68
69 /**
70 * Displays, what files the user has available in his ownCloud.
71 *
72 * @author Bartek Przybylski
73 *
74 */
75
76 public class FileDisplayActivity extends SherlockFragmentActivity implements
77 OnNavigationListener, OnClickListener, android.view.View.OnClickListener {
78 private ArrayAdapter<String> mDirectories;
79 private DataStorageManager mStorageManager;
80 private FileListFragment mFileList;
81 private OCFile mCurrentDir;
82 private String[] mDirs = null;
83
84 private SyncBroadcastReceiver syncBroadcastRevceiver;
85
86 private static final String KEY_DIR_ARRAY = "DIR_ARRAY";
87 private static final String KEY_CURRENT_DIR = "DIR";
88
89 private static final int DIALOG_SETUP_ACCOUNT = 0;
90 private static final int DIALOG_CREATE_DIR = 1;
91 private static final int ACTION_SELECT_FILE = 1;
92
93 @Override
94 public void onCreate(Bundle savedInstanceState) {
95 super.onCreate(savedInstanceState);
96
97 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
98 setProgressBarIndeterminateVisibility(false);
99
100 if(savedInstanceState != null){
101 mCurrentDir = (OCFile) savedInstanceState.getParcelable(KEY_CURRENT_DIR);
102 }
103 }
104
105 @Override
106 public boolean onCreateOptionsMenu(Menu menu) {
107 MenuInflater inflater = getSherlock().getMenuInflater();
108 inflater.inflate(R.menu.menu, menu);
109 return true;
110 }
111
112 @Override
113 public boolean onOptionsItemSelected(MenuItem item) {
114 boolean retval = true;
115 switch (item.getItemId()) {
116 case R.id.createDirectoryItem: {
117 showDialog(DIALOG_CREATE_DIR);
118 break;
119 }
120 case R.id.startSync: {
121 Bundle bundle = new Bundle();
122 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
123 ContentResolver.requestSync(
124 AccountUtils.getCurrentOwnCloudAccount(this),
125 "org.owncloud", bundle);
126 break;
127 }
128 case R.id.action_upload: {
129 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
130 action = action.setType("*/*")
131 .addCategory(Intent.CATEGORY_OPENABLE);
132 startActivityForResult(
133 Intent.createChooser(action, "Upload file from..."),
134 ACTION_SELECT_FILE);
135 break;
136 }
137 case R.id.action_settings: {
138 Intent settingsIntent = new Intent(this, Preferences.class);
139 startActivity(settingsIntent);
140 }
141 case android.R.id.home: {
142 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
143 onBackPressed();
144 }
145 break;
146 }
147 default:
148 retval = false;
149 }
150 return retval;
151 }
152
153 @Override
154 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
155 int i = itemPosition;
156 while (i-- != 0) {
157 onBackPressed();
158 }
159 return true;
160 }
161
162 /**
163 * Called, when the user selected something for uploading
164 */
165 public void onActivityResult(int requestCode, int resultCode, Intent data) {
166 if (resultCode == RESULT_OK) {
167 if (requestCode == ACTION_SELECT_FILE) {
168 Uri selectedImageUri = data.getData();
169
170 String filemanagerstring = selectedImageUri.getPath();
171 String selectedImagePath = getPath(selectedImageUri);
172 String filepath;
173
174 if (selectedImagePath != null)
175 filepath = selectedImagePath;
176 else
177 filepath = filemanagerstring;
178
179 if (filepath == null) {
180 Log.e("FileDisplay", "Couldnt resolve path to file");
181 return;
182 }
183
184 Intent i = new Intent(this, FileUploader.class);
185 i.putExtra(FileUploader.KEY_ACCOUNT,
186 AccountUtils.getCurrentOwnCloudAccount(this));
187 String remotepath = new String();
188 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
189 remotepath += "/" + URLEncoder.encode(mDirectories.getItem(j));
190 }
191 if (!remotepath.endsWith("/"))
192 remotepath += "/";
193 remotepath += URLEncoder.encode(new File(filepath).getName());
194
195 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
196 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
197 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
198 startService(i);
199 }
200 }
201 }
202
203 @Override
204 public void onBackPressed() {
205 if (mDirectories == null || mDirectories.getCount() <= 1) {
206 finish();
207 return;
208 }
209 popDirname();
210 mFileList.onNavigateUp();
211 mCurrentDir = mFileList.getCurrentFile();
212
213 if(mCurrentDir.getParentId() == 0){
214 ActionBar actionBar = getSupportActionBar();
215 actionBar.setDisplayHomeAsUpEnabled(false);
216 }
217 }
218
219 @Override
220 protected void onRestoreInstanceState(Bundle savedInstanceState) {
221 super.onRestoreInstanceState(savedInstanceState);
222 mDirs = savedInstanceState.getStringArray(KEY_DIR_ARRAY);
223 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
224 mDirectories.add("/");
225 if (mDirs != null)
226 for (String s : mDirs)
227 mDirectories.insert(s, 0);
228 }
229
230 @Override
231 protected void onSaveInstanceState(Bundle outState) {
232 super.onSaveInstanceState(outState);
233 if(mDirectories != null && mDirectories.getCount() != 0){
234 mDirs = new String[mDirectories.getCount()-1];
235 for (int j = mDirectories.getCount() - 2, i = 0; j >= 0; --j, ++i) {
236 mDirs[i] = mDirectories.getItem(j);
237 }
238 }
239 outState.putStringArray(KEY_DIR_ARRAY, mDirs);
240 outState.putParcelable(KEY_CURRENT_DIR, mCurrentDir);
241 }
242
243 @Override
244 protected void onResume() {
245 super.onResume();
246
247 //TODO: Dialog useless -> get rid of this
248 if (!accountsAreSetup()) {
249 setContentView(R.layout.no_account_available);
250 setProgressBarIndeterminateVisibility(false);
251 getSupportActionBar().setNavigationMode(ActionBar.DISPLAY_SHOW_TITLE);
252 findViewById(R.id.setup_account).setOnClickListener(this);
253 return;
254 } else if (findViewById(R.id.file_list_view) == null) {
255 setContentView(R.layout.files);
256 }
257
258 // Listen for sync messages
259 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
260 syncBroadcastRevceiver = new SyncBroadcastReceiver();
261 registerReceiver(syncBroadcastRevceiver, syncIntentFilter);
262
263 // Storage manager initialization
264 mStorageManager = new FileDataStorageManager(
265 AccountUtils.getCurrentOwnCloudAccount(this),
266 getContentResolver());
267
268 // File list
269 mFileList = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
270
271 // Figure out what directory to list.
272 // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)
273 if(getIntent().hasExtra(FileDetailFragment.EXTRA_FILE)){
274 mCurrentDir = (OCFile) getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
275 if(!mCurrentDir.isDirectory()){
276 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
277 }
278
279 // Clear intent extra, so rotating the screen will not return us to this directory
280 getIntent().removeExtra(FileDetailFragment.EXTRA_FILE);
281 }
282
283 // Drop-Down navigation and file list restore
284 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
285
286
287 // Given the case we have a file to display:
288 if(mCurrentDir != null){
289 ArrayList<OCFile> files = new ArrayList<OCFile>();
290 OCFile currFile = mCurrentDir;
291 while(currFile != null){
292 files.add(currFile);
293 currFile = mStorageManager.getFileById(currFile.getParentId());
294 }
295
296 // Insert in mDirs
297 mDirs = new String[files.size()];
298 for(int i = files.size() - 1; i >= 0; i--){
299 mDirs[i] = files.get(i).getFileName();
300 }
301 }
302
303 if (mDirs != null) {
304 for (String s : mDirs)
305 mDirectories.add(s);
306 } else {
307 mDirectories.add("/");
308 }
309
310 // Actionbar setup
311 ActionBar action_bar = getSupportActionBar();
312 action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
313 action_bar.setDisplayShowTitleEnabled(false);
314 action_bar.setListNavigationCallbacks(mDirectories, this);
315 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
316 action_bar.setDisplayHomeAsUpEnabled(true);
317 } else {
318 action_bar.setDisplayHomeAsUpEnabled(false);
319 }
320
321 // List dir here
322 mFileList.listDirectory(mCurrentDir);
323 }
324
325 @Override
326 protected void onPause() {
327 super.onPause();
328 if (syncBroadcastRevceiver != null) {
329 unregisterReceiver(syncBroadcastRevceiver);
330 syncBroadcastRevceiver = null;
331 }
332
333 }
334
335 @Override
336 protected Dialog onCreateDialog(int id) {
337 Dialog dialog;
338 AlertDialog.Builder builder;
339 switch (id) {
340 case DIALOG_SETUP_ACCOUNT:
341 builder = new AlertDialog.Builder(this);
342 builder.setTitle(R.string.main_tit_accsetup);
343 builder.setMessage(R.string.main_wrn_accsetup);
344 builder.setCancelable(false);
345 builder.setPositiveButton(android.R.string.ok, this);
346 builder.setNegativeButton(android.R.string.cancel, this);
347 dialog = builder.create();
348 break;
349 case DIALOG_CREATE_DIR: {
350 builder = new Builder(this);
351 final EditText dirNameInput = new EditText(getBaseContext());
352 final Account a = AccountUtils.getCurrentOwnCloudAccount(this);
353 builder.setView(dirNameInput);
354 builder.setTitle(R.string.uploader_info_dirname);
355 int typed_color = getResources().getColor(R.color.setup_text_typed);
356 dirNameInput.setTextColor(typed_color);
357
358 builder.setPositiveButton(android.R.string.ok,
359 new OnClickListener() {
360 public void onClick(DialogInterface dialog, int which) {
361 String directoryName = dirNameInput.getText().toString();
362 if (directoryName.trim().length() == 0) {
363 dialog.cancel();
364 return;
365 }
366
367 // Figure out the path where the dir needs to be created
368 String path = mCurrentDir.getRemotePath();
369
370 // Create directory
371 path += directoryName + "/";
372 Thread thread = new Thread(new DirectoryCreator(
373 path, a));
374 thread.start();
375
376 // Save new directory in local database
377 OCFile newDir = new OCFile(path);
378 newDir.setMimetype("DIR");
379 newDir.setParentId(mCurrentDir.getFileId());
380 mStorageManager.saveFile(newDir);
381
382 // Display the new folder right away
383 dialog.dismiss();
384 mFileList.listDirectory(mCurrentDir);
385 }
386 });
387 builder.setNegativeButton(R.string.common_cancel,
388 new OnClickListener() {
389 public void onClick(DialogInterface dialog, int which) {
390 dialog.cancel();
391 }
392 });
393 dialog = builder.create();
394 break;
395 }
396 default:
397 dialog = null;
398 }
399
400 return dialog;
401 }
402
403
404 /**
405 * Responds to the "There are no ownCloud Accounts setup" dialog
406 * TODO: Dialog is 100% useless -> Remove
407 */
408 @Override
409 public void onClick(DialogInterface dialog, int which) {
410 // In any case - we won't need it anymore
411 dialog.dismiss();
412 switch (which) {
413 case DialogInterface.BUTTON_POSITIVE:
414 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
415 intent.putExtra("authorities",
416 new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
417 startActivity(intent);
418 break;
419 case DialogInterface.BUTTON_NEGATIVE:
420 finish();
421 }
422
423 }
424
425 /**
426 * Translates a content URI of an image to a physical path
427 * on the disk
428 * @param uri The URI to resolve
429 * @return The path to the image or null if it could not be found
430 */
431 public String getPath(Uri uri) {
432 String[] projection = { MediaStore.Images.Media.DATA };
433 Cursor cursor = managedQuery(uri, projection, null, null, null);
434 if (cursor != null) {
435 int column_index = cursor
436 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
437 cursor.moveToFirst();
438 return cursor.getString(column_index);
439 }
440 return null;
441 }
442
443 /**
444 * Pushes a directory to the drop down list
445 * @param directory to push
446 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
447 */
448 public void pushDirname(OCFile directory) {
449 if(!directory.isDirectory()){
450 throw new IllegalArgumentException("Only directories may be pushed!");
451 }
452 mDirectories.insert(directory.getFileName(), 0);
453 mCurrentDir = directory;
454 }
455
456 /**
457 * Pops a directory name from the drop down list
458 * @return True, unless the stack is empty
459 */
460 public boolean popDirname() {
461 mDirectories.remove(mDirectories.getItem(0));
462 return !mDirectories.isEmpty();
463 }
464
465 /**
466 * Checks, whether or not there are any ownCloud accounts setup.
467 *
468 * @return true, if there is at least one account.
469 */
470 private boolean accountsAreSetup() {
471 AccountManager accMan = AccountManager.get(this);
472 Account[] accounts = accMan
473 .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
474 return accounts.length > 0;
475 }
476
477 private class DirectoryCreator implements Runnable {
478 private String mTargetPath;
479 private Account mAccount;
480 private AccountManager mAm;
481
482 public DirectoryCreator(String targetPath, Account account) {
483 mTargetPath = targetPath;
484 mAccount = account;
485 mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
486 }
487
488 @Override
489 public void run() {
490 WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(
491 mAccount, AccountAuthenticator.KEY_OC_URL)));
492
493 String username = mAccount.name.substring(0,
494 mAccount.name.lastIndexOf('@'));
495 String password = mAm.getPassword(mAccount);
496
497 wdc.setCredentials(username, password);
498 wdc.allowSelfsignedCertificates();
499 wdc.createDirectory(mTargetPath);
500 }
501
502 }
503
504 // Custom array adapter to override text colors
505 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
506
507 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
508 super(ctx, view);
509 }
510
511 public View getView(int position, View convertView, ViewGroup parent) {
512 View v = super.getView(position, convertView, parent);
513
514 ((TextView) v).setTextColor(getResources().getColorStateList(
515 android.R.color.white));
516 return v;
517 }
518
519 public View getDropDownView(int position, View convertView,
520 ViewGroup parent) {
521 View v = super.getDropDownView(position, convertView, parent);
522
523 ((TextView) v).setTextColor(getResources().getColorStateList(
524 android.R.color.white));
525
526 return v;
527 }
528
529 }
530
531 private class SyncBroadcastReceiver extends BroadcastReceiver {
532 /**
533 * {@link BroadcastReceiver} to enable syncing feedback in UI
534 */
535 @Override
536 public void onReceive(Context context, Intent intent) {
537 boolean inProgress = intent.getBooleanExtra(
538 FileSyncService.IN_PROGRESS, false);
539 String account_name = intent
540 .getStringExtra(FileSyncService.ACCOUNT_NAME);
541 Log.d("FileDisplay", "sync of account " + account_name
542 + " is in_progress: " + inProgress);
543 setProgressBarIndeterminateVisibility(inProgress);
544 if (!inProgress) {
545 FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()
546 .findFragmentById(R.id.fileList);
547 if (fileListFramgent != null)
548 fileListFramgent.listDirectory();
549 }
550 }
551
552 }
553
554 @Override
555 public void onClick(View v) {
556 if (v.getId() == R.id.setup_account) {
557 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
558 intent.putExtra("authorities", new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
559 startActivity(intent);
560 }
561 }
562
563 }