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