1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
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.
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.
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/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import java
.io
.IOException
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AuthenticatorException
;
27 import android
.accounts
.OperationCanceledException
;
28 import android
.app
.AlertDialog
;
29 import android
.app
.Dialog
;
30 import android
.app
.ProgressDialog
;
31 import android
.content
.BroadcastReceiver
;
32 import android
.content
.ComponentName
;
33 import android
.content
.ContentResolver
;
34 import android
.content
.ContentUris
;
35 import android
.content
.Context
;
36 import android
.content
.DialogInterface
;
37 import android
.content
.Intent
;
38 import android
.content
.IntentFilter
;
39 import android
.content
.ServiceConnection
;
40 import android
.content
.SharedPreferences
;
41 import android
.content
.SyncRequest
;
42 import android
.content
.res
.Resources
.NotFoundException
;
43 import android
.database
.Cursor
;
44 import android
.net
.Uri
;
45 import android
.os
.Build
;
46 import android
.os
.Bundle
;
47 import android
.os
.Environment
;
48 import android
.os
.IBinder
;
49 import android
.preference
.PreferenceManager
;
50 import android
.provider
.DocumentsContract
;
51 import android
.provider
.MediaStore
;
52 import android
.provider
.OpenableColumns
;
53 import android
.support
.v4
.app
.Fragment
;
54 import android
.support
.v4
.app
.FragmentManager
;
55 import android
.support
.v4
.app
.FragmentTransaction
;
56 import android
.util
.Log
;
57 import android
.view
.View
;
58 import android
.view
.ViewGroup
;
59 import android
.widget
.ArrayAdapter
;
60 import android
.widget
.TextView
;
61 import android
.widget
.Toast
;
63 import com
.actionbarsherlock
.app
.ActionBar
;
64 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
65 import com
.actionbarsherlock
.view
.Menu
;
66 import com
.actionbarsherlock
.view
.MenuInflater
;
67 import com
.actionbarsherlock
.view
.MenuItem
;
68 import com
.actionbarsherlock
.view
.Window
;
69 import com
.owncloud
.android
.BuildConfig
;
70 import com
.owncloud
.android
.MainApp
;
71 import com
.owncloud
.android
.R
;
72 import com
.owncloud
.android
.datamodel
.OCFile
;
73 import com
.owncloud
.android
.files
.services
.FileDownloader
;
74 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
75 import com
.owncloud
.android
.files
.services
.FileUploader
;
76 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
78 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
79 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
80 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
81 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
82 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
83 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
84 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
85 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
86 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
87 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
88 import com
.owncloud
.android
.operations
.CreateShareOperation
;
89 import com
.owncloud
.android
.operations
.MoveFileOperation
;
90 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
91 import com
.owncloud
.android
.operations
.RenameFileOperation
;
92 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
93 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
94 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
95 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
96 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
97 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
;
98 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
99 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
100 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
101 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
102 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
103 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
105 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
106 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
107 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
108 import com
.owncloud
.android
.utils
.DisplayUtils
;
109 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
110 import com
.owncloud
.android
.utils
.UriUtils
;
114 * Displays, what files the user has available in his ownCloud.
116 * @author Bartek Przybylski
117 * @author David A. Velasco
120 public class FileDisplayActivity
extends HookActivity
implements
121 FileFragment
.ContainerActivity
, OnNavigationListener
,
122 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
124 private ArrayAdapter
<String
> mDirectories
;
126 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
127 private UploadFinishReceiver mUploadFinishReceiver
;
128 private DownloadFinishReceiver mDownloadFinishReceiver
;
129 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
131 private boolean mDualPane
;
132 private View mLeftFragmentContainer
;
133 private View mRightFragmentContainer
;
135 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
136 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
137 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
139 public static final int DIALOG_SHORT_WAIT
= 0;
140 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
141 private static final int DIALOG_CERT_NOT_SAVED
= 2;
143 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
145 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
146 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
147 public static final int ACTION_MOVE_FILES
= 3;
149 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
151 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
152 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
154 private OCFile mWaitingToPreview
;
156 private boolean mSyncInProgress
= false
;
158 private String DIALOG_UNTRUSTED_CERT
;
160 private OCFile mWaitingToSend
;
163 protected void onCreate(Bundle savedInstanceState
) {
164 Log_OC
.d(TAG
, "onCreate() start");
165 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
167 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
169 // PIN CODE request ; best location is to decide, let's try this first
170 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
172 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
176 /// grant that FileObserverService is watching favourite files
177 if (savedInstanceState
== null
) {
178 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
179 startService(initObserversIntent
);
182 /// Load of saved instance state
183 if(savedInstanceState
!= null
) {
184 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
185 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
186 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
189 mWaitingToPreview
= null
;
190 mSyncInProgress
= false
;
191 mWaitingToSend
= null
;
196 // Inflate and set the layout view
197 setContentView(R
.layout
.files
);
198 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
199 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
200 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
201 if (savedInstanceState
== null
) {
202 createMinFragments();
206 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
207 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
208 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
212 Log_OC
.d(TAG
, "onCreate() end");
216 protected void onStart() {
218 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
222 protected void onDestroy() {
227 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
230 protected void onAccountSet(boolean stateWasRecovered
) {
231 super.onAccountSet(stateWasRecovered
);
232 if (getAccount() != null
) {
233 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
234 OCFile file
= getFile();
235 // get parent from path
236 String parentPath
= "";
238 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
239 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
240 // get parent from path
241 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
242 if (getStorageManager().getFileByPath(parentPath
) == null
)
243 file
= null
; // not able to know the directory where the file is uploading
245 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
249 // fall back to root folder
250 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
253 setNavigationListWithFolder(file
);
255 if (!stateWasRecovered
) {
256 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
257 initFragmentsWithFile();
258 if (file
.isFolder()) {
259 startSyncFolderOperation(file
, false
);
263 updateFragmentsVisibility(!file
.isFolder());
264 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
270 private void setNavigationListWithFolder(OCFile file
) {
271 mDirectories
.clear();
272 OCFile fileIt
= file
;
274 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
275 if (fileIt
.isFolder()) {
276 mDirectories
.add(fileIt
.getFileName());
278 // get parent from path
279 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
280 fileIt
= getStorageManager().getFileByPath(parentPath
);
282 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
286 private void createMinFragments() {
287 OCFileListFragment listOfFiles
= new OCFileListFragment();
288 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
289 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
290 transaction
.commit();
293 private void initFragmentsWithFile() {
294 if (getAccount() != null
&& getFile() != null
) {
296 OCFileListFragment listOfFiles
= getListOfFilesFragment();
297 if (listOfFiles
!= null
) {
298 listOfFiles
.listDirectory(getCurrentDir());
300 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
304 OCFile file
= getFile();
305 Fragment secondFragment
= chooseInitialSecondFragment(file
);
306 if (secondFragment
!= null
) {
307 setSecondFragment(secondFragment
);
308 updateFragmentsVisibility(true
);
309 updateNavigationElementsInActionBar(file
);
312 cleanSecondFragment();
316 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
317 if (getAccount() == null
) {
318 Log_OC
.wtf(TAG
, "\t account is NULL");
320 if (getFile() == null
) {
321 Log_OC
.wtf(TAG
, "\t file is NULL");
326 private Fragment
chooseInitialSecondFragment(OCFile file
) {
327 Fragment secondFragment
= null
;
328 if (file
!= null
&& !file
.isFolder()) {
329 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
330 && file
.getLastSyncDateForProperties() > 0 // temporal fix
332 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
333 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
334 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
337 secondFragment
= new FileDetailFragment(file
, getAccount());
340 return secondFragment
;
345 * Replaces the second fragment managed by the activity with the received as
348 * Assumes never will be more than two fragments managed at the same time.
350 * @param fragment New second Fragment to set.
352 private void setSecondFragment(Fragment fragment
) {
353 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
354 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
355 transaction
.commit();
359 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
361 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
362 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
364 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
365 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
368 } else if (existsSecondFragment
) {
369 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
370 mLeftFragmentContainer
.setVisibility(View
.GONE
);
372 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
373 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
377 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
378 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
380 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
381 mRightFragmentContainer
.setVisibility(View
.GONE
);
387 private OCFileListFragment
getListOfFilesFragment() {
388 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
389 if (listOfFiles
!= null
) {
390 return (OCFileListFragment
)listOfFiles
;
392 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
396 public FileFragment
getSecondFragment() {
397 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
398 if (second
!= null
) {
399 return (FileFragment
)second
;
404 protected void cleanSecondFragment() {
405 Fragment second
= getSecondFragment();
406 if (second
!= null
) {
407 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
411 updateFragmentsVisibility(false
);
412 updateNavigationElementsInActionBar(null
);
415 protected void refreshListOfFilesFragment() {
416 OCFileListFragment fileListFragment
= getListOfFilesFragment();
417 if (fileListFragment
!= null
) {
418 fileListFragment
.listDirectory();
422 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
423 FileFragment secondFragment
= getSecondFragment();
424 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
425 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
426 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
427 OCFile fileInFragment
= detailsFragment
.getFile();
428 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
429 // the user browsed to other file ; forget the automatic preview
430 mWaitingToPreview
= null
;
432 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
433 // grant that the right panel updates the progress bar
434 detailsFragment
.listenForTransferProgress();
435 detailsFragment
.updateFileDetails(true
, false
);
437 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
438 // update the right panel
439 boolean detailsFragmentChanged
= false
;
442 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
443 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
444 startMediaPreview(mWaitingToPreview
, 0, true
);
445 detailsFragmentChanged
= true
;
447 getFileOperationsHelper().openFile(mWaitingToPreview
);
450 mWaitingToPreview
= null
;
452 if (!detailsFragmentChanged
) {
453 detailsFragment
.updateFileDetails(false
, (success
));
460 public boolean onPrepareOptionsMenu(Menu menu
) {
461 if (BuildConfig
.DEBUG
) {
462 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
464 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
466 return super.onPrepareOptionsMenu(menu
);
470 public boolean onCreateOptionsMenu(Menu menu
) {
471 MenuInflater inflater
= getSherlock().getMenuInflater();
472 inflater
.inflate(R
.menu
.main_menu
, menu
);
477 public boolean onOptionsItemSelected(MenuItem item
) {
478 boolean retval
= true
;
479 switch (item
.getItemId()) {
480 case R
.id
.action_create_dir
: {
481 CreateFolderDialogFragment dialog
=
482 CreateFolderDialogFragment
.newInstance(getCurrentDir());
483 dialog
.show(getSupportFragmentManager(), "createdirdialog");
486 case R
.id
.action_sync_account
: {
487 startSynchronization();
490 case R
.id
.action_upload
: {
491 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
494 case R
.id
.action_settings
: {
495 Intent settingsIntent
= new Intent(this, Preferences
.class);
496 startActivity(settingsIntent
);
499 case R
.id
.action_logger
: {
500 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
501 startActivity(loggerIntent
);
504 case android
.R
.id
.home
: {
505 FileFragment second
= getSecondFragment();
506 OCFile currentDir
= getCurrentDir();
507 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
508 (second
!= null
&& second
.getFile() != null
)) {
514 case R
.id
.action_sort
: {
515 SharedPreferences appPreferences
= PreferenceManager
516 .getDefaultSharedPreferences(this);
518 // Read sorting order, default to sort by name ascending
519 Integer sortOrder
= appPreferences
520 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
522 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
523 builder
.setTitle(R
.string
.actionbar_sort_title
)
524 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
525 public void onClick(DialogInterface dialog
, int which
) {
535 // TODO re-enable when server-side folder size calculation is available
537 // sortBySize(false);
545 builder
.create().show();
549 retval
= super.onOptionsItemSelected(item
);
554 private void startSynchronization() {
555 Log_OC
.e(TAG
, "Got to start sync");
556 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
557 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
558 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
559 Bundle bundle
= new Bundle();
560 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
561 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
562 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
563 ContentResolver
.requestSync(
565 MainApp
.getAuthority(), bundle
);
567 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
568 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
569 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
570 builder
.setExpedited(true
);
571 builder
.setManual(true
);
573 SyncRequest request
= builder
.build();
574 ContentResolver
.requestSync(request
);
580 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
581 if (itemPosition
!= 0) {
582 String targetPath
= "";
583 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
584 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
586 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
587 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
588 if (targetFolder
!= null
) {
589 browseTo(targetFolder
);
592 // the next operation triggers a new call to this method, but it's necessary to
593 // ensure that the name exposed in the action bar is the current directory when the
594 // user selected it in the navigation list
595 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
596 getSupportActionBar().setSelectedNavigationItem(0);
602 * Called, when the user selected something for uploading
604 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
605 super.onActivityResult(requestCode
, resultCode
, data
);
607 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
608 requestSimpleUpload(data
, resultCode
);
610 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
611 requestMultipleUpload(data
, resultCode
);
613 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
614 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)){
616 final Intent fData
= data
;
617 final int fResultCode
= resultCode
;
618 getHandler().postDelayed(
622 requestMoveOperation(fData
, fResultCode
);
625 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
630 private void requestMultipleUpload(Intent data
, int resultCode
) {
631 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
632 if (filePaths
!= null
) {
633 String
[] remotePaths
= new String
[filePaths
.length
];
634 String remotePathBase
= "";
635 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
636 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
638 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
639 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
640 for (int j
= 0; j
< remotePaths
.length
; j
++) {
641 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
644 Intent i
= new Intent(this, FileUploader
.class);
645 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
646 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
647 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
648 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
649 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
650 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
654 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
655 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
662 private void requestSimpleUpload(Intent data
, int resultCode
) {
663 String filepath
= null
;
664 String mimeType
= null
;
666 Uri selectedImageUri
= data
.getData();
669 mimeType
= getContentResolver().getType(selectedImageUri
);
671 String filemanagerstring
= selectedImageUri
.getPath();
672 String selectedImagePath
= getPath(selectedImageUri
);
674 if (selectedImagePath
!= null
)
675 filepath
= selectedImagePath
;
677 filepath
= filemanagerstring
;
679 } catch (Exception e
) {
680 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
684 if (filepath
== null
) {
685 Log_OC
.e(TAG
, "Couldnt resolve path to file");
686 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
692 Intent i
= new Intent(this, FileUploader
.class);
693 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
695 String remotepath
= new String();
696 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
697 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
699 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
700 remotepath
+= OCFile
.PATH_SEPARATOR
;
702 if (filepath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
704 Cursor cursor
= MainApp
.getAppContext().getContentResolver()
705 .query(Uri
.parse(filepath
), null
, null
, null
, null
, null
);
708 if (cursor
!= null
&& cursor
.moveToFirst()) {
709 String displayName
= cursor
.getString(
710 cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
711 Log
.i(TAG
, "Display Name: " + displayName
+ "; mimeType: " + mimeType
);
713 displayName
.replace(File
.separatorChar
, '_');
714 displayName
.replace(File
.pathSeparatorChar
, '_');
715 remotepath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filepath
);
723 remotepath
+= new File(filepath
).getName();
726 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
727 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
728 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
729 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
730 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
731 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
736 * Request the operation for moving the file/folder from one path to another
738 * @param data Intent received
739 * @param resultCode Result code received
741 private void requestMoveOperation(Intent data
, int resultCode
) {
742 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
743 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
744 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
748 public void onBackPressed() {
749 OCFileListFragment listOfFiles
= getListOfFilesFragment();
750 if (mDualPane
|| getSecondFragment() == null
) {
751 if (listOfFiles
!= null
) { // should never be null, indeed
752 if (mDirectories
.getCount() <= 1) {
756 int levelsUp
= listOfFiles
.onBrowseUp();
757 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
762 if (listOfFiles
!= null
) { // should never be null, indeed
763 setFile(listOfFiles
.getCurrentFile());
765 cleanSecondFragment();
770 protected void onSaveInstanceState(Bundle outState
) {
771 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
772 Log_OC
.e(TAG
, "onSaveInstanceState() start");
773 super.onSaveInstanceState(outState
);
774 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
775 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
776 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
777 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
779 Log_OC
.d(TAG
, "onSaveInstanceState() end");
785 protected void onResume() {
787 Log_OC
.e(TAG
, "onResume() start");
789 // refresh list of files
790 refreshListOfFilesFragment();
792 // Listen for sync messages
793 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
794 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
795 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
796 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
797 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
798 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
799 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
800 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
802 // Listen for upload messages
803 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
804 mUploadFinishReceiver
= new UploadFinishReceiver();
805 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
807 // Listen for download messages
808 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
809 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
810 mDownloadFinishReceiver
= new DownloadFinishReceiver();
811 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
813 Log_OC
.d(TAG
, "onResume() end");
818 protected void onPause() {
819 Log_OC
.e(TAG
, "onPause() start");
820 if (mSyncBroadcastReceiver
!= null
) {
821 unregisterReceiver(mSyncBroadcastReceiver
);
822 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
823 mSyncBroadcastReceiver
= null
;
825 if (mUploadFinishReceiver
!= null
) {
826 unregisterReceiver(mUploadFinishReceiver
);
827 mUploadFinishReceiver
= null
;
829 if (mDownloadFinishReceiver
!= null
) {
830 unregisterReceiver(mDownloadFinishReceiver
);
831 mDownloadFinishReceiver
= null
;
835 Log_OC
.d(TAG
, "onPause() end");
841 protected Dialog
onCreateDialog(int id
) {
842 Dialog dialog
= null
;
843 AlertDialog
.Builder builder
;
845 case DIALOG_SHORT_WAIT
: {
846 ProgressDialog working_dialog
= new ProgressDialog(this);
847 working_dialog
.setMessage(getResources().getString(
848 R
.string
.wait_a_moment
));
849 working_dialog
.setIndeterminate(true
);
850 working_dialog
.setCancelable(false
);
851 dialog
= working_dialog
;
854 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
857 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
858 getString(R
.string
.actionbar_upload_from_apps
) };
860 builder
= new AlertDialog
.Builder(this);
861 builder
.setTitle(R
.string
.actionbar_upload
);
862 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
863 public void onClick(DialogInterface dialog
, int item
) {
866 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
867 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
868 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
870 // TODO create and handle new fragment
871 // LocalFileListFragment
873 } else if (item
== 1) {
874 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
875 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
876 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
877 ACTION_SELECT_CONTENT_FROM_APPS
);
881 dialog
= builder
.create();
884 case DIALOG_CERT_NOT_SAVED
: {
885 builder
= new AlertDialog
.Builder(this);
886 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
887 builder
.setCancelable(false
);
888 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
890 public void onClick(DialogInterface dialog
, int which
) {
894 dialog
= builder
.create();
905 * Translates a content URI of an content to a physical path on the disk
907 * @param uri The URI to resolve
908 * @return The path to the content or null if it could not be found
910 public String
getPath(Uri uri
) {
911 final boolean isKitKatOrLater
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
914 if (isKitKatOrLater
&& DocumentsContract
.isDocumentUri(getApplicationContext(), uri
)) {
915 // ExternalStorageProvider
916 if (UriUtils
.isExternalStorageDocument(uri
)) {
917 final String docId
= DocumentsContract
.getDocumentId(uri
);
918 final String
[] split
= docId
.split(":");
919 final String type
= split
[0];
921 if ("primary".equalsIgnoreCase(type
)) {
922 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
926 else if (UriUtils
.isDownloadsDocument(uri
)) {
928 final String id
= DocumentsContract
.getDocumentId(uri
);
929 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
932 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, null
, null
);
935 else if (UriUtils
.isMediaDocument(uri
)) {
936 final String docId
= DocumentsContract
.getDocumentId(uri
);
937 final String
[] split
= docId
.split(":");
938 final String type
= split
[0];
940 Uri contentUri
= null
;
941 if ("image".equals(type
)) {
942 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
943 } else if ("video".equals(type
)) {
944 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
945 } else if ("audio".equals(type
)) {
946 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
949 final String selection
= "_id=?";
950 final String
[] selectionArgs
= new String
[] { split
[1] };
952 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, selection
, selectionArgs
);
954 // Documents providers returned as content://...
955 else if (UriUtils
.isContentDocument(uri
)) {
956 return uri
.toString();
959 // MediaStore (and general)
960 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
962 // Return the remote address
963 if (UriUtils
.isGooglePhotosUri(uri
))
964 return uri
.getLastPathSegment();
966 return UriUtils
.getDataColumn(getApplicationContext(), uri
, null
, null
);
969 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
970 return uri
.getPath();
976 * Pushes a directory to the drop down list
977 * @param directory to push
978 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
980 public void pushDirname(OCFile directory
) {
981 if(!directory
.isFolder()){
982 throw new IllegalArgumentException("Only directories may be pushed!");
984 mDirectories
.insert(directory
.getFileName(), 0);
989 * Pops a directory name from the drop down list
990 * @return True, unless the stack is empty
992 public boolean popDirname() {
993 mDirectories
.remove(mDirectories
.getItem(0));
994 return !mDirectories
.isEmpty();
997 // Custom array adapter to override text colors
998 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1000 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1004 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1005 View v
= super.getView(position
, convertView
, parent
);
1007 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1008 android
.R
.color
.white
));
1010 fixRoot((TextView
) v
);
1014 public View
getDropDownView(int position
, View convertView
,
1016 View v
= super.getDropDownView(position
, convertView
, parent
);
1018 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1019 android
.R
.color
.white
));
1021 fixRoot((TextView
) v
);
1025 private void fixRoot(TextView v
) {
1026 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1027 v
.setText(R
.string
.default_display_name_for_root_folder
);
1033 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1036 * {@link BroadcastReceiver} to enable syncing feedback in UI
1039 public void onReceive(Context context
, Intent intent
) {
1041 String event
= intent
.getAction();
1042 Log_OC
.d(TAG
, "Received broadcast " + event
);
1043 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1044 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1045 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1046 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1050 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1051 mSyncInProgress
= true
;
1054 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1055 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1057 if (currentDir
== null
) {
1058 // current folder was removed from the server
1059 Toast
.makeText( FileDisplayActivity
.this,
1060 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1066 if (currentFile
== null
&& !getFile().isFolder()) {
1067 // currently selected file was removed in the server, and now we know it
1068 cleanSecondFragment();
1069 currentFile
= currentDir
;
1072 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1073 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1074 if (fileListFragment
!= null
) {
1075 fileListFragment
.listDirectory(currentDir
);
1078 setFile(currentFile
);
1081 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1083 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1085 /// TODO refactor and make common
1086 synchResult
!= null
&& !synchResult
.isSuccess() &&
1087 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1088 synchResult
.isIdPRedirection() ||
1089 (synchResult
.isException() && synchResult
.getException()
1090 instanceof AuthenticatorException
))) {
1092 OwnCloudClient client
= null
;
1094 OwnCloudAccount ocAccount
=
1095 new OwnCloudAccount(getAccount(), context
);
1096 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1097 removeClientFor(ocAccount
));
1098 // TODO get rid of these exceptions
1099 } catch (AccountNotFoundException e
) {
1100 e
.printStackTrace();
1101 } catch (AuthenticatorException e
) {
1102 e
.printStackTrace();
1103 } catch (OperationCanceledException e
) {
1104 e
.printStackTrace();
1105 } catch (IOException e
) {
1106 e
.printStackTrace();
1109 if (client
!= null
) {
1110 OwnCloudCredentials cred
= client
.getCredentials();
1112 AccountManager am
= AccountManager
.get(context
);
1113 if (cred
.authTokenExpires()) {
1114 am
.invalidateAuthToken(
1119 am
.clearPassword(getAccount());
1124 requestCredentialsUpdate();
1128 removeStickyBroadcast(intent
);
1129 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1130 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1132 setBackgroundText();
1136 if (synchResult
!= null
) {
1137 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1138 mLastSslUntrustedServerResult
= synchResult
;
1141 } catch (RuntimeException e
) {
1142 // avoid app crashes after changing the serial id of RemoteOperationResult
1143 // in owncloud library with broadcast notifications pending to process
1144 removeStickyBroadcast(intent
);
1150 * Show a text message on screen view for notifying user if content is
1151 * loading or folder is empty
1153 private void setBackgroundText() {
1154 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1155 if (ocFileListFragment
!= null
) {
1156 int message
= R
.string
.file_list_loading
;
1157 if (!mSyncInProgress
) {
1158 // In case file list is empty
1159 message
= R
.string
.file_list_empty
;
1161 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1163 Log_OC
.e(TAG
, "OCFileListFragment is null");
1168 * Once the file upload has finished -> update view
1170 private class UploadFinishReceiver
extends BroadcastReceiver
{
1172 * Once the file upload has finished -> update view
1173 * @author David A. Velasco
1174 * {@link BroadcastReceiver} to enable upload feedback in UI
1177 public void onReceive(Context context
, Intent intent
) {
1179 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1180 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1181 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1182 OCFile currentDir
= getCurrentDir();
1183 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1184 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1186 if (sameAccount
&& isDescendant
) {
1187 refreshListOfFilesFragment();
1190 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1191 boolean renamedInUpload
= getFile().getRemotePath().
1192 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1193 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1195 FileFragment details
= getSecondFragment();
1196 boolean detailFragmentIsShown
= (details
!= null
&&
1197 details
instanceof FileDetailFragment
);
1199 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1200 if (uploadWasFine
) {
1201 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1203 if (renamedInUpload
) {
1204 String newName
= (new File(uploadedRemotePath
)).getName();
1205 Toast msg
= Toast
.makeText(
1208 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1213 if (uploadWasFine
|| getFile().fileExists()) {
1214 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1216 cleanSecondFragment();
1219 // Force the preview if the file is an image
1220 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1221 startImagePreview(getFile());
1222 } // TODO what about other kind of previews?
1226 if (intent
!= null
) {
1227 removeStickyBroadcast(intent
);
1237 * Class waiting for broadcast events from the {@link FielDownloader} service.
1239 * Updates the UI when a download is started or finished, provided that it is relevant for the
1242 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1244 public void onReceive(Context context
, Intent intent
) {
1246 boolean sameAccount
= isSameAccount(context
, intent
);
1247 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1248 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1250 if (sameAccount
&& isDescendant
) {
1251 refreshListOfFilesFragment();
1252 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1255 if (mWaitingToSend
!= null
) {
1256 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1257 if (mWaitingToSend
.isDown()) {
1258 sendDownloadedFile();
1263 if (intent
!= null
) {
1264 removeStickyBroadcast(intent
);
1269 private boolean isDescendant(String downloadedRemotePath
) {
1270 OCFile currentDir
= getCurrentDir();
1271 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1274 private boolean isSameAccount(Context context
, Intent intent
) {
1275 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1276 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1281 public void browseToRoot() {
1282 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1283 if (listOfFiles
!= null
) { // should never be null, indeed
1284 while (mDirectories
.getCount() > 1) {
1287 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1288 listOfFiles
.listDirectory(root
);
1289 setFile(listOfFiles
.getCurrentFile());
1290 startSyncFolderOperation(root
, false
);
1292 cleanSecondFragment();
1296 public void browseTo(OCFile folder
) {
1297 if (folder
== null
|| !folder
.isFolder()) {
1298 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1300 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1301 if (listOfFiles
!= null
) {
1302 setNavigationListWithFolder(folder
);
1303 listOfFiles
.listDirectory(folder
);
1304 setFile(listOfFiles
.getCurrentFile());
1305 startSyncFolderOperation(folder
, false
);
1307 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1309 cleanSecondFragment();
1316 * Updates action bar and second fragment, if in dual pane mode.
1319 public void onBrowsedDownTo(OCFile directory
) {
1320 pushDirname(directory
);
1321 cleanSecondFragment();
1324 startSyncFolderOperation(directory
, false
);
1329 * Shows the information of the {@link OCFile} received as a
1330 * parameter in the second fragment.
1332 * @param file {@link OCFile} whose details will be shown
1335 public void showDetails(OCFile file
) {
1336 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1337 setSecondFragment(detailFragment
);
1338 updateFragmentsVisibility(true
);
1339 updateNavigationElementsInActionBar(file
);
1347 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1348 ActionBar actionBar
= getSupportActionBar();
1349 if (chosenFile
== null
|| mDualPane
) {
1350 // only list of files - set for browsing through folders
1351 OCFile currentDir
= getCurrentDir();
1352 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1353 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1354 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1356 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1358 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1359 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1362 actionBar
.setDisplayHomeAsUpEnabled(true
);
1363 actionBar
.setDisplayShowTitleEnabled(true
);
1364 actionBar
.setTitle(chosenFile
.getFileName());
1365 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1371 protected ServiceConnection
newTransferenceServiceConnection() {
1372 return new ListServiceConnection();
1375 /** Defines callbacks for service binding, passed to bindService() */
1376 private class ListServiceConnection
implements ServiceConnection
{
1379 public void onServiceConnected(ComponentName component
, IBinder service
) {
1380 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1381 Log_OC
.d(TAG
, "Download service connected");
1382 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1383 if (mWaitingToPreview
!= null
)
1384 if (getStorageManager() != null
) {
1385 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1386 if (!mWaitingToPreview
.isDown()) {
1387 requestForDownload();
1391 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1392 Log_OC
.d(TAG
, "Upload service connected");
1393 mUploaderBinder
= (FileUploaderBinder
) service
;
1397 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1398 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1399 if (listOfFiles
!= null
) {
1400 listOfFiles
.listDirectory();
1402 FileFragment secondFragment
= getSecondFragment();
1403 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1404 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1405 detailFragment
.listenForTransferProgress();
1406 detailFragment
.updateFileDetails(false
, false
);
1411 public void onServiceDisconnected(ComponentName component
) {
1412 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1413 Log_OC
.d(TAG
, "Download service disconnected");
1414 mDownloaderBinder
= null
;
1415 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1416 Log_OC
.d(TAG
, "Upload service disconnected");
1417 mUploaderBinder
= null
;
1425 * Launch an intent to request the PIN code to the user before letting him use the app
1427 private void requestPinCode() {
1428 boolean pinStart
= false
;
1429 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1430 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1432 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1433 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1440 public void onSavedCertificate() {
1441 startSyncFolderOperation(getCurrentDir(), false
);
1446 public void onFailedSavingCertificate() {
1447 showDialog(DIALOG_CERT_NOT_SAVED
);
1451 public void onCancelCertificate() {
1456 * Updates the view associated to the activity after the finish of some operation over files
1457 * in the current account.
1459 * @param operation Removal operation performed.
1460 * @param result Result of the removal.
1463 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1464 super.onRemoteOperationFinish(operation
, result
);
1466 if (operation
instanceof RemoveFileOperation
) {
1467 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1469 } else if (operation
instanceof RenameFileOperation
) {
1470 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1472 } else if (operation
instanceof SynchronizeFileOperation
) {
1473 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1475 } else if (operation
instanceof CreateFolderOperation
) {
1476 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1478 } else if (operation
instanceof CreateShareOperation
) {
1479 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1481 } else if (operation
instanceof UnshareLinkOperation
) {
1482 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1484 } else if (operation
instanceof MoveFileOperation
) {
1485 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1491 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1492 if (result
.isSuccess()) {
1493 refreshShowDetails();
1494 refreshListOfFilesFragment();
1499 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1500 if (result
.isSuccess()) {
1501 refreshShowDetails();
1502 refreshListOfFilesFragment();
1504 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1505 cleanSecondFragment();
1506 refreshListOfFilesFragment();
1510 private void refreshShowDetails() {
1511 FileFragment details
= getSecondFragment();
1512 if (details
!= null
) {
1513 OCFile file
= details
.getFile();
1515 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1516 if (details
instanceof PreviewMediaFragment
) {
1517 // Refresh OCFile of the fragment
1518 ((PreviewMediaFragment
) details
).updateFile(file
);
1523 invalidateOptionsMenu();
1528 * Updates the view associated to the activity after the finish of an operation trying to remove a
1531 * @param operation Removal operation performed.
1532 * @param result Result of the removal.
1534 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1535 dismissLoadingDialog();
1537 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1541 if (result
.isSuccess()) {
1542 OCFile removedFile
= operation
.getFile();
1543 FileFragment second
= getSecondFragment();
1544 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1545 if (second
instanceof PreviewMediaFragment
) {
1546 ((PreviewMediaFragment
)second
).stopPreview(true
);
1548 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1549 cleanSecondFragment();
1551 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1552 refreshListOfFilesFragment();
1554 invalidateOptionsMenu();
1556 if (result
.isSslRecoverableException()) {
1557 mLastSslUntrustedServerResult
= result
;
1558 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1565 * Updates the view associated to the activity after the finish of an operation trying to move a
1568 * @param operation Move operation performed.
1569 * @param result Result of the move operation.
1571 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1572 if (result
.isSuccess()) {
1573 dismissLoadingDialog();
1574 refreshListOfFilesFragment();
1576 dismissLoadingDialog();
1578 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1579 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1583 } catch (NotFoundException e
) {
1584 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1591 * Updates the view associated to the activity after the finish of an operation trying to rename a
1594 * @param operation Renaming operation performed.
1595 * @param result Result of the renaming.
1597 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1598 dismissLoadingDialog();
1599 OCFile renamedFile
= operation
.getFile();
1600 if (result
.isSuccess()) {
1601 FileFragment details
= getSecondFragment();
1602 if (details
!= null
) {
1603 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1604 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1605 showDetails(renamedFile
);
1607 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1608 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1609 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1610 int position
= ((PreviewMediaFragment
)details
).getPosition();
1611 startMediaPreview(renamedFile
, position
, true
);
1613 getFileOperationsHelper().openFile(renamedFile
);
1618 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1619 refreshListOfFilesFragment();
1623 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1627 if (result
.isSslRecoverableException()) {
1628 mLastSslUntrustedServerResult
= result
;
1629 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1634 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1635 dismissLoadingDialog();
1636 OCFile syncedFile
= operation
.getLocalFile();
1637 if (!result
.isSuccess()) {
1638 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1639 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1640 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1641 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1647 if (operation
.transferWasRequested()) {
1648 onTransferStateChanged(syncedFile
, true
, true
);
1651 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1659 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1661 * @param operation Creation operation performed.
1662 * @param result Result of the creation.
1664 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1665 if (result
.isSuccess()) {
1666 dismissLoadingDialog();
1667 refreshListOfFilesFragment();
1669 dismissLoadingDialog();
1671 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1672 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1676 } catch (NotFoundException e
) {
1677 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1687 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1688 refreshListOfFilesFragment();
1689 FileFragment details
= getSecondFragment();
1690 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1691 if (downloading
|| uploading
) {
1692 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1694 if (!file
.fileExists()) {
1695 cleanSecondFragment();
1697 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1705 private void requestForDownload() {
1706 Account account
= getAccount();
1707 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1708 Intent i
= new Intent(this, FileDownloader
.class);
1709 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1710 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1716 private OCFile
getCurrentDir() {
1717 OCFile file
= getFile();
1719 if (file
.isFolder()) {
1721 } else if (getStorageManager() != null
) {
1722 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1723 return getStorageManager().getFileByPath(parentPath
);
1729 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1730 long currentSyncTime
= System
.currentTimeMillis();
1732 mSyncInProgress
= true
;
1734 // perform folder synchronization
1735 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1738 getFileOperationsHelper().isSharedSupported(),
1740 getStorageManager(),
1742 getApplicationContext()
1744 synchFolderOp
.execute(getAccount(), this, null
, null
);
1746 setSupportProgressBarIndeterminateVisibility(true
);
1748 setBackgroundText();
1752 * Show untrusted cert dialog
1754 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1755 // Show a dialog with the certificate info
1756 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1757 FragmentManager fm
= getSupportFragmentManager();
1758 FragmentTransaction ft
= fm
.beginTransaction();
1759 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1762 private void requestForDownload(OCFile file
) {
1763 Account account
= getAccount();
1764 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1765 Intent i
= new Intent(this, FileDownloader
.class);
1766 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1767 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1772 private void sendDownloadedFile(){
1773 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1774 mWaitingToSend
= null
;
1779 * Requests the download of the received {@link OCFile} , updates the UI
1780 * to monitor the download progress and prepares the activity to send the file
1781 * when the download finishes.
1783 * @param file {@link OCFile} to download and preview.
1785 public void startDownloadForSending(OCFile file
) {
1786 mWaitingToSend
= file
;
1787 requestForDownload(mWaitingToSend
);
1788 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1789 updateFragmentsVisibility(hasSecondFragment
);
1793 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1795 * @param file Image {@link OCFile} to show.
1797 public void startImagePreview(OCFile file
) {
1798 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1799 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1800 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1801 startActivity(showDetailsIntent
);
1806 * Stars the preview of an already down media {@link OCFile}.
1808 * @param file Media {@link OCFile} to preview.
1809 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1810 * @param autoplay When 'true', the playback will start without user interactions.
1812 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1813 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1814 setSecondFragment(mediaFragment
);
1815 updateFragmentsVisibility(true
);
1816 updateNavigationElementsInActionBar(file
);
1821 * Requests the download of the received {@link OCFile} , updates the UI
1822 * to monitor the download progress and prepares the activity to preview
1823 * or open the file when the download finishes.
1825 * @param file {@link OCFile} to download and preview.
1827 public void startDownloadForPreview(OCFile file
) {
1828 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1829 setSecondFragment(detailFragment
);
1830 mWaitingToPreview
= file
;
1831 requestForDownload();
1832 updateFragmentsVisibility(true
);
1833 updateNavigationElementsInActionBar(file
);
1838 public void cancelTransference(OCFile file
) {
1839 getFileOperationsHelper().cancelTransference(file
);
1840 if (mWaitingToPreview
!= null
&&
1841 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1842 mWaitingToPreview
= null
;
1844 if (mWaitingToSend
!= null
&&
1845 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1846 mWaitingToSend
= null
;
1848 onTransferStateChanged(file
, false
, false
);
1852 public void onRefresh(boolean ignoreETag
) {
1853 refreshList(ignoreETag
);
1857 public void onRefresh() {
1861 private void refreshList(boolean ignoreETag
) {
1862 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1863 if (listOfFiles
!= null
) {
1864 OCFile folder
= listOfFiles
.getCurrentFile();
1865 if (folder
!= null
) {
1866 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1867 listDirectory(mFile);*/
1868 startSyncFolderOperation(folder
, ignoreETag
);
1873 private void sortByDate(boolean ascending
){
1874 getListOfFilesFragment().sortByDate(ascending
);
1877 private void sortBySize(boolean ascending
){
1878 getListOfFilesFragment().sortBySize(ascending
);
1881 private void sortByName(boolean ascending
){
1882 getListOfFilesFragment().sortByName(ascending
);