FileDisplayActivity.java 61 KB

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