FileDisplayActivity.java 68 KB

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