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