FileDisplayActivity.java 62 KB

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