FileDisplayActivity.java 57 KB

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