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