FileDisplayActivity.java 65 KB

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