FileDisplayActivity.java 65 KB

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