Adding cancellation to uploads (WIP)
[pub/Android/ownCloud.git] / src / com / owncloud / android / 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 com.owncloud.android.ui.activity;
20
21 import java.io.File;
22
23 import android.accounts.Account;
24 import android.app.AlertDialog;
25 import android.app.ProgressDialog;
26 import android.app.AlertDialog.Builder;
27 import android.app.Dialog;
28 import android.content.BroadcastReceiver;
29 import android.content.ComponentName;
30 import android.content.ContentResolver;
31 import android.content.Context;
32 import android.content.DialogInterface;
33 import android.content.DialogInterface.OnClickListener;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.ServiceConnection;
37 import android.content.SharedPreferences;
38 import android.content.pm.PackageInfo;
39 import android.content.pm.PackageManager.NameNotFoundException;
40 import android.content.res.Resources.NotFoundException;
41 import android.database.Cursor;
42 import android.net.Uri;
43 import android.os.Bundle;
44 import android.os.Handler;
45 import android.os.IBinder;
46 import android.preference.PreferenceManager;
47 import android.provider.MediaStore;
48 import android.support.v4.app.FragmentTransaction;
49 import android.util.Log;
50 import android.view.View;
51 import android.view.ViewGroup;
52 import android.widget.ArrayAdapter;
53 import android.widget.EditText;
54 import android.widget.TextView;
55 import android.widget.Toast;
56
57 import com.actionbarsherlock.app.ActionBar;
58 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
59 import com.actionbarsherlock.app.SherlockFragmentActivity;
60 import com.actionbarsherlock.view.Menu;
61 import com.actionbarsherlock.view.MenuInflater;
62 import com.actionbarsherlock.view.MenuItem;
63 import com.actionbarsherlock.view.Window;
64 import com.owncloud.android.AccountUtils;
65 import com.owncloud.android.authenticator.AccountAuthenticator;
66 import com.owncloud.android.datamodel.DataStorageManager;
67 import com.owncloud.android.datamodel.FileDataStorageManager;
68 import com.owncloud.android.datamodel.OCFile;
69 import com.owncloud.android.files.services.FileDownloader;
70 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
71 import com.owncloud.android.files.services.FileUploader;
72 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
73 import com.owncloud.android.network.OwnCloudClientUtils;
74 import com.owncloud.android.syncadapter.FileSyncService;
75 import com.owncloud.android.ui.fragment.FileDetailFragment;
76 import com.owncloud.android.ui.fragment.OCFileListFragment;
77
78 import com.owncloud.android.R;
79 import eu.alefzero.webdav.WebdavClient;
80
81 /**
82 * Displays, what files the user has available in his ownCloud.
83 *
84 * @author Bartek Przybylski
85 *
86 */
87
88 public class FileDisplayActivity extends SherlockFragmentActivity implements
89 OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener {
90
91 private ArrayAdapter<String> mDirectories;
92 private OCFile mCurrentDir = null;
93 private OCFile mCurrentFile = null;
94
95 private DataStorageManager mStorageManager;
96 private SyncBroadcastReceiver mSyncBroadcastReceiver;
97 private UploadFinishReceiver mUploadFinishReceiver;
98 private DownloadFinishReceiver mDownloadFinishReceiver;
99 private FileDownloaderBinder mDownloaderBinder = null;
100 private FileUploaderBinder mUploaderBinder = null;
101 private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
102
103 private OCFileListFragment mFileList;
104
105 private boolean mDualPane;
106
107 private static final int DIALOG_SETUP_ACCOUNT = 0;
108 private static final int DIALOG_CREATE_DIR = 1;
109 private static final int DIALOG_ABOUT_APP = 2;
110 public static final int DIALOG_SHORT_WAIT = 3;
111 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 4;
112
113 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
114 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
115
116 private static final String TAG = "FileDisplayActivity";
117
118 @Override
119 public void onCreate(Bundle savedInstanceState) {
120 Log.d(getClass().toString(), "onCreate() start");
121 super.onCreate(savedInstanceState);
122
123 /// Load of parameters from received intent
124 mCurrentDir = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE); // no check necessary, mCurrenDir == null if the parameter is not in the intent
125 Account account = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT);
126 if (account != null)
127 AccountUtils.setCurrentOwnCloudAccount(this, account.name);
128
129 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
130 if(savedInstanceState != null) {
131 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
132 mCurrentDir = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
133 }
134
135 if (!AccountUtils.accountsAreSetup(this)) {
136 /// no account available: FORCE ACCOUNT CREATION
137 mStorageManager = null;
138 createFirstAccount();
139
140 } else { /// at least an account is available
141
142 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
143
144 }
145
146 mUploadConnection = new ListServiceConnection();
147 mDownloadConnection = new ListServiceConnection();
148 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
149 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
150
151 // PIN CODE request ; best location is to decide, let's try this first
152 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
153 requestPinCode();
154 }
155
156 // file observer
157 /*Intent observer_intent = new Intent(this, FileObserverService.class);
158 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
159 startService(observer_intent);
160 */
161
162 /// USER INTERFACE
163 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
164
165 // Drop-down navigation
166 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
167 OCFile currFile = mCurrentDir;
168 while(currFile != null && currFile.getFileName() != OCFile.PATH_SEPARATOR) {
169 mDirectories.add(currFile.getFileName());
170 currFile = mStorageManager.getFileById(currFile.getParentId());
171 }
172 mDirectories.add(OCFile.PATH_SEPARATOR);
173
174 // Inflate and set the layout view
175 setContentView(R.layout.files);
176 mFileList = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
177 mDualPane = (findViewById(R.id.file_details_container) != null);
178 if (mDualPane) {
179 initFileDetailsInDualPane();
180 }
181
182 // Action bar setup
183 ActionBar actionBar = getSupportActionBar();
184 actionBar.setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
185 actionBar.setDisplayHomeAsUpEnabled(mCurrentDir != null && mCurrentDir.getParentId() != 0);
186 actionBar.setDisplayShowTitleEnabled(false);
187 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
188 actionBar.setListNavigationCallbacks(mDirectories, this);
189 setSupportProgressBarIndeterminateVisibility(false); // always AFTER setContentView(...) ; to workaround bug in its implementation
190
191 Log.d(getClass().toString(), "onCreate() end");
192 }
193
194
195 /**
196 * Launches the account creation activity. To use when no ownCloud account is available
197 */
198 private void createFirstAccount() {
199 Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
200 intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
201 startActivity(intent); // the new activity won't be created until this.onStart() and this.onResume() are finished;
202 }
203
204
205 /**
206 * Load of state dependent of the existence of an ownCloud account
207 */
208 private void initDataFromCurrentAccount() {
209 /// Storage manager initialization - access to local database
210 mStorageManager = new FileDataStorageManager(
211 AccountUtils.getCurrentOwnCloudAccount(this),
212 getContentResolver());
213
214 /// Check if mCurrentDir is a directory
215 if(mCurrentDir != null && !mCurrentDir.isDirectory()) {
216 mCurrentFile = mCurrentDir;
217 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
218 }
219
220 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
221 if (mCurrentDir != null) {
222 mCurrentDir = mStorageManager.getFileByPath(mCurrentDir.getRemotePath()); // mCurrentDir == null if it is not in the current account
223 }
224 if (mCurrentFile != null) {
225 mCurrentFile = mStorageManager.getFileByPath(mCurrentFile.getRemotePath()); // mCurrentFile == null if it is not in the current account
226 }
227
228 /// Default to root if mCurrentDir was not found
229 if (mCurrentDir == null) {
230 mCurrentDir = mStorageManager.getFileByPath("/"); // will be NULL if the database was never synchronized
231 }
232 }
233
234
235 private void initFileDetailsInDualPane() {
236 if (mDualPane && getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG) == null) {
237 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
238 if (mCurrentFile != null) {
239 transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG); // empty FileDetailFragment
240 mCurrentFile = null;
241 } else {
242 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
243 }
244 transaction.commit();
245 }
246 }
247
248
249 @Override
250 public void onDestroy() {
251 super.onDestroy();
252 if (mDownloadConnection != null)
253 unbindService(mDownloadConnection);
254 if (mUploadConnection != null)
255 unbindService(mUploadConnection);
256 }
257
258
259 @Override
260 public boolean onCreateOptionsMenu(Menu menu) {
261 MenuInflater inflater = getSherlock().getMenuInflater();
262 inflater.inflate(R.menu.menu, menu);
263 return true;
264 }
265
266 @Override
267 public boolean onOptionsItemSelected(MenuItem item) {
268 boolean retval = true;
269 switch (item.getItemId()) {
270 case R.id.createDirectoryItem: {
271 showDialog(DIALOG_CREATE_DIR);
272 break;
273 }
274 case R.id.startSync: {
275 ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE); // cancel the current synchronizations of any ownCloud account
276 Bundle bundle = new Bundle();
277 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
278 ContentResolver.requestSync(
279 AccountUtils.getCurrentOwnCloudAccount(this),
280 AccountAuthenticator.AUTH_TOKEN_TYPE, bundle);
281 break;
282 }
283 case R.id.action_upload: {
284 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
285 break;
286 }
287 case R.id.action_settings: {
288 Intent settingsIntent = new Intent(this, Preferences.class);
289 startActivity(settingsIntent);
290 break;
291 }
292 case R.id.about_app : {
293 showDialog(DIALOG_ABOUT_APP);
294 break;
295 }
296 case android.R.id.home: {
297 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
298 onBackPressed();
299 }
300 break;
301 }
302 default:
303 retval = false;
304 }
305 return retval;
306 }
307
308 @Override
309 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
310 int i = itemPosition;
311 while (i-- != 0) {
312 onBackPressed();
313 }
314 // the next operation triggers a new call to this method, but it's necessary to
315 // ensure that the name exposed in the action bar is the current directory when the
316 // user selected it in the navigation list
317 if (itemPosition != 0)
318 getSupportActionBar().setSelectedNavigationItem(0);
319 return true;
320 }
321
322 /**
323 * Called, when the user selected something for uploading
324 */
325 public void onActivityResult(int requestCode, int resultCode, Intent data) {
326
327 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && resultCode == RESULT_OK) {
328 requestSimpleUpload(data);
329
330 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && resultCode == RESULT_OK) {
331 requestMultipleUpload(data);
332
333 }
334 }
335
336 private void requestMultipleUpload(Intent data) {
337 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
338 if (filePaths != null) {
339 String[] remotePaths = new String[filePaths.length];
340 String remotePathBase = "";
341 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
342 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
343 }
344 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
345 remotePathBase += OCFile.PATH_SEPARATOR;
346 for (int j = 0; j< remotePaths.length; j++) {
347 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
348 }
349
350 Intent i = new Intent(this, FileUploader.class);
351 i.putExtra(FileUploader.KEY_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
352 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
353 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
354 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
355 startService(i);
356
357 } else {
358 Log.d("FileDisplay", "User clicked on 'Update' with no selection");
359 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
360 t.show();
361 return;
362 }
363 }
364
365
366 private void requestSimpleUpload(Intent data) {
367 String filepath = null;
368 try {
369 Uri selectedImageUri = data.getData();
370
371 String filemanagerstring = selectedImageUri.getPath();
372 String selectedImagePath = getPath(selectedImageUri);
373
374 if (selectedImagePath != null)
375 filepath = selectedImagePath;
376 else
377 filepath = filemanagerstring;
378
379 } catch (Exception e) {
380 Log.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
381 e.printStackTrace();
382
383 } finally {
384 if (filepath == null) {
385 Log.e("FileDisplay", "Couldnt resolve path to file");
386 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
387 t.show();
388 return;
389 }
390 }
391
392 Intent i = new Intent(this, FileUploader.class);
393 i.putExtra(FileUploader.KEY_ACCOUNT,
394 AccountUtils.getCurrentOwnCloudAccount(this));
395 String remotepath = new String();
396 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
397 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
398 }
399 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
400 remotepath += OCFile.PATH_SEPARATOR;
401 remotepath += new File(filepath).getName();
402
403 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
404 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
405 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
406 startService(i);
407 }
408
409
410 @Override
411 public void onBackPressed() {
412 if (mDirectories.getCount() <= 1) {
413 finish();
414 return;
415 }
416 popDirname();
417 mFileList.onNavigateUp();
418 mCurrentDir = mFileList.getCurrentFile();
419
420 if (mDualPane) {
421 // Resets the FileDetailsFragment on Tablets so that it always displays
422 FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
423 if (fileDetails != null && !fileDetails.isEmpty()) {
424 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
425 transaction.remove(fileDetails);
426 transaction.add(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG);
427 transaction.commit();
428 }
429 }
430
431 if(mCurrentDir.getParentId() == 0){
432 ActionBar actionBar = getSupportActionBar();
433 actionBar.setDisplayHomeAsUpEnabled(false);
434 }
435 }
436
437 @Override
438 protected void onSaveInstanceState(Bundle outState) {
439 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
440 Log.d(getClass().toString(), "onSaveInstanceState() start");
441 super.onSaveInstanceState(outState);
442 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);
443 if (mDualPane) {
444 FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
445 OCFile file = fragment.getDisplayedFile();
446 if (file != null) {
447 outState.putParcelable(FileDetailFragment.EXTRA_FILE, file);
448 }
449 }
450 Log.d(getClass().toString(), "onSaveInstanceState() end");
451 }
452
453 @Override
454 protected void onResume() {
455 Log.d(getClass().toString(), "onResume() start");
456 super.onResume();
457
458 if (AccountUtils.accountsAreSetup(this)) {
459
460 if (mStorageManager == null) {
461 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
462 initDataFromCurrentAccount();
463 if (mDualPane) {
464 initFileDetailsInDualPane();
465 }
466 }
467
468 // Listen for sync messages
469 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
470 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
471 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
472
473 // Listen for upload messages
474 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
475 mUploadFinishReceiver = new UploadFinishReceiver();
476 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
477
478 // Listen for download messages
479 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
480 mDownloadFinishReceiver = new DownloadFinishReceiver();
481 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
482
483 // List current directory
484 mFileList.listDirectory(mCurrentDir); // we should find the way to avoid the need of this
485
486 } else {
487
488 mStorageManager = null; // an invalid object will be there if all the ownCloud accounts are removed
489 showDialog(DIALOG_SETUP_ACCOUNT);
490
491 }
492 Log.d(getClass().toString(), "onResume() end");
493 }
494
495
496 @Override
497 protected void onPause() {
498 Log.d(getClass().toString(), "onPause() start");
499 super.onPause();
500 if (mSyncBroadcastReceiver != null) {
501 unregisterReceiver(mSyncBroadcastReceiver);
502 mSyncBroadcastReceiver = null;
503 }
504 if (mUploadFinishReceiver != null) {
505 unregisterReceiver(mUploadFinishReceiver);
506 mUploadFinishReceiver = null;
507 }
508 if (mDownloadFinishReceiver != null) {
509 unregisterReceiver(mDownloadFinishReceiver);
510 mDownloadFinishReceiver = null;
511 }
512 if (!AccountUtils.accountsAreSetup(this)) {
513 dismissDialog(DIALOG_SETUP_ACCOUNT);
514 }
515
516 Log.d(getClass().toString(), "onPause() end");
517 }
518
519 @Override
520 protected Dialog onCreateDialog(int id) {
521 Dialog dialog = null;
522 AlertDialog.Builder builder;
523 switch (id) {
524 case DIALOG_SETUP_ACCOUNT: {
525 builder = new AlertDialog.Builder(this);
526 builder.setTitle(R.string.main_tit_accsetup);
527 builder.setMessage(R.string.main_wrn_accsetup);
528 builder.setCancelable(false);
529 builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
530 public void onClick(DialogInterface dialog, int which) {
531 createFirstAccount();
532 dialog.dismiss();
533 }
534 });
535 builder.setNegativeButton(R.string.common_exit, new OnClickListener() {
536 public void onClick(DialogInterface dialog, int which) {
537 dialog.dismiss();
538 finish();
539 }
540 });
541 //builder.setNegativeButton(android.R.string.cancel, this);
542 dialog = builder.create();
543 break;
544 }
545 case DIALOG_ABOUT_APP: {
546 builder = new AlertDialog.Builder(this);
547 builder.setTitle(getString(R.string.about_title));
548 PackageInfo pkg;
549 try {
550 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
551 builder.setMessage("ownCloud android client\n\nversion: " + pkg.versionName );
552 builder.setIcon(android.R.drawable.ic_menu_info_details);
553 dialog = builder.create();
554 } catch (NameNotFoundException e) {
555 builder = null;
556 dialog = null;
557 Log.e(TAG, "Error while showing about dialog", e);
558 }
559 break;
560 }
561 case DIALOG_CREATE_DIR: {
562 builder = new Builder(this);
563 final EditText dirNameInput = new EditText(getBaseContext());
564 builder.setView(dirNameInput);
565 builder.setTitle(R.string.uploader_info_dirname);
566 int typed_color = getResources().getColor(R.color.setup_text_typed);
567 dirNameInput.setTextColor(typed_color);
568 builder.setPositiveButton(android.R.string.ok,
569 new OnClickListener() {
570 public void onClick(DialogInterface dialog, int which) {
571 String directoryName = dirNameInput.getText().toString();
572 if (directoryName.trim().length() == 0) {
573 dialog.cancel();
574 return;
575 }
576
577 // Figure out the path where the dir needs to be created
578 String path;
579 if (mCurrentDir == null) {
580 // this is just a patch; we should ensure that mCurrentDir never is null
581 if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
582 OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
583 mStorageManager.saveFile(file);
584 }
585 mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
586 }
587 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
588
589 // Create directory
590 path += directoryName + OCFile.PATH_SEPARATOR;
591 Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
592 thread.start();
593
594 dialog.dismiss();
595
596 showDialog(DIALOG_SHORT_WAIT);
597 }
598 });
599 builder.setNegativeButton(R.string.common_cancel,
600 new OnClickListener() {
601 public void onClick(DialogInterface dialog, int which) {
602 dialog.cancel();
603 }
604 });
605 dialog = builder.create();
606 break;
607 }
608 case DIALOG_SHORT_WAIT: {
609 ProgressDialog working_dialog = new ProgressDialog(this);
610 working_dialog.setMessage(getResources().getString(
611 R.string.wait_a_moment));
612 working_dialog.setIndeterminate(true);
613 working_dialog.setCancelable(false);
614 dialog = working_dialog;
615 break;
616 }
617 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
618 final String [] items = { getString(R.string.actionbar_upload_files),
619 getString(R.string.actionbar_upload_from_apps) };
620 builder = new AlertDialog.Builder(this);
621 builder.setTitle(R.string.actionbar_upload);
622 builder.setItems(items, new DialogInterface.OnClickListener() {
623 public void onClick(DialogInterface dialog, int item) {
624 if (item == 0) {
625 //if (!mDualPane) {
626 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
627 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
628 //} else {
629 // TODO create and handle new fragment LocalFileListFragment
630 //}
631 } else if (item == 1) {
632 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
633 action = action.setType("*/*")
634 .addCategory(Intent.CATEGORY_OPENABLE);
635 startActivityForResult(
636 Intent.createChooser(action, getString(R.string.upload_chooser_title)),
637 ACTION_SELECT_CONTENT_FROM_APPS);
638 }
639 }
640 });
641 dialog = builder.create();
642 break;
643 }
644 default:
645 dialog = null;
646 }
647
648 return dialog;
649 }
650
651
652 /**
653 * Translates a content URI of an image to a physical path
654 * on the disk
655 * @param uri The URI to resolve
656 * @return The path to the image or null if it could not be found
657 */
658 public String getPath(Uri uri) {
659 String[] projection = { MediaStore.Images.Media.DATA };
660 Cursor cursor = managedQuery(uri, projection, null, null, null);
661 if (cursor != null) {
662 int column_index = cursor
663 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
664 cursor.moveToFirst();
665 return cursor.getString(column_index);
666 }
667 return null;
668 }
669
670 /**
671 * Pushes a directory to the drop down list
672 * @param directory to push
673 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
674 */
675 public void pushDirname(OCFile directory) {
676 if(!directory.isDirectory()){
677 throw new IllegalArgumentException("Only directories may be pushed!");
678 }
679 mDirectories.insert(directory.getFileName(), 0);
680 mCurrentDir = directory;
681 }
682
683 /**
684 * Pops a directory name from the drop down list
685 * @return True, unless the stack is empty
686 */
687 public boolean popDirname() {
688 mDirectories.remove(mDirectories.getItem(0));
689 return !mDirectories.isEmpty();
690 }
691
692 private class DirectoryCreator implements Runnable {
693 private String mTargetPath;
694 private Account mAccount;
695 private Handler mHandler;
696
697 public DirectoryCreator(String targetPath, Account account, Handler handler) {
698 mTargetPath = targetPath;
699 mAccount = account;
700 mHandler = handler;
701 }
702
703 @Override
704 public void run() {
705 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
706 boolean created = wdc.createDirectory(mTargetPath);
707 if (created) {
708 mHandler.post(new Runnable() {
709 @Override
710 public void run() {
711 dismissDialog(DIALOG_SHORT_WAIT);
712
713 // Save new directory in local database
714 OCFile newDir = new OCFile(mTargetPath);
715 newDir.setMimetype("DIR");
716 newDir.setParentId(mCurrentDir.getFileId());
717 mStorageManager.saveFile(newDir);
718
719 // Display the new folder right away
720 mFileList.listDirectory(mCurrentDir);
721 }
722 });
723
724 } else {
725 mHandler.post(new Runnable() {
726 @Override
727 public void run() {
728 dismissDialog(DIALOG_SHORT_WAIT);
729 try {
730 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
731 msg.show();
732
733 } catch (NotFoundException e) {
734 Log.e(TAG, "Error while trying to show fail message " , e);
735 }
736 }
737 });
738 }
739 }
740
741 }
742
743 // Custom array adapter to override text colors
744 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
745
746 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
747 super(ctx, view);
748 }
749
750 public View getView(int position, View convertView, ViewGroup parent) {
751 View v = super.getView(position, convertView, parent);
752
753 ((TextView) v).setTextColor(getResources().getColorStateList(
754 android.R.color.white));
755 return v;
756 }
757
758 public View getDropDownView(int position, View convertView,
759 ViewGroup parent) {
760 View v = super.getDropDownView(position, convertView, parent);
761
762 ((TextView) v).setTextColor(getResources().getColorStateList(
763 android.R.color.white));
764
765 return v;
766 }
767
768 }
769
770 private class SyncBroadcastReceiver extends BroadcastReceiver {
771 /**
772 * {@link BroadcastReceiver} to enable syncing feedback in UI
773 */
774 @Override
775 public void onReceive(Context context, Intent intent) {
776 boolean inProgress = intent.getBooleanExtra(
777 FileSyncService.IN_PROGRESS, false);
778 String accountName = intent
779 .getStringExtra(FileSyncService.ACCOUNT_NAME);
780
781 Log.d("FileDisplay", "sync of account " + accountName
782 + " is in_progress: " + inProgress);
783
784 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
785
786 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
787
788 boolean fillBlankRoot = false;
789 if (mCurrentDir == null) {
790 mCurrentDir = mStorageManager.getFileByPath("/");
791 fillBlankRoot = (mCurrentDir != null);
792 }
793
794 if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
795 || fillBlankRoot ) {
796 if (!fillBlankRoot)
797 mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
798 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager()
799 .findFragmentById(R.id.fileList);
800 if (fileListFragment != null) {
801 fileListFragment.listDirectory(mCurrentDir);
802 }
803 }
804
805 setSupportProgressBarIndeterminateVisibility(inProgress);
806
807 }
808 }
809 }
810
811
812 private class UploadFinishReceiver extends BroadcastReceiver {
813 /**
814 * Once the file upload has finished -> update view
815 * @author David A. Velasco
816 * {@link BroadcastReceiver} to enable upload feedback in UI
817 */
818 @Override
819 public void onReceive(Context context, Intent intent) {
820 long parentDirId = intent.getLongExtra(FileUploader.EXTRA_PARENT_DIR_ID, -1);
821 OCFile parentDir = mStorageManager.getFileById(parentDirId);
822 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
823
824 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
825 parentDir != null &&
826 ( (mCurrentDir == null && parentDir.getFileName().equals("/")) ||
827 parentDir.equals(mCurrentDir)
828 )
829 ) {
830 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
831 if (fileListFragment != null) {
832 fileListFragment.listDirectory();
833 }
834 }
835 }
836
837 }
838
839
840 /**
841 * Once the file download has finished -> update view
842 */
843 private class DownloadFinishReceiver extends BroadcastReceiver {
844 @Override
845 public void onReceive(Context context, Intent intent) {
846 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
847 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
848
849 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
850 mCurrentDir != null && mCurrentDir.getFileId() == mStorageManager.getFileByPath(downloadedRemotePath).getParentId()) {
851 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
852 if (fileListFragment != null) {
853 fileListFragment.listDirectory();
854 }
855 }
856 }
857 }
858
859
860
861
862 /**
863 * {@inheritDoc}
864 */
865 @Override
866 public DataStorageManager getStorageManager() {
867 return mStorageManager;
868 }
869
870
871 /**
872 * {@inheritDoc}
873 */
874 @Override
875 public void onDirectoryClick(OCFile directory) {
876 pushDirname(directory);
877 ActionBar actionBar = getSupportActionBar();
878 actionBar.setDisplayHomeAsUpEnabled(true);
879
880 if (mDualPane) {
881 // Resets the FileDetailsFragment on Tablets so that it always displays
882 FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
883 if (fileDetails != null && !fileDetails.isEmpty()) {
884 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
885 transaction.remove(fileDetails);
886 transaction.add(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG);
887 transaction.commit();
888 }
889 }
890 }
891
892
893 /**
894 * {@inheritDoc}
895 */
896 @Override
897 public void onFileClick(OCFile file) {
898
899 // If we are on a large device -> update fragment
900 if (mDualPane) {
901 // buttons in the details view are problematic when trying to reuse an existing fragment; create always a new one solves some of them, BUT no all; downloads are 'dangerous'
902 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
903 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
904 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
905 transaction.commit();
906
907 } else { // small or medium screen device -> new Activity
908 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
909 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
910 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
911 startActivity(showDetailsIntent);
912 }
913 }
914
915
916 /**
917 * {@inheritDoc}
918 */
919 @Override
920 public OCFile getInitialDirectory() {
921 return mCurrentDir;
922 }
923
924
925 /**
926 * {@inheritDoc}
927 */
928 @Override
929 public void onFileStateChanged() {
930 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
931 if (fileListFragment != null) {
932 fileListFragment.listDirectory();
933 }
934 }
935
936
937 /**
938 * {@inheritDoc}
939 */
940 @Override
941 public FileDownloaderBinder getFileDownloaderBinder() {
942 return mDownloaderBinder;
943 }
944
945
946 /**
947 * {@inheritDoc}
948 */
949 @Override
950 public FileUploaderBinder getFileUploaderBinder() {
951 return mUploaderBinder;
952 }
953
954
955 /** Defines callbacks for service binding, passed to bindService() */
956 private class ListServiceConnection implements ServiceConnection {
957
958 @Override
959 public void onServiceConnected(ComponentName component, IBinder service) {
960 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
961 Log.d(TAG, "Download service connected");
962 mDownloaderBinder = (FileDownloaderBinder) service;
963 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
964 Log.d(TAG, "Upload service connected");
965 mUploaderBinder = (FileUploaderBinder) service;
966 } else {
967 return;
968 }
969 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
970 mFileList.listDirectory();
971 if (mDualPane) {
972 FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
973 if (fragment != null)
974 fragment.updateFileDetails();
975 }
976
977 }
978
979 @Override
980 public void onServiceDisconnected(ComponentName component) {
981 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
982 Log.d(TAG, "Download service disconnected");
983 mDownloaderBinder = null;
984 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
985 Log.d(TAG, "Upload service disconnected");
986 mUploaderBinder = null;
987 }
988 }
989 };
990
991
992
993 /**
994 * Launch an intent to request the PIN code to the user before letting him use the app
995 */
996 private void requestPinCode() {
997 boolean pinStart = false;
998 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
999 pinStart = appPrefs.getBoolean("set_pincode", false);
1000 if (pinStart) {
1001 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1002 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1003 startActivity(i);
1004 }
1005 }
1006
1007
1008 }