9fb3151926d6fab5365a9e0a99bd0c594456f4c0
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
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 import java.io.IOException;
23
24 import android.accounts.Account;
25 import android.accounts.AuthenticatorException;
26 import android.accounts.OperationCanceledException;
27 import android.app.AlertDialog;
28 import android.app.ProgressDialog;
29 import android.app.Dialog;
30 import android.content.BroadcastReceiver;
31 import android.content.ComponentName;
32 import android.content.ContentResolver;
33 import android.content.Context;
34 import android.content.DialogInterface;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.ServiceConnection;
38 import android.content.SharedPreferences;
39 import android.content.res.Resources.NotFoundException;
40 import android.database.Cursor;
41 import android.net.Uri;
42 import android.os.Bundle;
43 import android.os.Handler;
44 import android.os.IBinder;
45 import android.preference.PreferenceManager;
46 import android.provider.MediaStore;
47 import android.support.v4.app.Fragment;
48 import android.support.v4.app.FragmentManager;
49 import android.support.v4.app.FragmentTransaction;
50 import android.util.Log;
51 import android.view.View;
52 import android.view.ViewGroup;
53 import android.widget.ArrayAdapter;
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.view.Menu;
60 import com.actionbarsherlock.view.MenuInflater;
61 import com.actionbarsherlock.view.MenuItem;
62 import com.actionbarsherlock.view.Window;
63 import com.owncloud.android.Log_OC;
64 import com.owncloud.android.R;
65 import com.owncloud.android.authentication.AccountAuthenticator;
66 import com.owncloud.android.authentication.AccountUtils;
67 import com.owncloud.android.authentication.AccountUtils.AccountNotFoundException;
68 import com.owncloud.android.datamodel.DataStorageManager;
69 import com.owncloud.android.datamodel.FileDataStorageManager;
70 import com.owncloud.android.datamodel.OCFile;
71 import com.owncloud.android.files.services.FileDownloader;
72 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
73 import com.owncloud.android.files.services.FileObserverService;
74 import com.owncloud.android.files.services.FileUploader;
75 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
76 import com.owncloud.android.network.OwnCloudClientUtils;
77 import com.owncloud.android.operations.CreateFolderOperation;
78 import com.owncloud.android.operations.OnRemoteOperationListener;
79 import com.owncloud.android.operations.RemoteOperation;
80 import com.owncloud.android.operations.RemoteOperationResult;
81 import com.owncloud.android.operations.RemoveFileOperation;
82 import com.owncloud.android.operations.RenameFileOperation;
83 import com.owncloud.android.operations.SynchronizeFileOperation;
84 import com.owncloud.android.operations.SynchronizeFolderOperation;
85 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
86 import com.owncloud.android.syncadapter.FileSyncService;
87 import com.owncloud.android.ui.dialog.EditNameDialog;
88 import com.owncloud.android.ui.dialog.LoadingDialog;
89 import com.owncloud.android.ui.dialog.SslValidatorDialog;
90 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
91 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
92 import com.owncloud.android.ui.fragment.FileDetailFragment;
93 import com.owncloud.android.ui.fragment.FileFragment;
94 import com.owncloud.android.ui.fragment.OCFileListFragment;
95 import com.owncloud.android.ui.preview.PreviewImageActivity;
96 import com.owncloud.android.ui.preview.PreviewMediaFragment;
97 import com.owncloud.android.ui.preview.PreviewVideoActivity;
98
99 import eu.alefzero.webdav.WebdavClient;
100
101 /**
102 * Displays, what files the user has available in his ownCloud.
103 *
104 * @author Bartek Przybylski
105 * @author David A. Velasco
106 */
107
108 public class FileDisplayActivity extends FileActivity implements
109 OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener, OnRemoteOperationListener, EditNameDialogListener {
110
111 private ArrayAdapter<String> mDirectories;
112
113 /** Access point to the cached database for the current ownCloud {@link Account} */
114 private DataStorageManager mStorageManager = null;
115
116 private SyncBroadcastReceiver mSyncBroadcastReceiver;
117 private UploadFinishReceiver mUploadFinishReceiver;
118 private DownloadFinishReceiver mDownloadFinishReceiver;
119 private FileDownloaderBinder mDownloaderBinder = null;
120 private FileUploaderBinder mUploaderBinder = null;
121 private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
122 private RemoteOperationResult mLastSslUntrustedServerResult = null;
123
124 private boolean mDualPane;
125 private View mLeftFragmentContainer;
126 private View mRightFragmentContainer;
127
128 private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
129
130 public static final int DIALOG_SHORT_WAIT = 0;
131 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
132 private static final int DIALOG_SSL_VALIDATOR = 2;
133 private static final int DIALOG_CERT_NOT_SAVED = 3;
134
135 private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
136
137 public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
138
139 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
140 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
141
142 private static final String TAG = FileDisplayActivity.class.getSimpleName();
143
144 private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
145 private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
146
147 private OCFile mWaitingToPreview;
148 private Handler mHandler;
149
150 @Override
151 protected void onCreate(Bundle savedInstanceState) {
152 Log_OC.d(TAG, "onCreate() start");
153 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
154
155 super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
156
157 mHandler = new Handler();
158
159 /// bindings to transference services
160 mUploadConnection = new ListServiceConnection();
161 mDownloadConnection = new ListServiceConnection();
162 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
163 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
164
165 // PIN CODE request ; best location is to decide, let's try this first
166 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
167 requestPinCode();
168 }
169
170 /// file observer
171 Intent observer_intent = new Intent(this, FileObserverService.class);
172 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
173 startService(observer_intent);
174
175 /// Load of saved instance state
176 if(savedInstanceState != null) {
177 mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
178
179 } else {
180 mWaitingToPreview = null;
181 }
182
183 /// USER INTERFACE
184
185 // Inflate and set the layout view
186 setContentView(R.layout.files);
187 mDualPane = getResources().getBoolean(R.bool.large_land_layout);
188 mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
189 mRightFragmentContainer = findViewById(R.id.right_fragment_container);
190 if (savedInstanceState == null) {
191 createMinFragments();
192 }
193
194 // Action bar setup
195 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
196 getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
197 setSupportProgressBarIndeterminateVisibility(false); // always AFTER setContentView(...) ; to work around bug in its implementation
198
199 Log_OC.d(TAG, "onCreate() end");
200 }
201
202
203 @Override
204 protected void onDestroy() {
205 super.onDestroy();
206 if (mDownloadConnection != null)
207 unbindService(mDownloadConnection);
208 if (mUploadConnection != null)
209 unbindService(mUploadConnection);
210 }
211
212
213 /**
214 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
215 */
216 @Override
217 protected void onAccountSet(boolean stateWasRecovered) {
218 if (getAccount() != null) {
219 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
220
221 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
222 OCFile file = getFile();
223 if (file != null) {
224 if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
225 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
226 if (mStorageManager.getFileById(file.getParentId()) == null) {
227 file = null; // not able to know the directory where the file is uploading
228 }
229 } else {
230 file = mStorageManager.getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
231 }
232 }
233 if (file == null) {
234 // fall back to root folder
235 file = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR); // never returns null
236 }
237 setFile(file);
238 mDirectories.clear();
239 OCFile fileIt = file;
240 while(fileIt != null && fileIt.getFileName() != OCFile.PATH_SEPARATOR) {
241 if (fileIt.isDirectory()) {
242 mDirectories.add(fileIt.getFileName());
243 }
244 fileIt = mStorageManager.getFileById(fileIt.getParentId());
245 }
246 mDirectories.add(OCFile.PATH_SEPARATOR);
247 if (!stateWasRecovered) {
248 Log_OC.e(TAG, "Initializing Fragments in onAccountChanged..");
249 initFragmentsWithFile();
250
251 } else {
252 updateFragmentsVisibility(!file.isDirectory());
253 updateNavigationElementsInActionBar(file.isDirectory() ? null : file);
254 }
255
256
257 } else {
258 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
259 }
260 }
261
262
263 private void createMinFragments() {
264 OCFileListFragment listOfFiles = new OCFileListFragment();
265 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
266 transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
267 transaction.commit();
268 }
269
270 private void initFragmentsWithFile() {
271 if (getAccount() != null && getFile() != null) {
272 /// First fragment
273 OCFileListFragment listOfFiles = getListOfFilesFragment();
274 if (listOfFiles != null) {
275 listOfFiles.listDirectory(getCurrentDir());
276 } else {
277 Log.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
278 }
279
280 /// Second fragment
281 OCFile file = getFile();
282 Fragment secondFragment = chooseInitialSecondFragment(file);
283 if (secondFragment != null) {
284 setSecondFragment(secondFragment);
285 updateFragmentsVisibility(true);
286 updateNavigationElementsInActionBar(file);
287
288 } else {
289 cleanSecondFragment();
290 }
291
292 } else {
293 Log.wtf(TAG, "initFragments() called with invalid NULLs!");
294 if (getAccount() == null) {
295 Log.wtf(TAG, "\t account is NULL");
296 }
297 if (getFile() == null) {
298 Log.wtf(TAG, "\t file is NULL");
299 }
300 }
301 }
302
303 private Fragment chooseInitialSecondFragment(OCFile file) {
304 Fragment secondFragment = null;
305 if (file != null && !file.isDirectory()) {
306 if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
307 && file.getLastSyncDateForProperties() > 0 // temporal fix
308 ) {
309 int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
310 boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
311 secondFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
312
313 } else {
314 secondFragment = new FileDetailFragment(file, getAccount());
315 }
316 }
317 return secondFragment;
318 }
319
320
321 /**
322 * Replaces the second fragment managed by the activity with the received as
323 * a parameter.
324 *
325 * Assumes never will be more than two fragments managed at the same time.
326 *
327 * @param fragment New second Fragment to set.
328 */
329 private void setSecondFragment(Fragment fragment) {
330 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
331 transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
332 transaction.commit();
333 }
334
335
336 private void updateFragmentsVisibility(boolean existsSecondFragment) {
337 if (mDualPane) {
338 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
339 mLeftFragmentContainer.setVisibility(View.VISIBLE);
340 }
341 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
342 mRightFragmentContainer.setVisibility(View.VISIBLE);
343 }
344
345 } else if (existsSecondFragment) {
346 if (mLeftFragmentContainer.getVisibility() != View.GONE) {
347 mLeftFragmentContainer.setVisibility(View.GONE);
348 }
349 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
350 mRightFragmentContainer.setVisibility(View.VISIBLE);
351 }
352
353 } else {
354 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
355 mLeftFragmentContainer.setVisibility(View.VISIBLE);
356 }
357 if (mRightFragmentContainer.getVisibility() != View.GONE) {
358 mRightFragmentContainer.setVisibility(View.GONE);
359 }
360 }
361 }
362
363
364 private OCFileListFragment getListOfFilesFragment() {
365 Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES);
366 if (listOfFiles != null) {
367 return (OCFileListFragment)listOfFiles;
368 }
369 Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
370 return null;
371 }
372
373 protected FileFragment getSecondFragment() {
374 Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
375 if (second != null) {
376 return (FileFragment)second;
377 }
378 return null;
379 }
380
381 public void cleanSecondFragment() {
382 Fragment second = getSecondFragment();
383 if (second != null) {
384 FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
385 tr.remove(second);
386 tr.commit();
387 }
388 updateFragmentsVisibility(false);
389 updateNavigationElementsInActionBar(null);
390 }
391
392 protected void refeshListOfFilesFragment() {
393 OCFileListFragment fileListFragment = getListOfFilesFragment();
394 if (fileListFragment != null) {
395 fileListFragment.listDirectory();
396 }
397 }
398
399 protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath, boolean success) {
400 FileFragment secondFragment = getSecondFragment();
401 boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
402 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
403 FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
404 OCFile fileInFragment = detailsFragment.getFile();
405 if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
406 // the user browsed to other file ; forget the automatic preview
407 mWaitingToPreview = null;
408
409 } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_ADDED_MESSAGE)) {
410 // grant that the right panel updates the progress bar
411 detailsFragment.listenForTransferProgress();
412 detailsFragment.updateFileDetails(true, false);
413
414 } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
415 // update the right panel
416 boolean detailsFragmentChanged = false;
417 if (waitedPreview) {
418 if (success) {
419 mWaitingToPreview = mStorageManager.getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
420 if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
421 startMediaPreview(mWaitingToPreview, 0, true);
422 detailsFragmentChanged = true;
423 } else {
424 openFile(mWaitingToPreview);
425 }
426 }
427 mWaitingToPreview = null;
428 }
429 if (!detailsFragmentChanged) {
430 detailsFragment.updateFileDetails(false, (success));
431 }
432 }
433 }
434 }
435
436
437 @Override
438 public boolean onCreateOptionsMenu(Menu menu) {
439 MenuInflater inflater = getSherlock().getMenuInflater();
440 inflater.inflate(R.menu.main_menu, menu);
441 return true;
442 }
443
444 @Override
445 public boolean onOptionsItemSelected(MenuItem item) {
446 boolean retval = true;
447 switch (item.getItemId()) {
448 case R.id.action_create_dir: {
449 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.uploader_info_dirname), "", -1, -1, this);
450 dialog.show(getSupportFragmentManager(), "createdirdialog");
451 break;
452 }
453 case R.id.action_sync_account: {
454 startSynchronization();
455 break;
456 }
457 case R.id.action_upload: {
458 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
459 break;
460 }
461 case R.id.action_settings: {
462 Intent settingsIntent = new Intent(this, Preferences.class);
463 startActivity(settingsIntent);
464 break;
465 }
466 case android.R.id.home: {
467 FileFragment second = getSecondFragment();
468 OCFile currentDir = getCurrentDir();
469 if((currentDir != null && currentDir.getParentId() != 0) ||
470 (second != null && second.getFile() != null)) {
471 onBackPressed();
472
473 }
474 break;
475 }
476 default:
477 retval = super.onOptionsItemSelected(item);
478 }
479 return retval;
480 }
481
482 private void startSynchronization() {
483 ContentResolver.cancelSync(null, AccountAuthenticator.AUTHORITY); // cancel the current synchronizations of any ownCloud account
484 Bundle bundle = new Bundle();
485 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
486 ContentResolver.requestSync(
487 getAccount(),
488 AccountAuthenticator.AUTHORITY, bundle);
489 }
490
491
492 @Override
493 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
494 int i = itemPosition;
495 while (i-- != 0) {
496 onBackPressed();
497 }
498 // the next operation triggers a new call to this method, but it's necessary to
499 // ensure that the name exposed in the action bar is the current directory when the
500 // user selected it in the navigation list
501 if (itemPosition != 0)
502 getSupportActionBar().setSelectedNavigationItem(0);
503 return true;
504 }
505
506 /**
507 * Called, when the user selected something for uploading
508 */
509 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
510 super.onActivityResult(requestCode, resultCode, data);
511
512 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
513 requestSimpleUpload(data, resultCode);
514
515 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
516 requestMultipleUpload(data, resultCode);
517
518 }
519 }
520
521 private void requestMultipleUpload(Intent data, int resultCode) {
522 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
523 if (filePaths != null) {
524 String[] remotePaths = new String[filePaths.length];
525 String remotePathBase = "";
526 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
527 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
528 }
529 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
530 remotePathBase += OCFile.PATH_SEPARATOR;
531 for (int j = 0; j< remotePaths.length; j++) {
532 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
533 }
534
535 Intent i = new Intent(this, FileUploader.class);
536 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
537 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
538 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
539 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
540 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
541 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
542 startService(i);
543
544 } else {
545 Log_OC.d(TAG, "User clicked on 'Update' with no selection");
546 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
547 t.show();
548 return;
549 }
550 }
551
552
553 private void requestSimpleUpload(Intent data, int resultCode) {
554 String filepath = null;
555 try {
556 Uri selectedImageUri = data.getData();
557
558 String filemanagerstring = selectedImageUri.getPath();
559 String selectedImagePath = getPath(selectedImageUri);
560
561 if (selectedImagePath != null)
562 filepath = selectedImagePath;
563 else
564 filepath = filemanagerstring;
565
566 } catch (Exception e) {
567 Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
568 e.printStackTrace();
569
570 } finally {
571 if (filepath == null) {
572 Log_OC.e(TAG, "Couldnt resolve path to file");
573 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
574 t.show();
575 return;
576 }
577 }
578
579 Intent i = new Intent(this, FileUploader.class);
580 i.putExtra(FileUploader.KEY_ACCOUNT,
581 getAccount());
582 String remotepath = new String();
583 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
584 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
585 }
586 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
587 remotepath += OCFile.PATH_SEPARATOR;
588 remotepath += new File(filepath).getName();
589
590 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
591 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
592 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
593 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
594 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
595 startService(i);
596 }
597
598 @Override
599 public void onBackPressed() {
600 OCFileListFragment listOfFiles = getListOfFilesFragment();
601 if (mDualPane || getSecondFragment() == null) {
602 if (listOfFiles != null) { // should never be null, indeed
603 if (mDirectories.getCount() <= 1) {
604 finish();
605 return;
606 }
607 popDirname();
608 listOfFiles.onBrowseUp();
609 }
610 }
611 if (listOfFiles != null) { // should never be null, indeed
612 setFile(listOfFiles.getCurrentFile());
613 }
614 cleanSecondFragment();
615 }
616
617 @Override
618 protected void onSaveInstanceState(Bundle outState) {
619 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
620 Log_OC.e(TAG, "onSaveInstanceState() start");
621 super.onSaveInstanceState(outState);
622 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
623 Log_OC.d(TAG, "onSaveInstanceState() end");
624 }
625
626
627
628 @Override
629 protected void onResume() {
630 super.onResume();
631 Log_OC.e(TAG, "onResume() start");
632
633 // Listen for sync messages
634 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
635 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
636 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
637
638 // Listen for upload messages
639 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
640 mUploadFinishReceiver = new UploadFinishReceiver();
641 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
642
643 // Listen for download messages
644 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
645 downloadIntentFilter.addAction(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
646 mDownloadFinishReceiver = new DownloadFinishReceiver();
647 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
648
649 Log_OC.d(TAG, "onResume() end");
650 }
651
652
653 @Override
654 protected void onPause() {
655 super.onPause();
656 Log_OC.e(TAG, "onPause() start");
657 if (mSyncBroadcastReceiver != null) {
658 unregisterReceiver(mSyncBroadcastReceiver);
659 mSyncBroadcastReceiver = null;
660 }
661 if (mUploadFinishReceiver != null) {
662 unregisterReceiver(mUploadFinishReceiver);
663 mUploadFinishReceiver = null;
664 }
665 if (mDownloadFinishReceiver != null) {
666 unregisterReceiver(mDownloadFinishReceiver);
667 mDownloadFinishReceiver = null;
668 }
669
670 Log_OC.d(TAG, "onPause() end");
671 }
672
673
674 @Override
675 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
676 if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {
677 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
678 }
679 }
680
681
682 @Override
683 protected Dialog onCreateDialog(int id) {
684 Dialog dialog = null;
685 AlertDialog.Builder builder;
686 switch (id) {
687 case DIALOG_SHORT_WAIT: {
688 ProgressDialog working_dialog = new ProgressDialog(this);
689 working_dialog.setMessage(getResources().getString(
690 R.string.wait_a_moment));
691 working_dialog.setIndeterminate(true);
692 working_dialog.setCancelable(false);
693 dialog = working_dialog;
694 break;
695 }
696 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
697
698 String[] items = null;
699
700 String[] allTheItems = { getString(R.string.actionbar_upload_files),
701 getString(R.string.actionbar_upload_from_apps),
702 getString(R.string.actionbar_failed_instant_upload) };
703
704 String[] commonItems = { getString(R.string.actionbar_upload_files),
705 getString(R.string.actionbar_upload_from_apps) };
706
707 if (InstantUploadActivity.IS_ENABLED)
708 items = allTheItems;
709 else
710 items = commonItems;
711
712 builder = new AlertDialog.Builder(this);
713 builder.setTitle(R.string.actionbar_upload);
714 builder.setItems(items, new DialogInterface.OnClickListener() {
715 public void onClick(DialogInterface dialog, int item) {
716 if (item == 0) {
717 // if (!mDualPane) {
718 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
719 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
720 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
721 // } else {
722 // TODO create and handle new fragment
723 // LocalFileListFragment
724 // }
725 } else if (item == 1) {
726 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
727 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
728 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
729 ACTION_SELECT_CONTENT_FROM_APPS);
730 } else if (item == 2 && InstantUploadActivity.IS_ENABLED) {
731 Intent action = new Intent(FileDisplayActivity.this, InstantUploadActivity.class);
732 action.putExtra(FileUploader.KEY_ACCOUNT, FileDisplayActivity.this.getAccount());
733 startActivity(action);
734 }
735 }
736 });
737 dialog = builder.create();
738 break;
739 }
740 case DIALOG_SSL_VALIDATOR: {
741 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
742 break;
743 }
744 case DIALOG_CERT_NOT_SAVED: {
745 builder = new AlertDialog.Builder(this);
746 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
747 builder.setCancelable(false);
748 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
749 @Override
750 public void onClick(DialogInterface dialog, int which) {
751 dialog.dismiss();
752 };
753 });
754 dialog = builder.create();
755 break;
756 }
757 default:
758 dialog = null;
759 }
760
761 return dialog;
762 }
763
764
765 /**
766 * Show loading dialog
767 */
768 public void showLoadingDialog() {
769 // Construct dialog
770 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
771 FragmentManager fm = getSupportFragmentManager();
772 FragmentTransaction ft = fm.beginTransaction();
773 loading.show(ft, DIALOG_WAIT_TAG);
774
775 }
776
777 /**
778 * Dismiss loading dialog
779 */
780 public void dismissLoadingDialog(){
781 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
782 if (frag != null) {
783 LoadingDialog loading = (LoadingDialog) frag;
784 loading.dismiss();
785 }
786 }
787
788
789 /**
790 * Translates a content URI of an image to a physical path
791 * on the disk
792 * @param uri The URI to resolve
793 * @return The path to the image or null if it could not be found
794 */
795 public String getPath(Uri uri) {
796 String[] projection = { MediaStore.Images.Media.DATA };
797 Cursor cursor = managedQuery(uri, projection, null, null, null);
798 if (cursor != null) {
799 int column_index = cursor
800 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
801 cursor.moveToFirst();
802 return cursor.getString(column_index);
803 }
804 return null;
805 }
806
807 /**
808 * Pushes a directory to the drop down list
809 * @param directory to push
810 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
811 */
812 public void pushDirname(OCFile directory) {
813 if(!directory.isDirectory()){
814 throw new IllegalArgumentException("Only directories may be pushed!");
815 }
816 mDirectories.insert(directory.getFileName(), 0);
817 setFile(directory);
818 }
819
820 /**
821 * Pops a directory name from the drop down list
822 * @return True, unless the stack is empty
823 */
824 public boolean popDirname() {
825 mDirectories.remove(mDirectories.getItem(0));
826 return !mDirectories.isEmpty();
827 }
828
829 // Custom array adapter to override text colors
830 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
831
832 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
833 super(ctx, view);
834 }
835
836 public View getView(int position, View convertView, ViewGroup parent) {
837 View v = super.getView(position, convertView, parent);
838
839 ((TextView) v).setTextColor(getResources().getColorStateList(
840 android.R.color.white));
841 return v;
842 }
843
844 public View getDropDownView(int position, View convertView,
845 ViewGroup parent) {
846 View v = super.getDropDownView(position, convertView, parent);
847
848 ((TextView) v).setTextColor(getResources().getColorStateList(
849 android.R.color.white));
850
851 return v;
852 }
853
854 }
855
856 private class SyncBroadcastReceiver extends BroadcastReceiver {
857
858 /**
859 * {@link BroadcastReceiver} to enable syncing feedback in UI
860 */
861 @Override
862 public void onReceive(Context context, Intent intent) {
863 boolean inProgress = intent.getBooleanExtra(FileSyncService.IN_PROGRESS, false);
864 String accountName = intent.getStringExtra(FileSyncService.ACCOUNT_NAME);
865
866 Log_OC.d(TAG, "sync of account " + accountName + " is in_progress: " + inProgress);
867
868 if (getAccount() != null && accountName.equals(getAccount().name)) {
869
870 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
871
872 boolean fillBlankRoot = false;
873 OCFile currentDir = getCurrentDir();
874 if (currentDir == null) {
875 currentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
876 fillBlankRoot = (currentDir != null);
877 }
878
879 if ((synchFolderRemotePath != null && currentDir != null && (currentDir.getRemotePath().equals(synchFolderRemotePath)))
880 || fillBlankRoot ) {
881 if (!fillBlankRoot)
882 currentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
883 OCFileListFragment fileListFragment = getListOfFilesFragment();
884 if (fileListFragment != null) {
885 fileListFragment.listDirectory(currentDir);
886 }
887 if (getSecondFragment() == null)
888 setFile(currentDir);
889 }
890
891 setSupportProgressBarIndeterminateVisibility(inProgress);
892 removeStickyBroadcast(intent);
893
894 }
895
896 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT);
897 if (synchResult != null) {
898 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
899 mLastSslUntrustedServerResult = synchResult;
900 showDialog(DIALOG_SSL_VALIDATOR);
901 }
902 }
903 }
904 }
905
906
907 private class UploadFinishReceiver extends BroadcastReceiver {
908 /**
909 * Once the file upload has finished -> update view
910 * @author David A. Velasco
911 * {@link BroadcastReceiver} to enable upload feedback in UI
912 */
913 @Override
914 public void onReceive(Context context, Intent intent) {
915 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
916 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
917 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
918 OCFile currentDir = getCurrentDir();
919 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
920 if (sameAccount && isDescendant) {
921 refeshListOfFilesFragment();
922 }
923 }
924
925 }
926
927
928 /**
929 * Class waiting for broadcast events from the {@link FielDownloader} service.
930 *
931 * Updates the UI when a download is started or finished, provided that it is relevant for the
932 * current folder.
933 */
934 private class DownloadFinishReceiver extends BroadcastReceiver {
935 @Override
936 public void onReceive(Context context, Intent intent) {
937 boolean sameAccount = isSameAccount(context, intent);
938 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
939 boolean isDescendant = isDescendant(downloadedRemotePath);
940
941 if (sameAccount && isDescendant) {
942 refeshListOfFilesFragment();
943 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
944 }
945
946 removeStickyBroadcast(intent);
947 }
948
949 private boolean isDescendant(String downloadedRemotePath) {
950 OCFile currentDir = getCurrentDir();
951 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
952 }
953
954 private boolean isSameAccount(Context context, Intent intent) {
955 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
956 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
957 }
958 }
959
960
961 /**
962 * {@inheritDoc}
963 */
964 @Override
965 public DataStorageManager getStorageManager() {
966 return mStorageManager;
967 }
968
969
970 /**
971 * {@inheritDoc}
972 *
973 * Updates action bar and second fragment, if in dual pane mode.
974 */
975 @Override
976 public void onBrowsedDownTo(OCFile directory) {
977 pushDirname(directory);
978 cleanSecondFragment();
979
980 // Sync Folder
981 startSyncFolderOperation(directory.getRemotePath(), directory.getFileId());
982 // // Update folder size on DB
983 // getStorageManager().calculateFolderSize(directory.getParentId());
984
985 }
986
987 /**
988 * Opens the image gallery showing the image {@link OCFile} received as parameter.
989 *
990 * @param file Image {@link OCFile} to show.
991 */
992 @Override
993 public void startImagePreview(OCFile file) {
994 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
995 showDetailsIntent.putExtra(EXTRA_FILE, file);
996 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
997 startActivity(showDetailsIntent);
998 }
999
1000 /**
1001 * Stars the preview of an already down media {@link OCFile}.
1002 *
1003 * @param file Media {@link OCFile} to preview.
1004 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1005 * @param autoplay When 'true', the playback will start without user interactions.
1006 */
1007 @Override
1008 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1009 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1010 setSecondFragment(mediaFragment);
1011 updateFragmentsVisibility(true);
1012 updateNavigationElementsInActionBar(file);
1013 setFile(file);
1014 }
1015
1016 /**
1017 * Requests the download of the received {@link OCFile} , updates the UI
1018 * to monitor the download progress and prepares the activity to preview
1019 * or open the file when the download finishes.
1020 *
1021 * @param file {@link OCFile} to download and preview.
1022 */
1023 @Override
1024 public void startDownloadForPreview(OCFile file) {
1025 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1026 setSecondFragment(detailFragment);
1027 mWaitingToPreview = file;
1028 requestForDownload();
1029 updateFragmentsVisibility(true);
1030 updateNavigationElementsInActionBar(file);
1031 setFile(file);
1032 }
1033
1034
1035 /**
1036 * Shows the information of the {@link OCFile} received as a
1037 * parameter in the second fragment.
1038 *
1039 * @param file {@link OCFile} whose details will be shown
1040 */
1041 @Override
1042 public void showDetails(OCFile file) {
1043 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1044 setSecondFragment(detailFragment);
1045 updateFragmentsVisibility(true);
1046 updateNavigationElementsInActionBar(file);
1047 setFile(file);
1048 }
1049
1050
1051 /**
1052 * TODO
1053 */
1054 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1055 ActionBar actionBar = getSupportActionBar();
1056 if (chosenFile == null || mDualPane) {
1057 // only list of files - set for browsing through folders
1058 OCFile currentDir = getCurrentDir();
1059 actionBar.setDisplayHomeAsUpEnabled(currentDir != null && currentDir.getParentId() != 0);
1060 actionBar.setDisplayShowTitleEnabled(false);
1061 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
1062 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1063
1064 } else {
1065 actionBar.setDisplayHomeAsUpEnabled(true);
1066 actionBar.setDisplayShowTitleEnabled(true);
1067 actionBar.setTitle(chosenFile.getFileName());
1068 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1069 }
1070 }
1071
1072
1073 /**
1074 * {@inheritDoc}
1075 */
1076 @Override
1077 public void onFileStateChanged() {
1078 refeshListOfFilesFragment();
1079 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1080 }
1081
1082
1083 /**
1084 * {@inheritDoc}
1085 */
1086 @Override
1087 public FileDownloaderBinder getFileDownloaderBinder() {
1088 return mDownloaderBinder;
1089 }
1090
1091
1092 /**
1093 * {@inheritDoc}
1094 */
1095 @Override
1096 public FileUploaderBinder getFileUploaderBinder() {
1097 return mUploaderBinder;
1098 }
1099
1100
1101 /** Defines callbacks for service binding, passed to bindService() */
1102 private class ListServiceConnection implements ServiceConnection {
1103
1104 @Override
1105 public void onServiceConnected(ComponentName component, IBinder service) {
1106 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1107 Log_OC.d(TAG, "Download service connected");
1108 mDownloaderBinder = (FileDownloaderBinder) service;
1109 if (mWaitingToPreview != null) {
1110 requestForDownload();
1111 }
1112
1113 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1114 Log_OC.d(TAG, "Upload service connected");
1115 mUploaderBinder = (FileUploaderBinder) service;
1116 } else {
1117 return;
1118 }
1119 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1120 OCFileListFragment listOfFiles = getListOfFilesFragment();
1121 if (listOfFiles != null) {
1122 listOfFiles.listDirectory();
1123 }
1124 FileFragment secondFragment = getSecondFragment();
1125 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1126 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1127 detailFragment.listenForTransferProgress();
1128 detailFragment.updateFileDetails(false, false);
1129 }
1130 }
1131
1132 @Override
1133 public void onServiceDisconnected(ComponentName component) {
1134 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1135 Log_OC.d(TAG, "Download service disconnected");
1136 mDownloaderBinder = null;
1137 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1138 Log_OC.d(TAG, "Upload service disconnected");
1139 mUploaderBinder = null;
1140 }
1141 }
1142 };
1143
1144
1145
1146 /**
1147 * Launch an intent to request the PIN code to the user before letting him use the app
1148 */
1149 private void requestPinCode() {
1150 boolean pinStart = false;
1151 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1152 pinStart = appPrefs.getBoolean("set_pincode", false);
1153 if (pinStart) {
1154 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1155 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1156 startActivity(i);
1157 }
1158 }
1159
1160
1161 @Override
1162 public void onSavedCertificate() {
1163 startSynchronization();
1164 }
1165
1166
1167 @Override
1168 public void onFailedSavingCertificate() {
1169 showDialog(DIALOG_CERT_NOT_SAVED);
1170 }
1171
1172
1173 /**
1174 * Updates the view associated to the activity after the finish of some operation over files
1175 * in the current account.
1176 *
1177 * @param operation Removal operation performed.
1178 * @param result Result of the removal.
1179 */
1180 @Override
1181 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1182 if (operation instanceof RemoveFileOperation) {
1183 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1184
1185 } else if (operation instanceof RenameFileOperation) {
1186 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1187
1188 } else if (operation instanceof SynchronizeFileOperation) {
1189 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1190
1191 } else if (operation instanceof CreateFolderOperation) {
1192 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1193
1194 } else if (operation instanceof SynchronizeFolderOperation) {
1195 onSynchronizeFolderOperationFinish((SynchronizeFolderOperation)operation, result);
1196 }
1197 }
1198
1199
1200 /**
1201 * Updates the view associated to the activity after the finish of an operation trying to synchronize a folder.
1202 *
1203 * @param operation Synchronize operation performed.
1204 * @param result Result of the synchronization.
1205 */
1206 private void onSynchronizeFolderOperationFinish(SynchronizeFolderOperation operation, RemoteOperationResult result) {
1207
1208 OCFileListFragment list = getListOfFilesFragment();
1209 enableDisableViewGroup(list.getListView(), true);
1210
1211 setSupportProgressBarIndeterminateVisibility(false);
1212 if (result.isSuccess()) {
1213 if (result.getCode() != ResultCode.OK_NO_CHANGES_ON_DIR) {
1214 DataStorageManager storageManager = getStorageManager();
1215 OCFile parentDir = storageManager.getFileByPath(operation.getRemotePath());
1216
1217 // Update folder size on DB
1218 getStorageManager().calculateFolderSize(parentDir.getFileId());
1219
1220 // Refrest List
1221 refreshListOfFilesFragment(parentDir);
1222 }
1223 } else {
1224 try {
1225 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1226 msg.show();
1227
1228 } catch (NotFoundException e) {
1229 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1230 }
1231 }
1232 }
1233
1234
1235 private void refreshListOfFilesFragment(OCFile parentDir) {
1236 OCFileListFragment fileListFragment = getListOfFilesFragment();
1237 if (fileListFragment != null) {
1238 fileListFragment.listDirectory(parentDir);
1239 }
1240 }
1241
1242
1243 /**
1244 * Updates the view associated to the activity after the finish of an operation trying to remove a
1245 * file.
1246 *
1247 * @param operation Removal operation performed.
1248 * @param result Result of the removal.
1249 */
1250 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1251 dismissLoadingDialog();
1252 if (result.isSuccess()) {
1253 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1254 msg.show();
1255 OCFile removedFile = operation.getFile();
1256 getSecondFragment();
1257 FileFragment second = getSecondFragment();
1258 if (second != null && removedFile.equals(second.getFile())) {
1259 cleanSecondFragment();
1260 }
1261 if (mStorageManager.getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1262 refeshListOfFilesFragment();
1263 }
1264
1265 } else {
1266 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1267 msg.show();
1268 if (result.isSslRecoverableException()) {
1269 mLastSslUntrustedServerResult = result;
1270 showDialog(DIALOG_SSL_VALIDATOR);
1271 }
1272 }
1273 }
1274
1275 /**
1276 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1277 *
1278 * @param operation Creation operation performed.
1279 * @param result Result of the creation.
1280 */
1281 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1282 if (result.isSuccess()) {
1283 dismissLoadingDialog();
1284 refeshListOfFilesFragment();
1285
1286 } else {
1287 //dismissDialog(DIALOG_SHORT_WAIT);
1288 dismissLoadingDialog();
1289 try {
1290 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
1291 msg.show();
1292
1293 } catch (NotFoundException e) {
1294 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1295 }
1296 }
1297 }
1298
1299
1300 /**
1301 * Updates the view associated to the activity after the finish of an operation trying to rename a
1302 * file.
1303 *
1304 * @param operation Renaming operation performed.
1305 * @param result Result of the renaming.
1306 */
1307 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1308 dismissLoadingDialog();
1309 OCFile renamedFile = operation.getFile();
1310 if (result.isSuccess()) {
1311 if (mDualPane) {
1312 FileFragment details = getSecondFragment();
1313 if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1314 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1315 }
1316 }
1317 if (mStorageManager.getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1318 refeshListOfFilesFragment();
1319 }
1320
1321 } else {
1322 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1323 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1324 msg.show();
1325 // TODO throw again the new rename dialog
1326 } else {
1327 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1328 msg.show();
1329 if (result.isSslRecoverableException()) {
1330 mLastSslUntrustedServerResult = result;
1331 showDialog(DIALOG_SSL_VALIDATOR);
1332 }
1333 }
1334 }
1335 }
1336
1337
1338 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1339 dismissLoadingDialog();
1340 OCFile syncedFile = operation.getLocalFile();
1341 if (!result.isSuccess()) {
1342 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1343 Intent i = new Intent(this, ConflictsResolveActivity.class);
1344 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1345 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1346 startActivity(i);
1347
1348 } else {
1349 Toast msg = Toast.makeText(this, R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1350 msg.show();
1351 }
1352
1353 } else {
1354 if (operation.transferWasRequested()) {
1355 refeshListOfFilesFragment();
1356 onTransferStateChanged(syncedFile, true, true);
1357
1358 } else {
1359 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1360 msg.show();
1361 }
1362 }
1363 }
1364
1365
1366 /**
1367 * {@inheritDoc}
1368 */
1369 @Override
1370 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1371 if (mDualPane) {
1372 FileFragment details = getSecondFragment();
1373 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1374 if (downloading || uploading) {
1375 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1376 } else {
1377 ((FileDetailFragment)details).updateFileDetails(false, true);
1378 }
1379 }
1380 }
1381 }
1382
1383
1384 public void onDismiss(EditNameDialog dialog) {
1385 if (dialog.getResult()) {
1386 String newDirectoryName = dialog.getNewFilename().trim();
1387 Log_OC.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
1388 if (newDirectoryName.length() > 0) {
1389 String path = getCurrentDir().getRemotePath();
1390
1391 // Create directory
1392 path += newDirectoryName + OCFile.PATH_SEPARATOR;
1393 RemoteOperation operation = new CreateFolderOperation(path, getCurrentDir().getFileId(), mStorageManager);
1394 operation.execute( getAccount(),
1395 FileDisplayActivity.this,
1396 FileDisplayActivity.this,
1397 mHandler,
1398 FileDisplayActivity.this);
1399
1400 showLoadingDialog();
1401 }
1402 }
1403 }
1404
1405
1406 private void requestForDownload() {
1407 Account account = getAccount();
1408 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1409 Intent i = new Intent(this, FileDownloader.class);
1410 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1411 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1412 startService(i);
1413 }
1414 }
1415
1416
1417 private OCFile getCurrentDir() {
1418 OCFile file = getFile();
1419 if (file != null) {
1420 if (file.isDirectory()) {
1421 return file;
1422 } else if (mStorageManager != null) {
1423 return mStorageManager.getFileById(file.getParentId());
1424 }
1425 }
1426 return null;
1427 }
1428
1429 public void startSyncFolderOperation(String remotePath, long parentId) {
1430 long currentSyncTime = System.currentTimeMillis();
1431
1432 OCFileListFragment list = getListOfFilesFragment();
1433 enableDisableViewGroup(list.getListView(), false);
1434
1435 // perform folder synchronization
1436 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( remotePath,
1437 currentSyncTime,
1438 parentId,
1439 getStorageManager(),
1440 getAccount(),
1441 getApplicationContext()
1442 );
1443 synchFolderOp.execute(getAccount(), this, this, mHandler, this);
1444
1445 setSupportProgressBarIndeterminateVisibility(true);
1446 }
1447
1448
1449 public void enableDisableViewGroup(ViewGroup viewGroup, boolean enabled) {
1450 int childCount = viewGroup.getChildCount();
1451 for (int i = 0; i < childCount; i++) {
1452 View view = viewGroup.getChildAt(i);
1453 view.setEnabled(enabled);
1454 view.setClickable(!enabled);
1455 if (view instanceof ViewGroup) {
1456 enableDisableViewGroup((ViewGroup) view, enabled);
1457 }
1458 }
1459 }
1460 }