FileDisplayActivity.java 64 KB

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