FileDisplayActivity.java 54 KB

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