FileDisplayActivity.java 65 KB

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