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
.support
.v4
.app
.Fragment
;
53 import android
.support
.v4
.app
.FragmentManager
;
54 import android
.support
.v4
.app
.FragmentTransaction
;
55 import android
.view
.View
;
56 import android
.view
.ViewGroup
;
57 import android
.widget
.ArrayAdapter
;
58 import android
.widget
.TextView
;
59 import android
.widget
.Toast
;
61 import com
.actionbarsherlock
.app
.ActionBar
;
62 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
63 import com
.actionbarsherlock
.view
.Menu
;
64 import com
.actionbarsherlock
.view
.MenuInflater
;
65 import com
.actionbarsherlock
.view
.MenuItem
;
66 import com
.actionbarsherlock
.view
.Window
;
67 import com
.owncloud
.android
.BuildConfig
;
68 import com
.owncloud
.android
.MainApp
;
69 import com
.owncloud
.android
.R
;
70 import com
.owncloud
.android
.datamodel
.OCFile
;
71 import com
.owncloud
.android
.files
.services
.FileDownloader
;
72 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
73 import com
.owncloud
.android
.files
.services
.FileUploader
;
74 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
76 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
78 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
79 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
80 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
82 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
83 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
84 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
85 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
86 import com
.owncloud
.android
.operations
.CreateShareOperation
;
87 import com
.owncloud
.android
.operations
.MoveFileOperation
;
88 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
89 import com
.owncloud
.android
.operations
.RenameFileOperation
;
90 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
91 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
92 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
93 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
94 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
95 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
;
96 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
97 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
98 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
99 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
100 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
101 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
105 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
106 import com
.owncloud
.android
.utils
.DisplayUtils
;
107 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
111 * Displays, what files the user has available in his ownCloud.
113 * @author Bartek Przybylski
114 * @author David A. Velasco
117 public class FileDisplayActivity
extends HookActivity
implements
118 FileFragment
.ContainerActivity
, OnNavigationListener
,
119 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
121 private ArrayAdapter
<String
> mDirectories
;
123 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
124 private UploadFinishReceiver mUploadFinishReceiver
;
125 private DownloadFinishReceiver mDownloadFinishReceiver
;
126 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
128 private boolean mDualPane
;
129 private View mLeftFragmentContainer
;
130 private View mRightFragmentContainer
;
132 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
133 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
134 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
136 public static final int DIALOG_SHORT_WAIT
= 0;
137 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
138 private static final int DIALOG_CERT_NOT_SAVED
= 2;
140 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
142 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
143 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
144 public static final int ACTION_MOVE_FILES
= 3;
146 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
148 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
149 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
151 private OCFile mWaitingToPreview
;
153 private boolean mSyncInProgress
= false
;
155 private String DIALOG_UNTRUSTED_CERT
;
157 private OCFile mWaitingToSend
;
160 protected void onCreate(Bundle savedInstanceState
) {
161 Log_OC
.d(TAG
, "onCreate() start");
162 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
164 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
166 // PIN CODE request ; best location is to decide, let's try this first
167 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
169 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
173 /// grant that FileObserverService is watching favourite files
174 if (savedInstanceState
== null
) {
175 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
176 startService(initObserversIntent
);
179 /// Load of saved instance state
180 if(savedInstanceState
!= null
) {
181 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
182 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
183 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
186 mWaitingToPreview
= null
;
187 mSyncInProgress
= false
;
188 mWaitingToSend
= null
;
193 // Inflate and set the layout view
194 setContentView(R
.layout
.files
);
195 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
196 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
197 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
198 if (savedInstanceState
== null
) {
199 createMinFragments();
203 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
204 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
205 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
209 Log_OC
.d(TAG
, "onCreate() end");
213 protected void onStart() {
215 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
219 protected void onDestroy() {
224 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
227 protected void onAccountSet(boolean stateWasRecovered
) {
228 super.onAccountSet(stateWasRecovered
);
229 if (getAccount() != null
) {
230 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
231 OCFile file
= getFile();
232 // get parent from path
233 String parentPath
= "";
235 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
236 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
237 // get parent from path
238 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
239 if (getStorageManager().getFileByPath(parentPath
) == null
)
240 file
= null
; // not able to know the directory where the file is uploading
242 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
246 // fall back to root folder
247 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
250 setNavigationListWithFolder(file
);
252 if (!stateWasRecovered
) {
253 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
254 initFragmentsWithFile();
255 if (file
.isFolder()) {
256 startSyncFolderOperation(file
, false
);
260 updateFragmentsVisibility(!file
.isFolder());
261 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
267 private void setNavigationListWithFolder(OCFile file
) {
268 mDirectories
.clear();
269 OCFile fileIt
= file
;
271 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
272 if (fileIt
.isFolder()) {
273 mDirectories
.add(fileIt
.getFileName());
275 // get parent from path
276 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
277 fileIt
= getStorageManager().getFileByPath(parentPath
);
279 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
283 private void createMinFragments() {
284 OCFileListFragment listOfFiles
= new OCFileListFragment();
285 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
286 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
287 transaction
.commit();
290 private void initFragmentsWithFile() {
291 if (getAccount() != null
&& getFile() != null
) {
293 OCFileListFragment listOfFiles
= getListOfFilesFragment();
294 if (listOfFiles
!= null
) {
295 listOfFiles
.listDirectory(getCurrentDir());
297 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
301 OCFile file
= getFile();
302 Fragment secondFragment
= chooseInitialSecondFragment(file
);
303 if (secondFragment
!= null
) {
304 setSecondFragment(secondFragment
);
305 updateFragmentsVisibility(true
);
306 updateNavigationElementsInActionBar(file
);
309 cleanSecondFragment();
313 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
314 if (getAccount() == null
) {
315 Log_OC
.wtf(TAG
, "\t account is NULL");
317 if (getFile() == null
) {
318 Log_OC
.wtf(TAG
, "\t file is NULL");
323 private Fragment
chooseInitialSecondFragment(OCFile file
) {
324 Fragment secondFragment
= null
;
325 if (file
!= null
&& !file
.isFolder()) {
326 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
327 && file
.getLastSyncDateForProperties() > 0 // temporal fix
329 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
330 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
331 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
334 secondFragment
= new FileDetailFragment(file
, getAccount());
337 return secondFragment
;
342 * Replaces the second fragment managed by the activity with the received as
345 * Assumes never will be more than two fragments managed at the same time.
347 * @param fragment New second Fragment to set.
349 private void setSecondFragment(Fragment fragment
) {
350 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
351 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
352 transaction
.commit();
356 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
358 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
359 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
361 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
362 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
365 } else if (existsSecondFragment
) {
366 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
367 mLeftFragmentContainer
.setVisibility(View
.GONE
);
369 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
370 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
374 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
375 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
377 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
378 mRightFragmentContainer
.setVisibility(View
.GONE
);
384 private OCFileListFragment
getListOfFilesFragment() {
385 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
386 if (listOfFiles
!= null
) {
387 return (OCFileListFragment
)listOfFiles
;
389 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
393 public FileFragment
getSecondFragment() {
394 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
395 if (second
!= null
) {
396 return (FileFragment
)second
;
401 protected void cleanSecondFragment() {
402 Fragment second
= getSecondFragment();
403 if (second
!= null
) {
404 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
408 updateFragmentsVisibility(false
);
409 updateNavigationElementsInActionBar(null
);
412 protected void refreshListOfFilesFragment() {
413 OCFileListFragment fileListFragment
= getListOfFilesFragment();
414 if (fileListFragment
!= null
) {
415 fileListFragment
.listDirectory();
419 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
420 FileFragment secondFragment
= getSecondFragment();
421 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
422 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
423 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
424 OCFile fileInFragment
= detailsFragment
.getFile();
425 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
426 // the user browsed to other file ; forget the automatic preview
427 mWaitingToPreview
= null
;
429 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
430 // grant that the right panel updates the progress bar
431 detailsFragment
.listenForTransferProgress();
432 detailsFragment
.updateFileDetails(true
, false
);
434 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
435 // update the right panel
436 boolean detailsFragmentChanged
= false
;
439 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
440 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
441 startMediaPreview(mWaitingToPreview
, 0, true
);
442 detailsFragmentChanged
= true
;
444 getFileOperationsHelper().openFile(mWaitingToPreview
);
447 mWaitingToPreview
= null
;
449 if (!detailsFragmentChanged
) {
450 detailsFragment
.updateFileDetails(false
, (success
));
457 public boolean onPrepareOptionsMenu(Menu menu
) {
458 if (BuildConfig
.DEBUG
) {
459 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
461 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
463 return super.onPrepareOptionsMenu(menu
);
467 public boolean onCreateOptionsMenu(Menu menu
) {
468 MenuInflater inflater
= getSherlock().getMenuInflater();
469 inflater
.inflate(R
.menu
.main_menu
, menu
);
474 public boolean onOptionsItemSelected(MenuItem item
) {
475 boolean retval
= true
;
476 switch (item
.getItemId()) {
477 case R
.id
.action_create_dir
: {
478 CreateFolderDialogFragment dialog
=
479 CreateFolderDialogFragment
.newInstance(getCurrentDir());
480 dialog
.show(getSupportFragmentManager(), "createdirdialog");
483 case R
.id
.action_sync_account
: {
484 startSynchronization();
487 case R
.id
.action_upload
: {
488 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
491 case R
.id
.action_settings
: {
492 Intent settingsIntent
= new Intent(this, Preferences
.class);
493 startActivity(settingsIntent
);
496 case R
.id
.action_logger
: {
497 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
498 startActivity(loggerIntent
);
501 case android
.R
.id
.home
: {
502 FileFragment second
= getSecondFragment();
503 OCFile currentDir
= getCurrentDir();
504 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
505 (second
!= null
&& second
.getFile() != null
)) {
511 case R
.id
.action_sort
: {
512 SharedPreferences appPreferences
= PreferenceManager
513 .getDefaultSharedPreferences(this);
515 // Read sorting order, default to sort by name ascending
516 Integer sortOrder
= appPreferences
517 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
519 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
520 builder
.setTitle(R
.string
.actionbar_sort_title
)
521 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
522 public void onClick(DialogInterface dialog
, int which
) {
532 // TODO re-enable when server-side folder size calculation is available
534 // sortBySize(false);
542 builder
.create().show();
546 retval
= super.onOptionsItemSelected(item
);
551 private void startSynchronization() {
552 Log_OC
.e(TAG
, "Got to start sync");
553 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
554 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
555 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
556 Bundle bundle
= new Bundle();
557 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
558 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
559 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
560 ContentResolver
.requestSync(
562 MainApp
.getAuthority(), bundle
);
564 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
565 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
566 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
567 builder
.setExpedited(true
);
568 builder
.setManual(true
);
570 SyncRequest request
= builder
.build();
571 ContentResolver
.requestSync(request
);
577 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
578 if (itemPosition
!= 0) {
579 String targetPath
= "";
580 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
581 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
583 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
584 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
585 if (targetFolder
!= null
) {
586 browseTo(targetFolder
);
589 // the next operation triggers a new call to this method, but it's necessary to
590 // ensure that the name exposed in the action bar is the current directory when the
591 // user selected it in the navigation list
592 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
593 getSupportActionBar().setSelectedNavigationItem(0);
599 * Called, when the user selected something for uploading
601 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
602 super.onActivityResult(requestCode
, resultCode
, data
);
604 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
605 requestSimpleUpload(data
, resultCode
);
607 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
608 requestMultipleUpload(data
, resultCode
);
610 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
611 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)){
613 final Intent fData
= data
;
614 final int fResultCode
= resultCode
;
615 getHandler().postDelayed(
619 requestMoveOperation(fData
, fResultCode
);
622 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
627 private void requestMultipleUpload(Intent data
, int resultCode
) {
628 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
629 if (filePaths
!= null
) {
630 String
[] remotePaths
= new String
[filePaths
.length
];
631 String remotePathBase
= "";
632 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
633 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
635 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
636 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
637 for (int j
= 0; j
< remotePaths
.length
; j
++) {
638 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
641 Intent i
= new Intent(this, FileUploader
.class);
642 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
643 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
644 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
645 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
646 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
647 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
651 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
652 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
659 private void requestSimpleUpload(Intent data
, int resultCode
) {
660 String filepath
= null
;
662 Uri selectedImageUri
= data
.getData();
664 String filemanagerstring
= selectedImageUri
.getPath();
665 String selectedImagePath
= getPath(selectedImageUri
);
667 if (selectedImagePath
!= null
)
668 filepath
= selectedImagePath
;
670 filepath
= filemanagerstring
;
672 } catch (Exception e
) {
673 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
677 if (filepath
== null
) {
678 Log_OC
.e(TAG
, "Couldnt resolve path to file");
679 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
685 Intent i
= new Intent(this, FileUploader
.class);
686 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
688 String remotepath
= new String();
689 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
690 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
692 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
693 remotepath
+= OCFile
.PATH_SEPARATOR
;
694 remotepath
+= new File(filepath
).getName();
696 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
697 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
698 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
699 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
700 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
705 * Request the operation for moving the file/folder from one path to another
707 * @param data Intent received
708 * @param resultCode Result code received
710 private void requestMoveOperation(Intent data
, int resultCode
) {
711 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
712 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
713 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
717 public void onBackPressed() {
718 OCFileListFragment listOfFiles
= getListOfFilesFragment();
719 if (mDualPane
|| getSecondFragment() == null
) {
720 if (listOfFiles
!= null
) { // should never be null, indeed
721 if (mDirectories
.getCount() <= 1) {
725 int levelsUp
= listOfFiles
.onBrowseUp();
726 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
731 if (listOfFiles
!= null
) { // should never be null, indeed
732 setFile(listOfFiles
.getCurrentFile());
734 cleanSecondFragment();
739 protected void onSaveInstanceState(Bundle outState
) {
740 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
741 Log_OC
.e(TAG
, "onSaveInstanceState() start");
742 super.onSaveInstanceState(outState
);
743 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
744 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
745 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
746 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
748 Log_OC
.d(TAG
, "onSaveInstanceState() end");
754 protected void onResume() {
756 Log_OC
.e(TAG
, "onResume() start");
758 // refresh list of files
759 refreshListOfFilesFragment();
761 // Listen for sync messages
762 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
763 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
764 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
765 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
766 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
767 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
768 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
769 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
771 // Listen for upload messages
772 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
773 mUploadFinishReceiver
= new UploadFinishReceiver();
774 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
776 // Listen for download messages
777 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
778 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
779 mDownloadFinishReceiver
= new DownloadFinishReceiver();
780 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
782 Log_OC
.d(TAG
, "onResume() end");
787 protected void onPause() {
788 Log_OC
.e(TAG
, "onPause() start");
789 if (mSyncBroadcastReceiver
!= null
) {
790 unregisterReceiver(mSyncBroadcastReceiver
);
791 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
792 mSyncBroadcastReceiver
= null
;
794 if (mUploadFinishReceiver
!= null
) {
795 unregisterReceiver(mUploadFinishReceiver
);
796 mUploadFinishReceiver
= null
;
798 if (mDownloadFinishReceiver
!= null
) {
799 unregisterReceiver(mDownloadFinishReceiver
);
800 mDownloadFinishReceiver
= null
;
804 Log_OC
.d(TAG
, "onPause() end");
810 protected Dialog
onCreateDialog(int id
) {
811 Dialog dialog
= null
;
812 AlertDialog
.Builder builder
;
814 case DIALOG_SHORT_WAIT
: {
815 ProgressDialog working_dialog
= new ProgressDialog(this);
816 working_dialog
.setMessage(getResources().getString(
817 R
.string
.wait_a_moment
));
818 working_dialog
.setIndeterminate(true
);
819 working_dialog
.setCancelable(false
);
820 dialog
= working_dialog
;
823 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
826 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
827 getString(R
.string
.actionbar_upload_from_apps
) };
829 builder
= new AlertDialog
.Builder(this);
830 builder
.setTitle(R
.string
.actionbar_upload
);
831 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
832 public void onClick(DialogInterface dialog
, int item
) {
835 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
836 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
837 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
839 // TODO create and handle new fragment
840 // LocalFileListFragment
842 } else if (item
== 1) {
843 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
844 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
845 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
846 ACTION_SELECT_CONTENT_FROM_APPS
);
850 dialog
= builder
.create();
853 case DIALOG_CERT_NOT_SAVED
: {
854 builder
= new AlertDialog
.Builder(this);
855 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
856 builder
.setCancelable(false
);
857 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
859 public void onClick(DialogInterface dialog
, int which
) {
863 dialog
= builder
.create();
874 * Translates a content URI of an content to a physical path on the disk
876 * @param uri The URI to resolve
877 * @return The path to the content or null if it could not be found
879 public String
getPath(Uri uri
) {
880 final boolean isKitKat
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
883 if (isKitKat
&& DocumentsContract
.isDocumentUri(getApplicationContext(), uri
)) {
884 // ExternalStorageProvider
885 if (isExternalStorageDocument(uri
)) {
886 final String docId
= DocumentsContract
.getDocumentId(uri
);
887 final String
[] split
= docId
.split(":");
888 final String type
= split
[0];
890 if ("primary".equalsIgnoreCase(type
)) {
891 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
895 else if (isDownloadsDocument(uri
)) {
897 final String id
= DocumentsContract
.getDocumentId(uri
);
898 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
901 return getDataColumn(getApplicationContext(), contentUri
, null
, null
);
904 else if (isMediaDocument(uri
)) {
905 final String docId
= DocumentsContract
.getDocumentId(uri
);
906 final String
[] split
= docId
.split(":");
907 final String type
= split
[0];
909 Uri contentUri
= null
;
910 if ("image".equals(type
)) {
911 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
912 } else if ("video".equals(type
)) {
913 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
914 } else if ("audio".equals(type
)) {
915 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
918 final String selection
= "_id=?";
919 final String
[] selectionArgs
= new String
[] { split
[1] };
921 return getDataColumn(getApplicationContext(), contentUri
, selection
, selectionArgs
);
924 // MediaStore (and general)
925 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
927 // Return the remote address
928 if (isGooglePhotosUri(uri
))
929 return uri
.getLastPathSegment();
931 return getDataColumn(getApplicationContext(), uri
, null
, null
);
934 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
935 return uri
.getPath();
941 * Get the value of the data column for this Uri. This is useful for
942 * MediaStore Uris, and other file-based ContentProviders.
944 * @param context The context.
945 * @param uri The Uri to query.
946 * @param selection (Optional) Filter used in the query.
947 * @param selectionArgs (Optional) Selection arguments used in the query.
948 * @return The value of the _data column, which is typically a file path.
950 public static String
getDataColumn(Context context
, Uri uri
, String selection
, String
[] selectionArgs
) {
952 Cursor cursor
= null
;
953 final String column
= "_data";
954 final String
[] projection
= { column
};
957 cursor
= context
.getContentResolver().query(uri
, projection
, selection
, selectionArgs
, null
);
958 if (cursor
!= null
&& cursor
.moveToFirst()) {
960 final int column_index
= cursor
.getColumnIndexOrThrow(column
);
961 return cursor
.getString(column_index
);
971 * @param uri The Uri to check.
972 * @return Whether the Uri authority is ExternalStorageProvider.
974 public static boolean isExternalStorageDocument(Uri uri
) {
975 return "com.android.externalstorage.documents".equals(uri
.getAuthority());
979 * @param uri The Uri to check.
980 * @return Whether the Uri authority is DownloadsProvider.
982 public static boolean isDownloadsDocument(Uri uri
) {
983 return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
987 * @param uri The Uri to check.
988 * @return Whether the Uri authority is MediaProvider.
990 public static boolean isMediaDocument(Uri uri
) {
991 return "com.android.providers.media.documents".equals(uri
.getAuthority());
995 * @param uri The Uri to check.
996 * @return Whether the Uri authority is Google Photos.
998 public static boolean isGooglePhotosUri(Uri uri
) {
999 return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
1004 * @param uri The Uri to check.
1005 * @return Whether the Uri authority is Google Drive.
1007 public static boolean isGoogleDriveDocument(Uri uri
) {
1008 return "com.google.android.apps.docs.storage".equals(uri
.getAuthority());
1012 * Pushes a directory to the drop down list
1013 * @param directory to push
1014 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
1016 public void pushDirname(OCFile directory
) {
1017 if(!directory
.isFolder()){
1018 throw new IllegalArgumentException("Only directories may be pushed!");
1020 mDirectories
.insert(directory
.getFileName(), 0);
1025 * Pops a directory name from the drop down list
1026 * @return True, unless the stack is empty
1028 public boolean popDirname() {
1029 mDirectories
.remove(mDirectories
.getItem(0));
1030 return !mDirectories
.isEmpty();
1033 // Custom array adapter to override text colors
1034 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1036 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1040 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1041 View v
= super.getView(position
, convertView
, parent
);
1043 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1044 android
.R
.color
.white
));
1046 fixRoot((TextView
) v
);
1050 public View
getDropDownView(int position
, View convertView
,
1052 View v
= super.getDropDownView(position
, convertView
, parent
);
1054 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1055 android
.R
.color
.white
));
1057 fixRoot((TextView
) v
);
1061 private void fixRoot(TextView v
) {
1062 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1063 v
.setText(R
.string
.default_display_name_for_root_folder
);
1069 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1072 * {@link BroadcastReceiver} to enable syncing feedback in UI
1075 public void onReceive(Context context
, Intent intent
) {
1077 String event
= intent
.getAction();
1078 Log_OC
.d(TAG
, "Received broadcast " + event
);
1079 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1080 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1081 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1082 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1086 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1087 mSyncInProgress
= true
;
1090 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1091 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1093 if (currentDir
== null
) {
1094 // current folder was removed from the server
1095 Toast
.makeText( FileDisplayActivity
.this,
1096 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1102 if (currentFile
== null
&& !getFile().isFolder()) {
1103 // currently selected file was removed in the server, and now we know it
1104 cleanSecondFragment();
1105 currentFile
= currentDir
;
1108 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1109 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1110 if (fileListFragment
!= null
) {
1111 fileListFragment
.listDirectory(currentDir
);
1114 setFile(currentFile
);
1117 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1119 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1121 /// TODO refactor and make common
1122 synchResult
!= null
&& !synchResult
.isSuccess() &&
1123 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1124 synchResult
.isIdPRedirection() ||
1125 (synchResult
.isException() && synchResult
.getException()
1126 instanceof AuthenticatorException
))) {
1128 OwnCloudClient client
= null
;
1130 OwnCloudAccount ocAccount
=
1131 new OwnCloudAccount(getAccount(), context
);
1132 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1133 removeClientFor(ocAccount
));
1134 // TODO get rid of these exceptions
1135 } catch (AccountNotFoundException e
) {
1136 e
.printStackTrace();
1137 } catch (AuthenticatorException e
) {
1138 e
.printStackTrace();
1139 } catch (OperationCanceledException e
) {
1140 e
.printStackTrace();
1141 } catch (IOException e
) {
1142 e
.printStackTrace();
1145 if (client
!= null
) {
1146 OwnCloudCredentials cred
= client
.getCredentials();
1148 AccountManager am
= AccountManager
.get(context
);
1149 if (cred
.authTokenExpires()) {
1150 am
.invalidateAuthToken(
1155 am
.clearPassword(getAccount());
1160 requestCredentialsUpdate();
1164 removeStickyBroadcast(intent
);
1165 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1166 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1168 setBackgroundText();
1172 if (synchResult
!= null
) {
1173 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1174 mLastSslUntrustedServerResult
= synchResult
;
1177 } catch (RuntimeException e
) {
1178 // avoid app crashes after changing the serial id of RemoteOperationResult
1179 // in owncloud library with broadcast notifications pending to process
1180 removeStickyBroadcast(intent
);
1186 * Show a text message on screen view for notifying user if content is
1187 * loading or folder is empty
1189 private void setBackgroundText() {
1190 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1191 if (ocFileListFragment
!= null
) {
1192 int message
= R
.string
.file_list_loading
;
1193 if (!mSyncInProgress
) {
1194 // In case file list is empty
1195 message
= R
.string
.file_list_empty
;
1197 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1199 Log_OC
.e(TAG
, "OCFileListFragment is null");
1204 * Once the file upload has finished -> update view
1206 private class UploadFinishReceiver
extends BroadcastReceiver
{
1208 * Once the file upload has finished -> update view
1209 * @author David A. Velasco
1210 * {@link BroadcastReceiver} to enable upload feedback in UI
1213 public void onReceive(Context context
, Intent intent
) {
1215 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1216 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1217 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1218 OCFile currentDir
= getCurrentDir();
1219 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1220 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1222 if (sameAccount
&& isDescendant
) {
1223 refreshListOfFilesFragment();
1226 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1227 boolean renamedInUpload
= getFile().getRemotePath().
1228 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1229 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1231 FileFragment details
= getSecondFragment();
1232 boolean detailFragmentIsShown
= (details
!= null
&&
1233 details
instanceof FileDetailFragment
);
1235 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1236 if (uploadWasFine
) {
1237 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1239 if (renamedInUpload
) {
1240 String newName
= (new File(uploadedRemotePath
)).getName();
1241 Toast msg
= Toast
.makeText(
1244 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1249 if (uploadWasFine
|| getFile().fileExists()) {
1250 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1252 cleanSecondFragment();
1255 // Force the preview if the file is an image
1256 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1257 startImagePreview(getFile());
1258 } // TODO what about other kind of previews?
1262 if (intent
!= null
) {
1263 removeStickyBroadcast(intent
);
1273 * Class waiting for broadcast events from the {@link FielDownloader} service.
1275 * Updates the UI when a download is started or finished, provided that it is relevant for the
1278 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1280 public void onReceive(Context context
, Intent intent
) {
1282 boolean sameAccount
= isSameAccount(context
, intent
);
1283 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1284 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1286 if (sameAccount
&& isDescendant
) {
1287 refreshListOfFilesFragment();
1288 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1291 if (mWaitingToSend
!= null
) {
1292 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1293 if (mWaitingToSend
.isDown()) {
1294 sendDownloadedFile();
1299 if (intent
!= null
) {
1300 removeStickyBroadcast(intent
);
1305 private boolean isDescendant(String downloadedRemotePath
) {
1306 OCFile currentDir
= getCurrentDir();
1307 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1310 private boolean isSameAccount(Context context
, Intent intent
) {
1311 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1312 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1317 public void browseToRoot() {
1318 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1319 if (listOfFiles
!= null
) { // should never be null, indeed
1320 while (mDirectories
.getCount() > 1) {
1323 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1324 listOfFiles
.listDirectory(root
);
1325 setFile(listOfFiles
.getCurrentFile());
1326 startSyncFolderOperation(root
, false
);
1328 cleanSecondFragment();
1332 public void browseTo(OCFile folder
) {
1333 if (folder
== null
|| !folder
.isFolder()) {
1334 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1336 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1337 if (listOfFiles
!= null
) {
1338 setNavigationListWithFolder(folder
);
1339 listOfFiles
.listDirectory(folder
);
1340 setFile(listOfFiles
.getCurrentFile());
1341 startSyncFolderOperation(folder
, false
);
1343 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1345 cleanSecondFragment();
1352 * Updates action bar and second fragment, if in dual pane mode.
1355 public void onBrowsedDownTo(OCFile directory
) {
1356 pushDirname(directory
);
1357 cleanSecondFragment();
1360 startSyncFolderOperation(directory
, false
);
1365 * Shows the information of the {@link OCFile} received as a
1366 * parameter in the second fragment.
1368 * @param file {@link OCFile} whose details will be shown
1371 public void showDetails(OCFile file
) {
1372 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1373 setSecondFragment(detailFragment
);
1374 updateFragmentsVisibility(true
);
1375 updateNavigationElementsInActionBar(file
);
1383 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1384 ActionBar actionBar
= getSupportActionBar();
1385 if (chosenFile
== null
|| mDualPane
) {
1386 // only list of files - set for browsing through folders
1387 OCFile currentDir
= getCurrentDir();
1388 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1389 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1390 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1392 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1394 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1395 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1398 actionBar
.setDisplayHomeAsUpEnabled(true
);
1399 actionBar
.setDisplayShowTitleEnabled(true
);
1400 actionBar
.setTitle(chosenFile
.getFileName());
1401 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1407 protected ServiceConnection
newTransferenceServiceConnection() {
1408 return new ListServiceConnection();
1411 /** Defines callbacks for service binding, passed to bindService() */
1412 private class ListServiceConnection
implements ServiceConnection
{
1415 public void onServiceConnected(ComponentName component
, IBinder service
) {
1416 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1417 Log_OC
.d(TAG
, "Download service connected");
1418 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1419 if (mWaitingToPreview
!= null
)
1420 if (getStorageManager() != null
) {
1421 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1422 if (!mWaitingToPreview
.isDown()) {
1423 requestForDownload();
1427 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1428 Log_OC
.d(TAG
, "Upload service connected");
1429 mUploaderBinder
= (FileUploaderBinder
) service
;
1433 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1434 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1435 if (listOfFiles
!= null
) {
1436 listOfFiles
.listDirectory();
1438 FileFragment secondFragment
= getSecondFragment();
1439 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1440 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1441 detailFragment
.listenForTransferProgress();
1442 detailFragment
.updateFileDetails(false
, false
);
1447 public void onServiceDisconnected(ComponentName component
) {
1448 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1449 Log_OC
.d(TAG
, "Download service disconnected");
1450 mDownloaderBinder
= null
;
1451 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1452 Log_OC
.d(TAG
, "Upload service disconnected");
1453 mUploaderBinder
= null
;
1461 * Launch an intent to request the PIN code to the user before letting him use the app
1463 private void requestPinCode() {
1464 boolean pinStart
= false
;
1465 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1466 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1468 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1469 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1476 public void onSavedCertificate() {
1477 startSyncFolderOperation(getCurrentDir(), false
);
1482 public void onFailedSavingCertificate() {
1483 showDialog(DIALOG_CERT_NOT_SAVED
);
1487 public void onCancelCertificate() {
1492 * Updates the view associated to the activity after the finish of some operation over files
1493 * in the current account.
1495 * @param operation Removal operation performed.
1496 * @param result Result of the removal.
1499 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1500 super.onRemoteOperationFinish(operation
, result
);
1502 if (operation
instanceof RemoveFileOperation
) {
1503 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1505 } else if (operation
instanceof RenameFileOperation
) {
1506 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1508 } else if (operation
instanceof SynchronizeFileOperation
) {
1509 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1511 } else if (operation
instanceof CreateFolderOperation
) {
1512 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1514 } else if (operation
instanceof CreateShareOperation
) {
1515 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1517 } else if (operation
instanceof UnshareLinkOperation
) {
1518 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1520 } else if (operation
instanceof MoveFileOperation
) {
1521 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1527 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1528 if (result
.isSuccess()) {
1529 refreshShowDetails();
1530 refreshListOfFilesFragment();
1535 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1536 if (result
.isSuccess()) {
1537 refreshShowDetails();
1538 refreshListOfFilesFragment();
1540 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1541 cleanSecondFragment();
1542 refreshListOfFilesFragment();
1546 private void refreshShowDetails() {
1547 FileFragment details
= getSecondFragment();
1548 if (details
!= null
) {
1549 OCFile file
= details
.getFile();
1551 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1552 if (details
instanceof PreviewMediaFragment
) {
1553 // Refresh OCFile of the fragment
1554 ((PreviewMediaFragment
) details
).updateFile(file
);
1559 invalidateOptionsMenu();
1564 * Updates the view associated to the activity after the finish of an operation trying to remove a
1567 * @param operation Removal operation performed.
1568 * @param result Result of the removal.
1570 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1571 dismissLoadingDialog();
1573 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1577 if (result
.isSuccess()) {
1578 OCFile removedFile
= operation
.getFile();
1579 FileFragment second
= getSecondFragment();
1580 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1581 if (second
instanceof PreviewMediaFragment
) {
1582 ((PreviewMediaFragment
)second
).stopPreview(true
);
1584 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1585 cleanSecondFragment();
1587 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1588 refreshListOfFilesFragment();
1590 invalidateOptionsMenu();
1592 if (result
.isSslRecoverableException()) {
1593 mLastSslUntrustedServerResult
= result
;
1594 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1601 * Updates the view associated to the activity after the finish of an operation trying to move a
1604 * @param operation Move operation performed.
1605 * @param result Result of the move operation.
1607 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1608 if (result
.isSuccess()) {
1609 dismissLoadingDialog();
1610 refreshListOfFilesFragment();
1612 dismissLoadingDialog();
1614 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1615 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1619 } catch (NotFoundException e
) {
1620 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1627 * Updates the view associated to the activity after the finish of an operation trying to rename a
1630 * @param operation Renaming operation performed.
1631 * @param result Result of the renaming.
1633 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1634 dismissLoadingDialog();
1635 OCFile renamedFile
= operation
.getFile();
1636 if (result
.isSuccess()) {
1637 FileFragment details
= getSecondFragment();
1638 if (details
!= null
) {
1639 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1640 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1641 showDetails(renamedFile
);
1643 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1644 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1645 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1646 int position
= ((PreviewMediaFragment
)details
).getPosition();
1647 startMediaPreview(renamedFile
, position
, true
);
1649 getFileOperationsHelper().openFile(renamedFile
);
1654 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1655 refreshListOfFilesFragment();
1659 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1663 if (result
.isSslRecoverableException()) {
1664 mLastSslUntrustedServerResult
= result
;
1665 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1670 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1671 dismissLoadingDialog();
1672 OCFile syncedFile
= operation
.getLocalFile();
1673 if (!result
.isSuccess()) {
1674 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1675 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1676 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1677 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1683 if (operation
.transferWasRequested()) {
1684 onTransferStateChanged(syncedFile
, true
, true
);
1687 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1695 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1697 * @param operation Creation operation performed.
1698 * @param result Result of the creation.
1700 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1701 if (result
.isSuccess()) {
1702 dismissLoadingDialog();
1703 refreshListOfFilesFragment();
1705 dismissLoadingDialog();
1707 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1708 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1712 } catch (NotFoundException e
) {
1713 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1723 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1724 refreshListOfFilesFragment();
1725 FileFragment details
= getSecondFragment();
1726 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1727 if (downloading
|| uploading
) {
1728 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1730 if (!file
.fileExists()) {
1731 cleanSecondFragment();
1733 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1741 private void requestForDownload() {
1742 Account account
= getAccount();
1743 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1744 Intent i
= new Intent(this, FileDownloader
.class);
1745 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1746 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1752 private OCFile
getCurrentDir() {
1753 OCFile file
= getFile();
1755 if (file
.isFolder()) {
1757 } else if (getStorageManager() != null
) {
1758 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1759 return getStorageManager().getFileByPath(parentPath
);
1765 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1766 long currentSyncTime
= System
.currentTimeMillis();
1768 mSyncInProgress
= true
;
1770 // perform folder synchronization
1771 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1774 getFileOperationsHelper().isSharedSupported(),
1776 getStorageManager(),
1778 getApplicationContext()
1780 synchFolderOp
.execute(getAccount(), this, null
, null
);
1782 setSupportProgressBarIndeterminateVisibility(true
);
1784 setBackgroundText();
1788 * Show untrusted cert dialog
1790 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1791 // Show a dialog with the certificate info
1792 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1793 FragmentManager fm
= getSupportFragmentManager();
1794 FragmentTransaction ft
= fm
.beginTransaction();
1795 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1798 private void requestForDownload(OCFile file
) {
1799 Account account
= getAccount();
1800 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1801 Intent i
= new Intent(this, FileDownloader
.class);
1802 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1803 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1808 private void sendDownloadedFile(){
1809 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1810 mWaitingToSend
= null
;
1815 * Requests the download of the received {@link OCFile} , updates the UI
1816 * to monitor the download progress and prepares the activity to send the file
1817 * when the download finishes.
1819 * @param file {@link OCFile} to download and preview.
1821 public void startDownloadForSending(OCFile file
) {
1822 mWaitingToSend
= file
;
1823 requestForDownload(mWaitingToSend
);
1824 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1825 updateFragmentsVisibility(hasSecondFragment
);
1829 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1831 * @param file Image {@link OCFile} to show.
1833 public void startImagePreview(OCFile file
) {
1834 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1835 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1836 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1837 startActivity(showDetailsIntent
);
1842 * Stars the preview of an already down media {@link OCFile}.
1844 * @param file Media {@link OCFile} to preview.
1845 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1846 * @param autoplay When 'true', the playback will start without user interactions.
1848 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1849 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1850 setSecondFragment(mediaFragment
);
1851 updateFragmentsVisibility(true
);
1852 updateNavigationElementsInActionBar(file
);
1857 * Requests the download of the received {@link OCFile} , updates the UI
1858 * to monitor the download progress and prepares the activity to preview
1859 * or open the file when the download finishes.
1861 * @param file {@link OCFile} to download and preview.
1863 public void startDownloadForPreview(OCFile file
) {
1864 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1865 setSecondFragment(detailFragment
);
1866 mWaitingToPreview
= file
;
1867 requestForDownload();
1868 updateFragmentsVisibility(true
);
1869 updateNavigationElementsInActionBar(file
);
1874 public void cancelTransference(OCFile file
) {
1875 getFileOperationsHelper().cancelTransference(file
);
1876 if (mWaitingToPreview
!= null
&&
1877 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1878 mWaitingToPreview
= null
;
1880 if (mWaitingToSend
!= null
&&
1881 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1882 mWaitingToSend
= null
;
1884 onTransferStateChanged(file
, false
, false
);
1888 public void onRefresh(boolean ignoreETag
) {
1889 refreshList(ignoreETag
);
1893 public void onRefresh() {
1897 private void refreshList(boolean ignoreETag
) {
1898 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1899 if (listOfFiles
!= null
) {
1900 OCFile folder
= listOfFiles
.getCurrentFile();
1901 if (folder
!= null
) {
1902 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1903 listDirectory(mFile);*/
1904 startSyncFolderOperation(folder
, ignoreETag
);
1909 private void sortByDate(boolean ascending
){
1910 getListOfFilesFragment().sortByDate(ascending
);
1913 private void sortBySize(boolean ascending
){
1914 getListOfFilesFragment().sortBySize(ascending
);
1917 private void sortByName(boolean ascending
){
1918 getListOfFilesFragment().sortByName(ascending
);