FileDisplayActivity.java 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author David A. Velasco
  6. * Copyright (C) 2011 Bartek Przybylski
  7. * Copyright (C) 2016 ownCloud Inc.
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. package com.owncloud.android.ui.activity;
  22. import android.Manifest;
  23. import android.accounts.Account;
  24. import android.accounts.AuthenticatorException;
  25. import android.annotation.TargetApi;
  26. import android.content.BroadcastReceiver;
  27. import android.content.ComponentName;
  28. import android.content.ContentResolver;
  29. import android.content.Context;
  30. import android.content.DialogInterface;
  31. import android.content.Intent;
  32. import android.content.IntentFilter;
  33. import android.content.ServiceConnection;
  34. import android.content.SharedPreferences;
  35. import android.content.SyncRequest;
  36. import android.content.pm.PackageManager;
  37. import android.content.res.Resources.NotFoundException;
  38. import android.database.Cursor;
  39. import android.net.Uri;
  40. import android.os.Build;
  41. import android.os.Bundle;
  42. import android.os.IBinder;
  43. import android.preference.PreferenceManager;
  44. import android.provider.OpenableColumns;
  45. import android.support.design.widget.Snackbar;
  46. import android.support.v4.app.Fragment;
  47. import android.support.v4.app.FragmentManager;
  48. import android.support.v4.app.FragmentTransaction;
  49. import android.support.v4.content.ContextCompat;
  50. import android.support.v4.view.GravityCompat;
  51. import android.support.v7.app.AlertDialog;
  52. import android.view.Menu;
  53. import android.view.MenuInflater;
  54. import android.view.MenuItem;
  55. import android.view.View;
  56. import android.widget.ProgressBar;
  57. import android.widget.RelativeLayout;
  58. import android.widget.Toast;
  59. import com.owncloud.android.MainApp;
  60. import com.owncloud.android.R;
  61. import com.owncloud.android.datamodel.FileDataStorageManager;
  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.network.CertificateCombinedException;
  68. import com.owncloud.android.lib.common.operations.RemoteOperation;
  69. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  70. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  71. import com.owncloud.android.lib.common.utils.Log_OC;
  72. import com.owncloud.android.operations.CopyFileOperation;
  73. import com.owncloud.android.operations.CreateFolderOperation;
  74. import com.owncloud.android.operations.MoveFileOperation;
  75. import com.owncloud.android.operations.RefreshFolderOperation;
  76. import com.owncloud.android.operations.RemoveFileOperation;
  77. import com.owncloud.android.operations.RenameFileOperation;
  78. import com.owncloud.android.operations.SynchronizeFileOperation;
  79. import com.owncloud.android.operations.UploadFileOperation;
  80. import com.owncloud.android.services.observer.FileObserverService;
  81. import com.owncloud.android.syncadapter.FileSyncAdapter;
  82. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  83. import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
  84. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
  85. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
  86. import com.owncloud.android.ui.dialog.UploadSourceDialogFragment;
  87. import com.owncloud.android.ui.fragment.FileDetailFragment;
  88. import com.owncloud.android.ui.fragment.FileFragment;
  89. import com.owncloud.android.ui.fragment.OCFileListFragment;
  90. import com.owncloud.android.ui.preview.PreviewImageActivity;
  91. import com.owncloud.android.ui.preview.PreviewImageFragment;
  92. import com.owncloud.android.ui.preview.PreviewMediaFragment;
  93. import com.owncloud.android.ui.preview.PreviewTextFragment;
  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.FileStorageUtils;
  98. import com.owncloud.android.utils.PermissionUtil;
  99. import com.owncloud.android.utils.UriUtils;
  100. import java.io.File;
  101. /**
  102. * Displays, what files the user has available in his ownCloud. This is the main view.
  103. */
  104. public class FileDisplayActivity extends HookActivity implements
  105. FileFragment.ContainerActivity,
  106. OnSslUntrustedCertListener, OnEnforceableRefreshListener {
  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 ProgressBar mProgressBar;
  115. private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
  116. private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
  117. private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
  118. public static final int DIALOG_SHORT_WAIT = 0;
  119. private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
  120. public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
  121. public static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
  122. public static final int ACTION_SELECT_MULTIPLE_FILES = 2;
  123. public static final int ACTION_MOVE_FILES = 3;
  124. public static final int ACTION_COPY_FILES = 4;
  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 boolean mSyncInProgress = false;
  130. private static String DIALOG_UNTRUSTED_CERT = "DIALOG_UNTRUSTED_CERT";
  131. private static String DIALOG_CREATE_FOLDER = "DIALOG_CREATE_FOLDER";
  132. private static String DIALOG_UPLOAD_SOURCE = "DIALOG_UPLOAD_SOURCE";
  133. private static String DIALOG_CERT_NOT_SAVED = "DIALOG_CERT_NOT_SAVED";
  134. private OCFile mWaitingToSend;
  135. @Override
  136. protected void onCreate(Bundle savedInstanceState) {
  137. Log_OC.v(TAG, "onCreate() start");
  138. super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account
  139. // is valid
  140. /// grant that FileObserverService is watching favorite files
  141. if (savedInstanceState == null) {
  142. Intent initObserversIntent = FileObserverService.makeInitIntent(this);
  143. startService(initObserversIntent);
  144. }
  145. /// Load of saved instance state
  146. if (savedInstanceState != null) {
  147. mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(
  148. FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
  149. mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
  150. mWaitingToSend = (OCFile) savedInstanceState.getParcelable(
  151. FileDisplayActivity.KEY_WAITING_TO_SEND);
  152. } else {
  153. mWaitingToPreview = null;
  154. mSyncInProgress = false;
  155. mWaitingToSend = null;
  156. }
  157. /// USER INTERFACE
  158. // Inflate and set the layout view
  159. setContentView(R.layout.files);
  160. // Navigation Drawer
  161. initDrawer();
  162. mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
  163. mProgressBar.setIndeterminateDrawable(
  164. ContextCompat.getDrawable(this,
  165. R.drawable.actionbar_progress_indeterminate_horizontal));
  166. mDualPane = getResources().getBoolean(R.bool.large_land_layout);
  167. mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
  168. mRightFragmentContainer = findViewById(R.id.right_fragment_container);
  169. // Action bar setup
  170. getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS,
  171. // according to the official
  172. // documentation
  173. // enable ActionBar app icon to behave as action to toggle nav drawer
  174. //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  175. getSupportActionBar().setHomeButtonEnabled(true);
  176. Log_OC.v(TAG, "onCreate() end");
  177. }
  178. @Override
  179. protected void onPostCreate(Bundle savedInstanceState) {
  180. super.onPostCreate(savedInstanceState);
  181. if (PermissionUtil.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  182. // Check if we should show an explanation
  183. if (PermissionUtil.shouldShowRequestPermissionRationale(this,
  184. Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  185. // Show explanation to the user and then request permission
  186. Snackbar snackbar = Snackbar.make(findViewById(R.id.ListLayout), R.string.permission_storage_access,
  187. Snackbar.LENGTH_INDEFINITE)
  188. .setAction(R.string.common_ok, new View.OnClickListener() {
  189. @Override
  190. public void onClick(View v) {
  191. PermissionUtil.requestWriteExternalStoreagePermission(FileDisplayActivity.this);
  192. }
  193. });
  194. DisplayUtils.colorSnackbar(this, snackbar);
  195. snackbar.show();
  196. } else {
  197. // No explanation needed, request the permission.
  198. PermissionUtil.requestWriteExternalStoreagePermission(this);
  199. }
  200. }
  201. if (savedInstanceState == null) {
  202. createMinFragments();
  203. }
  204. mProgressBar.setIndeterminate(mSyncInProgress);
  205. // always AFTER setContentView(...) in onCreate(); to work around bug in its implementation
  206. setBackgroundText();
  207. }
  208. @Override
  209. public void onRequestPermissionsResult(int requestCode,
  210. String permissions[], int[] grantResults) {
  211. switch (requestCode) {
  212. case PermissionUtil.PERMISSIONS_WRITE_EXTERNAL_STORAGE: {
  213. // If request is cancelled, result arrays are empty.
  214. if (grantResults.length > 0
  215. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  216. // permission was granted
  217. startSynchronization();
  218. // toggle on is save since this is the only scenario this code gets accessed
  219. } else {
  220. // permission denied --> do nothing
  221. }
  222. return;
  223. }
  224. }
  225. }
  226. @Override
  227. protected void onStart() {
  228. Log_OC.v(TAG, "onStart() start");
  229. super.onStart();
  230. Log_OC.v(TAG, "onStart() end");
  231. }
  232. @Override
  233. protected void onStop() {
  234. Log_OC.v(TAG, "onStop() start");
  235. super.onStop();
  236. Log_OC.v(TAG, "onStop() end");
  237. }
  238. @Override
  239. protected void onDestroy() {
  240. Log_OC.v(TAG, "onDestroy() start");
  241. super.onDestroy();
  242. Log_OC.v(TAG, "onDestroy() end");
  243. }
  244. /**
  245. * Called when the ownCloud {@link Account} associated to the Activity was just updated.
  246. */
  247. @Override
  248. protected void onAccountSet(boolean stateWasRecovered) {
  249. super.onAccountSet(stateWasRecovered);
  250. if (getAccount() != null) {
  251. /// Check whether the 'main' OCFile handled by the Activity is contained in the
  252. // current Account
  253. OCFile file = getFile();
  254. // get parent from path
  255. String parentPath = "";
  256. if (file != null) {
  257. if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
  258. // upload in progress - right now, files are not inserted in the local
  259. // cache until the upload is successful get parent from path
  260. parentPath = file.getRemotePath().substring(0,
  261. file.getRemotePath().lastIndexOf(file.getFileName()));
  262. if (getStorageManager().getFileByPath(parentPath) == null)
  263. file = null; // not able to know the directory where the file is uploading
  264. } else {
  265. file = getStorageManager().getFileByPath(file.getRemotePath());
  266. // currentDir = null if not in the current Account
  267. }
  268. }
  269. if (file == null) {
  270. // fall back to root folder
  271. file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
  272. }
  273. setFile(file);
  274. if (mAccountWasSet) {
  275. setUsernameInDrawer((RelativeLayout) findViewById(R.id.left_drawer), getAccount());
  276. }
  277. if (!stateWasRecovered) {
  278. Log_OC.d(TAG, "Initializing Fragments in onAccountChanged..");
  279. initFragmentsWithFile();
  280. if (file.isFolder()) {
  281. startSyncFolderOperation(file, false);
  282. }
  283. } else {
  284. updateFragmentsVisibility(!file.isFolder());
  285. updateActionBarTitleAndHomeButton(file.isFolder() ? null : file);
  286. }
  287. }
  288. }
  289. private void createMinFragments() {
  290. OCFileListFragment listOfFiles = new OCFileListFragment();
  291. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  292. transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
  293. transaction.commit();
  294. }
  295. private void initFragmentsWithFile() {
  296. if (getAccount() != null && getFile() != null) {
  297. /// First fragment
  298. OCFileListFragment listOfFiles = getListOfFilesFragment();
  299. if (listOfFiles != null) {
  300. listOfFiles.listDirectory(getCurrentDir());
  301. // TODO Enable when "On Device" is recovered
  302. // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
  303. } else {
  304. Log_OC.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
  305. }
  306. /// Second fragment
  307. OCFile file = getFile();
  308. Fragment secondFragment = chooseInitialSecondFragment(file);
  309. if (secondFragment != null) {
  310. setSecondFragment(secondFragment);
  311. updateFragmentsVisibility(true);
  312. updateActionBarTitleAndHomeButton(file);
  313. } else {
  314. cleanSecondFragment();
  315. if (file.isDown() && PreviewTextFragment.canBePreviewed(file))
  316. startTextPreview(file);
  317. }
  318. } else {
  319. Log_OC.wtf(TAG, "initFragments() called with invalid NULLs!");
  320. if (getAccount() == null) {
  321. Log_OC.wtf(TAG, "\t account is NULL");
  322. }
  323. if (getFile() == null) {
  324. Log_OC.wtf(TAG, "\t file is NULL");
  325. }
  326. }
  327. }
  328. private Fragment chooseInitialSecondFragment(OCFile file) {
  329. Fragment secondFragment = null;
  330. if (file != null && !file.isFolder()) {
  331. if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
  332. && file.getLastSyncDateForProperties() > 0 // temporal fix
  333. ) {
  334. int startPlaybackPosition =
  335. getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
  336. boolean autoplay =
  337. getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
  338. secondFragment = new PreviewMediaFragment(file, getAccount(),
  339. startPlaybackPosition, autoplay);
  340. } else if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) {
  341. secondFragment = null;
  342. } else {
  343. secondFragment = FileDetailFragment.newInstance(file, getAccount());
  344. }
  345. }
  346. return secondFragment;
  347. }
  348. /**
  349. * Replaces the second fragment managed by the activity with the received as
  350. * a parameter.
  351. * <p/>
  352. * Assumes never will be more than two fragments managed at the same time.
  353. *
  354. * @param fragment New second Fragment to set.
  355. */
  356. private void setSecondFragment(Fragment fragment) {
  357. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  358. transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
  359. transaction.commit();
  360. }
  361. private void updateFragmentsVisibility(boolean existsSecondFragment) {
  362. if (mDualPane) {
  363. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  364. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  365. }
  366. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  367. mRightFragmentContainer.setVisibility(View.VISIBLE);
  368. }
  369. } else if (existsSecondFragment) {
  370. if (mLeftFragmentContainer.getVisibility() != View.GONE) {
  371. mLeftFragmentContainer.setVisibility(View.GONE);
  372. }
  373. if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
  374. mRightFragmentContainer.setVisibility(View.VISIBLE);
  375. }
  376. } else {
  377. if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
  378. mLeftFragmentContainer.setVisibility(View.VISIBLE);
  379. }
  380. if (mRightFragmentContainer.getVisibility() != View.GONE) {
  381. mRightFragmentContainer.setVisibility(View.GONE);
  382. }
  383. }
  384. }
  385. private OCFileListFragment getListOfFilesFragment() {
  386. Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(
  387. FileDisplayActivity.TAG_LIST_OF_FILES);
  388. if (listOfFiles != null) {
  389. return (OCFileListFragment) listOfFiles;
  390. }
  391. Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
  392. return null;
  393. }
  394. public FileFragment getSecondFragment() {
  395. Fragment second = getSupportFragmentManager().findFragmentByTag(
  396. FileDisplayActivity.TAG_SECOND_FRAGMENT);
  397. if (second != null) {
  398. return (FileFragment) second;
  399. }
  400. return null;
  401. }
  402. protected void cleanSecondFragment() {
  403. Fragment second = getSecondFragment();
  404. if (second != null) {
  405. FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
  406. tr.remove(second);
  407. tr.commit();
  408. }
  409. updateFragmentsVisibility(false);
  410. updateActionBarTitleAndHomeButton(null);
  411. }
  412. protected void refreshListOfFilesFragment() {
  413. OCFileListFragment fileListFragment = getListOfFilesFragment();
  414. if (fileListFragment != null) {
  415. fileListFragment.listDirectory();
  416. // TODO Enable when "On Device" is recovered ?
  417. // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
  418. }
  419. }
  420. protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath,
  421. boolean success) {
  422. FileFragment secondFragment = getSecondFragment();
  423. boolean waitedPreview = (mWaitingToPreview != null &&
  424. mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
  425. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  426. FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
  427. OCFile fileInFragment = detailsFragment.getFile();
  428. if (fileInFragment != null &&
  429. !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
  430. // the user browsed to other file ; forget the automatic preview
  431. mWaitingToPreview = null;
  432. } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
  433. // grant that the right panel updates the progress bar
  434. detailsFragment.listenForTransferProgress();
  435. detailsFragment.updateFileDetails(true, false);
  436. } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
  437. // update the right panel
  438. boolean detailsFragmentChanged = false;
  439. if (waitedPreview) {
  440. if (success) {
  441. mWaitingToPreview = getStorageManager().getFileById(
  442. mWaitingToPreview.getFileId()); // update the file from database,
  443. // for the local storage path
  444. if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
  445. startMediaPreview(mWaitingToPreview, 0, true);
  446. detailsFragmentChanged = true;
  447. } else if (PreviewTextFragment.canBePreviewed(mWaitingToPreview)) {
  448. startTextPreview(mWaitingToPreview);
  449. detailsFragmentChanged = true;
  450. } else {
  451. getFileOperationsHelper().openFile(mWaitingToPreview);
  452. }
  453. }
  454. mWaitingToPreview = null;
  455. }
  456. if (!detailsFragmentChanged) {
  457. detailsFragment.updateFileDetails(false, (success));
  458. }
  459. }
  460. }
  461. }
  462. @Override
  463. public boolean onPrepareOptionsMenu(Menu menu) {
  464. boolean drawerOpen = mDrawerLayout.isDrawerOpen(GravityCompat.START);
  465. menu.findItem(R.id.action_upload).setVisible(!drawerOpen);
  466. menu.findItem(R.id.action_create_dir).setVisible(!drawerOpen);
  467. menu.findItem(R.id.action_sort).setVisible(!drawerOpen);
  468. menu.findItem(R.id.action_sync_account).setVisible(!drawerOpen);
  469. menu.findItem(R.id.action_switch_view).setVisible(!drawerOpen);
  470. return super.onPrepareOptionsMenu(menu);
  471. }
  472. @Override
  473. public boolean onCreateOptionsMenu(Menu menu) {
  474. MenuInflater inflater = getMenuInflater();
  475. inflater.inflate(R.menu.main_menu, menu);
  476. return true;
  477. }
  478. @Override
  479. public boolean onOptionsItemSelected(MenuItem item) {
  480. boolean retval = true;
  481. switch (item.getItemId()) {
  482. case R.id.action_create_dir: {
  483. CreateFolderDialogFragment dialog =
  484. CreateFolderDialogFragment.newInstance(getCurrentDir());
  485. dialog.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER);
  486. break;
  487. }
  488. case R.id.action_sync_account: {
  489. startSynchronization();
  490. break;
  491. }
  492. case R.id.action_upload: {
  493. UploadSourceDialogFragment dialog =
  494. UploadSourceDialogFragment.newInstance(getAccount());
  495. dialog.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE);
  496. break;
  497. }
  498. case android.R.id.home: {
  499. FileFragment second = getSecondFragment();
  500. OCFile currentDir = getCurrentDir();
  501. if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
  502. mDrawerLayout.closeDrawer(GravityCompat.START);
  503. } else if ((currentDir != null && currentDir.getParentId() != 0) ||
  504. (second != null && second.getFile() != null)) {
  505. onBackPressed();
  506. } else {
  507. mDrawerLayout.openDrawer(GravityCompat.START);
  508. }
  509. break;
  510. }
  511. case R.id.action_sort: {
  512. SharedPreferences appPreferences = PreferenceManager
  513. .getDefaultSharedPreferences(this);
  514. // Read sorting order, default to sort by name ascending
  515. Integer sortOrder = appPreferences
  516. .getInt("sortOrder", FileStorageUtils.SORT_NAME);
  517. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  518. builder.setTitle(R.string.actionbar_sort_title)
  519. .setSingleChoiceItems(R.array.actionbar_sortby, sortOrder,
  520. new DialogInterface.OnClickListener() {
  521. public void onClick(DialogInterface dialog, int which) {
  522. switch (which) {
  523. case 0:
  524. sortByName(true);
  525. break;
  526. case 1:
  527. sortByDate(false);
  528. break;
  529. }
  530. dialog.dismiss();
  531. }
  532. });
  533. builder.create().show();
  534. break;
  535. }
  536. case R.id.action_switch_view: {
  537. if (isGridView()) {
  538. item.setTitle(getString(R.string.action_switch_grid_view));
  539. item.setIcon(ContextCompat.getDrawable(getApplicationContext(),
  540. R.drawable.ic_view_module));
  541. getListOfFilesFragment().setListAsPreferred();
  542. } else {
  543. item.setTitle(getApplicationContext().getString(R.string.action_switch_list_view));
  544. item.setIcon(ContextCompat.getDrawable(getApplicationContext(),
  545. R.drawable.ic_view_list));
  546. getListOfFilesFragment().setGridAsPreferred();
  547. }
  548. return true;
  549. }
  550. default:
  551. retval = super.onOptionsItemSelected(item);
  552. }
  553. return retval;
  554. }
  555. private void startSynchronization() {
  556. Log_OC.d(TAG, "Got to start sync");
  557. if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
  558. Log_OC.d(TAG, "Canceling all syncs for " + MainApp.getAuthority());
  559. ContentResolver.cancelSync(null, MainApp.getAuthority());
  560. // cancel the current synchronizations of any ownCloud account
  561. Bundle bundle = new Bundle();
  562. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  563. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
  564. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  565. MainApp.getAuthority());
  566. ContentResolver.requestSync(
  567. getAccount(),
  568. MainApp.getAuthority(), bundle);
  569. } else {
  570. Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
  571. MainApp.getAuthority() + " with new API");
  572. SyncRequest.Builder builder = new SyncRequest.Builder();
  573. builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
  574. builder.setExpedited(true);
  575. builder.setManual(true);
  576. builder.syncOnce();
  577. // Fix bug in Android Lollipop when you click on refresh the whole account
  578. Bundle extras = new Bundle();
  579. builder.setExtras(extras);
  580. SyncRequest request = builder.build();
  581. ContentResolver.requestSync(request);
  582. }
  583. }
  584. /**
  585. * Called, when the user selected something for uploading
  586. */
  587. @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  588. @Override
  589. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  590. if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK ||
  591. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  592. //getClipData is only supported on api level 16+, Jelly Bean
  593. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN &&
  594. data.getClipData() != null &&
  595. data.getClipData().getItemCount() > 0) {
  596. for (int i = 0; i < data.getClipData().getItemCount(); i++) {
  597. Intent intent = new Intent();
  598. intent.setData(data.getClipData().getItemAt(i).getUri());
  599. requestSimpleUpload(intent, resultCode);
  600. }
  601. } else {
  602. requestSimpleUpload(data, resultCode);
  603. }
  604. } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK ||
  605. resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  606. requestMultipleUpload(data, resultCode);
  607. } else if (requestCode == ACTION_MOVE_FILES && resultCode == RESULT_OK) {
  608. final Intent fData = data;
  609. final int fResultCode = resultCode;
  610. getHandler().postDelayed(
  611. new Runnable() {
  612. @Override
  613. public void run() {
  614. requestMoveOperation(fData, fResultCode);
  615. }
  616. },
  617. DELAY_TO_REQUEST_OPERATIONS_LATER
  618. );
  619. } else if (requestCode == ACTION_COPY_FILES && resultCode == RESULT_OK) {
  620. final Intent fData = data;
  621. final int fResultCode = resultCode;
  622. getHandler().postDelayed(
  623. new Runnable() {
  624. @Override
  625. public void run() {
  626. requestCopyOperation(fData, fResultCode);
  627. }
  628. },
  629. DELAY_TO_REQUEST_OPERATIONS_LATER
  630. );
  631. } else {
  632. super.onActivityResult(requestCode, resultCode, data);
  633. }
  634. }
  635. private void requestMultipleUpload(Intent data, int resultCode) {
  636. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  637. if (filePaths != null) {
  638. String[] remotePaths = new String[filePaths.length];
  639. String remotePathBase = getCurrentDir().getRemotePath();
  640. for (int j = 0; j < remotePaths.length; j++) {
  641. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  642. }
  643. int behaviour = (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE) ? FileUploader
  644. .LOCAL_BEHAVIOUR_MOVE : FileUploader.LOCAL_BEHAVIOUR_COPY;
  645. FileUploader.uploadNewFile(
  646. this,
  647. getAccount(),
  648. filePaths,
  649. remotePaths,
  650. null, // MIME type will be detected from file name
  651. behaviour,
  652. false, // do not create parent folder if not existent
  653. UploadFileOperation.CREATED_BY_USER
  654. );
  655. } else {
  656. Log_OC.d(TAG, "User clicked on 'Update' with no selection");
  657. Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected),
  658. Toast.LENGTH_LONG);
  659. t.show();
  660. return;
  661. }
  662. }
  663. private void requestSimpleUpload(Intent data, int resultCode) {
  664. String filePath = null;
  665. String mimeType = null;
  666. Uri selectedImageUri = data.getData();
  667. try {
  668. mimeType = getContentResolver().getType(selectedImageUri);
  669. String fileManagerString = selectedImageUri.getPath();
  670. String selectedImagePath = UriUtils.getLocalPath(selectedImageUri, this);
  671. if (selectedImagePath != null)
  672. filePath = selectedImagePath;
  673. else
  674. filePath = fileManagerString;
  675. } catch (Exception e) {
  676. Log_OC.e(TAG, "Unexpected exception when trying to read the result of " +
  677. "Intent.ACTION_GET_CONTENT", e);
  678. } finally {
  679. if (filePath == null) {
  680. Log_OC.e(TAG, "Couldn't resolve path to file");
  681. Toast t = Toast.makeText(
  682. this, getString(R.string.filedisplay_unexpected_bad_get_content),
  683. Toast.LENGTH_LONG
  684. );
  685. t.show();
  686. return;
  687. }
  688. }
  689. Intent i = new Intent(this, FileUploader.class);
  690. i.putExtra(FileUploader.KEY_ACCOUNT,
  691. getAccount());
  692. OCFile currentDir = getCurrentDir();
  693. String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
  694. if (filePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
  695. Cursor cursor = getContentResolver().query(Uri.parse(filePath), null, null, null, null);
  696. try {
  697. if (cursor != null && cursor.moveToFirst()) {
  698. String displayName = cursor.getString(cursor.getColumnIndex(
  699. OpenableColumns.DISPLAY_NAME));
  700. Log_OC.v(TAG, "Display Name: " + displayName);
  701. displayName.replace(File.separatorChar, '_');
  702. displayName.replace(File.pathSeparatorChar, '_');
  703. remotePath += displayName + DisplayUtils.getComposedFileExtension(filePath);
  704. }
  705. // and what happens in case of error?; wrong target name for the upload
  706. } finally {
  707. cursor.close();
  708. }
  709. } else {
  710. remotePath += new File(filePath).getName();
  711. }
  712. int behaviour = (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE) ? FileUploader.LOCAL_BEHAVIOUR_MOVE :
  713. FileUploader.LOCAL_BEHAVIOUR_COPY;
  714. FileUploader.uploadNewFile(
  715. this,
  716. getAccount(),
  717. filePath,
  718. remotePath,
  719. behaviour,
  720. mimeType,
  721. false, // do not create parent folder if not existent
  722. UploadFileOperation.CREATED_BY_USER
  723. );
  724. }
  725. /**
  726. * Request the operation for moving the file/folder from one path to another
  727. *
  728. * @param data Intent received
  729. * @param resultCode Result code received
  730. */
  731. private void requestMoveOperation(Intent data, int resultCode) {
  732. OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  733. OCFile targetFile = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
  734. getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
  735. }
  736. /**
  737. * Request the operation for copying the file/folder from one path to another
  738. *
  739. * @param data Intent received
  740. * @param resultCode Result code received
  741. */
  742. private void requestCopyOperation(Intent data, int resultCode) {
  743. OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
  744. OCFile targetFile = data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
  745. getFileOperationsHelper().copyFile(folderToMoveAt, targetFile);
  746. }
  747. @Override
  748. public void onBackPressed() {
  749. if (!isDrawerOpen()) {
  750. OCFileListFragment listOfFiles = getListOfFilesFragment();
  751. if (mDualPane || getSecondFragment() == null) {
  752. OCFile currentDir = getCurrentDir();
  753. if (currentDir == null || currentDir.getParentId() == FileDataStorageManager.ROOT_PARENT_ID) {
  754. finish();
  755. return;
  756. }
  757. if (listOfFiles != null) { // should never be null, indeed
  758. listOfFiles.onBrowseUp();
  759. }
  760. }
  761. if (listOfFiles != null) { // should never be null, indeed
  762. setFile(listOfFiles.getCurrentFile());
  763. }
  764. cleanSecondFragment();
  765. } else {
  766. super.onBackPressed();
  767. }
  768. }
  769. @Override
  770. protected void onSaveInstanceState(Bundle outState) {
  771. // responsibility of restore is preferred in onCreate() before than in
  772. // onRestoreInstanceState when there are Fragments involved
  773. Log_OC.v(TAG, "onSaveInstanceState() start");
  774. super.onSaveInstanceState(outState);
  775. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  776. outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
  777. //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
  778. // mRefreshSharesInProgress);
  779. outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
  780. Log_OC.v(TAG, "onSaveInstanceState() end");
  781. }
  782. @Override
  783. protected void onResume() {
  784. Log_OC.v(TAG, "onResume() start");
  785. super.onResume();
  786. // refresh Navigation Drawer account list
  787. mNavigationDrawerAdapter.updateAccountList();
  788. // refresh list of files
  789. refreshListOfFilesFragment();
  790. // Listen for sync messages
  791. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  792. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  793. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  794. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  795. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  796. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  797. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  798. //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
  799. // syncIntentFilter);
  800. // Listen for upload messages
  801. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
  802. mUploadFinishReceiver = new UploadFinishReceiver();
  803. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  804. // Listen for download messages
  805. IntentFilter downloadIntentFilter = new IntentFilter(
  806. FileDownloader.getDownloadAddedMessage());
  807. downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
  808. mDownloadFinishReceiver = new DownloadFinishReceiver();
  809. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  810. Log_OC.v(TAG, "onResume() end");
  811. }
  812. @Override
  813. protected void onPause() {
  814. Log_OC.v(TAG, "onPause() start");
  815. if (mSyncBroadcastReceiver != null) {
  816. unregisterReceiver(mSyncBroadcastReceiver);
  817. //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
  818. mSyncBroadcastReceiver = null;
  819. }
  820. if (mUploadFinishReceiver != null) {
  821. unregisterReceiver(mUploadFinishReceiver);
  822. mUploadFinishReceiver = null;
  823. }
  824. if (mDownloadFinishReceiver != null) {
  825. unregisterReceiver(mDownloadFinishReceiver);
  826. mDownloadFinishReceiver = null;
  827. }
  828. super.onPause();
  829. Log_OC.v(TAG, "onPause() end");
  830. }
  831. private class SyncBroadcastReceiver extends BroadcastReceiver {
  832. /**
  833. * {@link BroadcastReceiver} to enable syncing feedback in UI
  834. */
  835. @Override
  836. public void onReceive(Context context, Intent intent) {
  837. try {
  838. String event = intent.getAction();
  839. Log_OC.d(TAG, "Received broadcast " + event);
  840. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  841. String synchFolderRemotePath =
  842. intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  843. RemoteOperationResult synchResult =
  844. (RemoteOperationResult) intent.getSerializableExtra(
  845. FileSyncAdapter.EXTRA_RESULT);
  846. boolean sameAccount = (getAccount() != null &&
  847. accountName.equals(getAccount().name) && getStorageManager() != null);
  848. if (sameAccount) {
  849. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  850. mSyncInProgress = true;
  851. } else {
  852. OCFile currentFile = (getFile() == null) ? null :
  853. getStorageManager().getFileByPath(getFile().getRemotePath());
  854. OCFile currentDir = (getCurrentDir() == null) ? null :
  855. getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
  856. if (currentDir == null) {
  857. // current folder was removed from the server
  858. Toast.makeText(FileDisplayActivity.this,
  859. String.format(
  860. getString(R.string.
  861. sync_current_folder_was_removed),
  862. synchFolderRemotePath),
  863. Toast.LENGTH_LONG)
  864. .show();
  865. browseToRoot();
  866. } else {
  867. if (currentFile == null && !getFile().isFolder()) {
  868. // currently selected file was removed in the server, and now we
  869. // know it
  870. cleanSecondFragment();
  871. currentFile = currentDir;
  872. }
  873. if (synchFolderRemotePath != null &&
  874. currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  875. OCFileListFragment fileListFragment = getListOfFilesFragment();
  876. if (fileListFragment != null) {
  877. fileListFragment.listDirectory();
  878. // TODO Enable when "On Device" is recovered ?
  879. // fileListFragment.listDirectory(currentDir,
  880. // MainApp.getOnlyOnDevice());
  881. }
  882. }
  883. setFile(currentFile);
  884. }
  885. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  886. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED
  887. .equals(event));
  888. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
  889. equals(event) &&/// TODO refactor and make common
  890. synchResult != null && !synchResult.isSuccess() &&
  891. (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
  892. synchResult.isIdPRedirection() ||
  893. (synchResult.isException() && synchResult.getException()
  894. instanceof AuthenticatorException))) {
  895. requestCredentialsUpdate(context);
  896. }
  897. }
  898. removeStickyBroadcast(intent);
  899. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  900. mProgressBar.setIndeterminate(mSyncInProgress);
  901. //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
  902. //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
  903. /*|| mRefreshSharesInProgress*/ //);
  904. setBackgroundText();
  905. }
  906. if (synchResult != null) {
  907. if (synchResult.getCode().equals(
  908. RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  909. mLastSslUntrustedServerResult = synchResult;
  910. }
  911. }
  912. } catch (RuntimeException e) {
  913. // avoid app crashes after changing the serial id of RemoteOperationResult
  914. // in owncloud library with broadcast notifications pending to process
  915. removeStickyBroadcast(intent);
  916. }
  917. }
  918. }
  919. /**
  920. * Show a text message on screen view for notifying user if content is
  921. * loading or folder is empty
  922. */
  923. private void setBackgroundText() {
  924. OCFileListFragment ocFileListFragment = getListOfFilesFragment();
  925. if (ocFileListFragment != null) {
  926. int message = R.string.file_list_loading;
  927. if (!mSyncInProgress) {
  928. // In case file list is empty
  929. message = R.string.file_list_empty;
  930. }
  931. ocFileListFragment.setMessageForEmptyList(getString(message));
  932. } else {
  933. Log_OC.e(TAG, "OCFileListFragment is null");
  934. }
  935. }
  936. /**
  937. * Once the file upload has finished -> update view
  938. */
  939. private class UploadFinishReceiver extends BroadcastReceiver {
  940. /**
  941. * Once the file upload has finished -> update view
  942. *
  943. * @author David A. Velasco
  944. * {@link BroadcastReceiver} to enable upload feedback in UI
  945. */
  946. @Override
  947. public void onReceive(Context context, Intent intent) {
  948. try {
  949. String uploadedRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
  950. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  951. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
  952. OCFile currentDir = getCurrentDir();
  953. boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
  954. (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
  955. if (sameAccount && isDescendant) {
  956. String linkedToRemotePath =
  957. intent.getStringExtra(FileUploader.EXTRA_LINKED_TO_PATH);
  958. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  959. refreshListOfFilesFragment();
  960. }
  961. }
  962. boolean uploadWasFine = intent.getBooleanExtra(
  963. FileUploader.EXTRA_UPLOAD_RESULT,
  964. false);
  965. boolean renamedInUpload = getFile().getRemotePath().
  966. equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
  967. boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
  968. renamedInUpload;
  969. FileFragment details = getSecondFragment();
  970. boolean detailFragmentIsShown = (details != null &&
  971. details instanceof FileDetailFragment);
  972. if (sameAccount && sameFile && detailFragmentIsShown) {
  973. if (uploadWasFine) {
  974. setFile(getStorageManager().getFileByPath(uploadedRemotePath));
  975. } else {
  976. //TODO remove upload progress bar after upload failed.
  977. }
  978. if (renamedInUpload) {
  979. String newName = (new File(uploadedRemotePath)).getName();
  980. Toast msg = Toast.makeText(
  981. context,
  982. String.format(
  983. getString(R.string.filedetails_renamed_in_upload_msg),
  984. newName),
  985. Toast.LENGTH_LONG);
  986. msg.show();
  987. }
  988. if (uploadWasFine || getFile().fileExists()) {
  989. ((FileDetailFragment) details).updateFileDetails(false, true);
  990. } else {
  991. cleanSecondFragment();
  992. }
  993. // Force the preview if the file is an image or text file
  994. if (uploadWasFine) {
  995. OCFile ocFile = getFile();
  996. if (PreviewImageFragment.canBePreviewed(ocFile))
  997. startImagePreview(getFile());
  998. else if (PreviewTextFragment.canBePreviewed(ocFile))
  999. startTextPreview(ocFile);
  1000. // TODO what about other kind of previews?
  1001. }
  1002. }
  1003. mProgressBar.setIndeterminate(false);
  1004. } finally {
  1005. if (intent != null) {
  1006. removeStickyBroadcast(intent);
  1007. }
  1008. }
  1009. }
  1010. // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
  1011. private boolean isAscendant(String linkedToRemotePath) {
  1012. OCFile currentDir = getCurrentDir();
  1013. return (
  1014. currentDir != null &&
  1015. currentDir.getRemotePath().startsWith(linkedToRemotePath)
  1016. );
  1017. }
  1018. }
  1019. /**
  1020. * Class waiting for broadcast events from the {@link FileDownloader} service.
  1021. * <p/>
  1022. * Updates the UI when a download is started or finished, provided that it is relevant for the
  1023. * current folder.
  1024. */
  1025. private class DownloadFinishReceiver extends BroadcastReceiver {
  1026. @Override
  1027. public void onReceive(Context context, Intent intent) {
  1028. try {
  1029. boolean sameAccount = isSameAccount(intent);
  1030. String downloadedRemotePath =
  1031. intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  1032. boolean isDescendant = isDescendant(downloadedRemotePath);
  1033. if (sameAccount && isDescendant) {
  1034. String linkedToRemotePath =
  1035. intent.getStringExtra(FileDownloader.EXTRA_LINKED_TO_PATH);
  1036. if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
  1037. refreshListOfFilesFragment();
  1038. }
  1039. refreshSecondFragment(
  1040. intent.getAction(),
  1041. downloadedRemotePath,
  1042. intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false)
  1043. );
  1044. }
  1045. if (mWaitingToSend != null) {
  1046. mWaitingToSend =
  1047. getStorageManager().getFileByPath(mWaitingToSend.getRemotePath());
  1048. if (mWaitingToSend.isDown()) {
  1049. sendDownloadedFile();
  1050. }
  1051. }
  1052. } finally {
  1053. if (intent != null) {
  1054. removeStickyBroadcast(intent);
  1055. }
  1056. }
  1057. }
  1058. private boolean isDescendant(String downloadedRemotePath) {
  1059. OCFile currentDir = getCurrentDir();
  1060. return (
  1061. currentDir != null &&
  1062. downloadedRemotePath != null &&
  1063. downloadedRemotePath.startsWith(currentDir.getRemotePath())
  1064. );
  1065. }
  1066. private boolean isAscendant(String linkedToRemotePath) {
  1067. OCFile currentDir = getCurrentDir();
  1068. return (
  1069. currentDir != null &&
  1070. currentDir.getRemotePath().startsWith(linkedToRemotePath)
  1071. );
  1072. }
  1073. private boolean isSameAccount(Intent intent) {
  1074. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  1075. return (accountName != null && getAccount() != null &&
  1076. accountName.equals(getAccount().name));
  1077. }
  1078. }
  1079. public void browseToRoot() {
  1080. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1081. if (listOfFiles != null) { // should never be null, indeed
  1082. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  1083. listOfFiles.listDirectory(root);
  1084. // TODO Enable when "On Device" is recovered ?
  1085. // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
  1086. setFile(listOfFiles.getCurrentFile());
  1087. startSyncFolderOperation(root, false);
  1088. }
  1089. cleanSecondFragment();
  1090. }
  1091. /**
  1092. * {@inheritDoc}
  1093. * Updates action bar and second fragment, if in dual pane mode.
  1094. */
  1095. @Override
  1096. public void onBrowsedDownTo(OCFile directory) {
  1097. setFile(directory);
  1098. cleanSecondFragment();
  1099. // Sync Folder
  1100. startSyncFolderOperation(directory, false);
  1101. }
  1102. /**
  1103. * Shows the information of the {@link OCFile} received as a
  1104. * parameter in the second fragment.
  1105. *
  1106. * @param file {@link OCFile} whose details will be shown
  1107. */
  1108. @Override
  1109. public void showDetails(OCFile file) {
  1110. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  1111. setSecondFragment(detailFragment);
  1112. updateFragmentsVisibility(true);
  1113. updateActionBarTitleAndHomeButton(file);
  1114. setFile(file);
  1115. }
  1116. @Override
  1117. protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
  1118. if (mDualPane) {
  1119. // in dual pane mode, keep the focus of title an action bar in the current folder
  1120. super.updateActionBarTitleAndHomeButton(getCurrentDir());
  1121. } else {
  1122. super.updateActionBarTitleAndHomeButton(chosenFile);
  1123. }
  1124. }
  1125. @Override
  1126. protected ServiceConnection newTransferenceServiceConnection() {
  1127. return new ListServiceConnection();
  1128. }
  1129. /**
  1130. * Defines callbacks for service binding, passed to bindService()
  1131. */
  1132. private class ListServiceConnection implements ServiceConnection {
  1133. @Override
  1134. public void onServiceConnected(ComponentName component, IBinder service) {
  1135. if (component.equals(new ComponentName(
  1136. FileDisplayActivity.this, FileDownloader.class))) {
  1137. Log_OC.d(TAG, "Download service connected");
  1138. mDownloaderBinder = (FileDownloaderBinder) service;
  1139. if (mWaitingToPreview != null)
  1140. if (getStorageManager() != null) {
  1141. // update the file
  1142. mWaitingToPreview =
  1143. getStorageManager().getFileById(mWaitingToPreview.getFileId());
  1144. if (!mWaitingToPreview.isDown()) {
  1145. requestForDownload();
  1146. }
  1147. }
  1148. } else if (component.equals(new ComponentName(FileDisplayActivity.this,
  1149. FileUploader.class))) {
  1150. Log_OC.d(TAG, "Upload service connected");
  1151. mUploaderBinder = (FileUploaderBinder) service;
  1152. } else {
  1153. return;
  1154. }
  1155. // a new chance to get the mDownloadBinder through
  1156. // getFileDownloadBinder() - THIS IS A MESS
  1157. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1158. if (listOfFiles != null) {
  1159. listOfFiles.listDirectory();
  1160. // TODO Enable when "On Device" is recovered ?
  1161. // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
  1162. }
  1163. FileFragment secondFragment = getSecondFragment();
  1164. if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
  1165. FileDetailFragment detailFragment = (FileDetailFragment) secondFragment;
  1166. detailFragment.listenForTransferProgress();
  1167. detailFragment.updateFileDetails(false, false);
  1168. }
  1169. }
  1170. @Override
  1171. public void onServiceDisconnected(ComponentName component) {
  1172. if (component.equals(new ComponentName(FileDisplayActivity.this,
  1173. FileDownloader.class))) {
  1174. Log_OC.d(TAG, "Download service disconnected");
  1175. mDownloaderBinder = null;
  1176. } else if (component.equals(new ComponentName(FileDisplayActivity.this,
  1177. FileUploader.class))) {
  1178. Log_OC.d(TAG, "Upload service disconnected");
  1179. mUploaderBinder = null;
  1180. }
  1181. }
  1182. }
  1183. @Override
  1184. public void onSavedCertificate() {
  1185. startSyncFolderOperation(getCurrentDir(), false);
  1186. }
  1187. @Override
  1188. public void onFailedSavingCertificate() {
  1189. ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance(
  1190. R.string.ssl_validator_not_saved, new String[]{}, R.string.common_ok, -1, -1
  1191. );
  1192. dialog.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED);
  1193. }
  1194. @Override
  1195. public void onCancelCertificate() {
  1196. // nothing to do
  1197. }
  1198. /**
  1199. * Updates the view associated to the activity after the finish of some operation over files
  1200. * in the current account.
  1201. *
  1202. * @param operation Removal operation performed.
  1203. * @param result Result of the removal.
  1204. */
  1205. @Override
  1206. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1207. super.onRemoteOperationFinish(operation, result);
  1208. if (operation instanceof RemoveFileOperation) {
  1209. onRemoveFileOperationFinish((RemoveFileOperation) operation, result);
  1210. } else if (operation instanceof RenameFileOperation) {
  1211. onRenameFileOperationFinish((RenameFileOperation) operation, result);
  1212. } else if (operation instanceof SynchronizeFileOperation) {
  1213. onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
  1214. } else if (operation instanceof CreateFolderOperation) {
  1215. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  1216. } else if (operation instanceof MoveFileOperation) {
  1217. onMoveFileOperationFinish((MoveFileOperation) operation, result);
  1218. } else if (operation instanceof CopyFileOperation) {
  1219. onCopyFileOperationFinish((CopyFileOperation) operation, result);
  1220. }
  1221. }
  1222. private void refreshShowDetails() {
  1223. FileFragment details = getSecondFragment();
  1224. if (details != null) {
  1225. OCFile file = details.getFile();
  1226. if (file != null) {
  1227. file = getStorageManager().getFileByPath(file.getRemotePath());
  1228. if (details instanceof PreviewMediaFragment) {
  1229. // Refresh OCFile of the fragment
  1230. ((PreviewMediaFragment) details).updateFile(file);
  1231. } else if (details instanceof PreviewTextFragment) {
  1232. // Refresh OCFile of the fragment
  1233. ((PreviewTextFragment) details).updateFile(file);
  1234. } else {
  1235. showDetails(file);
  1236. }
  1237. }
  1238. invalidateOptionsMenu();
  1239. }
  1240. }
  1241. /**
  1242. * Updates the view associated to the activity after the finish of an operation trying to
  1243. * remove a file.
  1244. *
  1245. * @param operation Removal operation performed.
  1246. * @param result Result of the removal.
  1247. */
  1248. private void onRemoveFileOperationFinish(RemoveFileOperation operation,
  1249. RemoteOperationResult result) {
  1250. Toast msg = Toast.makeText(this,
  1251. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1252. Toast.LENGTH_LONG);
  1253. msg.show();
  1254. if (result.isSuccess()) {
  1255. OCFile removedFile = operation.getFile();
  1256. FileFragment second = getSecondFragment();
  1257. if (second != null && removedFile.equals(second.getFile())) {
  1258. if (second instanceof PreviewMediaFragment) {
  1259. ((PreviewMediaFragment) second).stopPreview(true);
  1260. }
  1261. setFile(getStorageManager().getFileById(removedFile.getParentId()));
  1262. cleanSecondFragment();
  1263. }
  1264. if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
  1265. refreshListOfFilesFragment();
  1266. }
  1267. invalidateOptionsMenu();
  1268. } else {
  1269. if (result.isSslRecoverableException()) {
  1270. mLastSslUntrustedServerResult = result;
  1271. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1272. }
  1273. }
  1274. }
  1275. /**
  1276. * Updates the view associated to the activity after the finish of an operation trying to move a
  1277. * file.
  1278. *
  1279. * @param operation Move operation performed.
  1280. * @param result Result of the move operation.
  1281. */
  1282. private void onMoveFileOperationFinish(MoveFileOperation operation,
  1283. RemoteOperationResult result) {
  1284. if (result.isSuccess()) {
  1285. refreshListOfFilesFragment();
  1286. } else {
  1287. try {
  1288. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1289. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1290. Toast.LENGTH_LONG);
  1291. msg.show();
  1292. } catch (NotFoundException e) {
  1293. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1294. }
  1295. }
  1296. }
  1297. /**
  1298. * Updates the view associated to the activity after the finish of an operation trying to copy a
  1299. * file.
  1300. *
  1301. * @param operation Copy operation performed.
  1302. * @param result Result of the copy operation.
  1303. */
  1304. private void onCopyFileOperationFinish(CopyFileOperation operation, RemoteOperationResult result) {
  1305. if (result.isSuccess()) {
  1306. refreshListOfFilesFragment();
  1307. } else {
  1308. try {
  1309. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1310. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1311. Toast.LENGTH_LONG);
  1312. msg.show();
  1313. } catch (NotFoundException e) {
  1314. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1315. }
  1316. }
  1317. }
  1318. /**
  1319. * Updates the view associated to the activity after the finish of an operation trying to rename
  1320. * a file.
  1321. *
  1322. * @param operation Renaming operation performed.
  1323. * @param result Result of the renaming.
  1324. */
  1325. private void onRenameFileOperationFinish(RenameFileOperation operation,
  1326. RemoteOperationResult result) {
  1327. OCFile renamedFile = operation.getFile();
  1328. if (result.isSuccess()) {
  1329. FileFragment details = getSecondFragment();
  1330. if (details != null) {
  1331. if (details instanceof FileDetailFragment &&
  1332. renamedFile.equals(details.getFile())) {
  1333. ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
  1334. showDetails(renamedFile);
  1335. } else if (details instanceof PreviewMediaFragment &&
  1336. renamedFile.equals(details.getFile())) {
  1337. ((PreviewMediaFragment) details).updateFile(renamedFile);
  1338. if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
  1339. int position = ((PreviewMediaFragment) details).getPosition();
  1340. startMediaPreview(renamedFile, position, true);
  1341. } else {
  1342. getFileOperationsHelper().openFile(renamedFile);
  1343. }
  1344. } else if (details instanceof PreviewTextFragment &&
  1345. renamedFile.equals(details.getFile())) {
  1346. ((PreviewTextFragment) details).updateFile(renamedFile);
  1347. if (PreviewTextFragment.canBePreviewed(renamedFile)) {
  1348. startTextPreview(renamedFile);
  1349. } else {
  1350. getFileOperationsHelper().openFile(renamedFile);
  1351. }
  1352. }
  1353. }
  1354. if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
  1355. refreshListOfFilesFragment();
  1356. }
  1357. } else {
  1358. Toast msg = Toast.makeText(this,
  1359. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1360. Toast.LENGTH_LONG);
  1361. msg.show();
  1362. if (result.isSslRecoverableException()) {
  1363. mLastSslUntrustedServerResult = result;
  1364. showUntrustedCertDialog(mLastSslUntrustedServerResult);
  1365. }
  1366. }
  1367. }
  1368. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation,
  1369. RemoteOperationResult result) {
  1370. if (result.isSuccess()) {
  1371. if (operation.transferWasRequested()) {
  1372. OCFile syncedFile = operation.getLocalFile();
  1373. onTransferStateChanged(syncedFile, true, true);
  1374. invalidateOptionsMenu();
  1375. refreshShowDetails();
  1376. }
  1377. }
  1378. }
  1379. /**
  1380. * Updates the view associated to the activity after the finish of an operation trying create a
  1381. * new folder
  1382. *
  1383. * @param operation Creation operation performed.
  1384. * @param result Result of the creation.
  1385. */
  1386. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  1387. RemoteOperationResult result) {
  1388. if (result.isSuccess()) {
  1389. refreshListOfFilesFragment();
  1390. } else {
  1391. try {
  1392. Toast msg = Toast.makeText(FileDisplayActivity.this,
  1393. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  1394. Toast.LENGTH_LONG);
  1395. msg.show();
  1396. } catch (NotFoundException e) {
  1397. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  1398. }
  1399. }
  1400. }
  1401. /**
  1402. * {@inheritDoc}
  1403. */
  1404. @Override
  1405. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  1406. refreshListOfFilesFragment();
  1407. FileFragment details = getSecondFragment();
  1408. if (details != null && details instanceof FileDetailFragment &&
  1409. file.equals(details.getFile())) {
  1410. if (downloading || uploading) {
  1411. ((FileDetailFragment) details).updateFileDetails(file, getAccount());
  1412. } else {
  1413. if (!file.fileExists()) {
  1414. cleanSecondFragment();
  1415. } else {
  1416. ((FileDetailFragment) details).updateFileDetails(false, true);
  1417. }
  1418. }
  1419. }
  1420. }
  1421. private void requestForDownload() {
  1422. Account account = getAccount();
  1423. //if (!mWaitingToPreview.isDownloading()) {
  1424. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1425. Intent i = new Intent(this, FileDownloader.class);
  1426. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1427. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1428. startService(i);
  1429. }
  1430. }
  1431. private OCFile getCurrentDir() {
  1432. OCFile file = getFile();
  1433. if (file != null) {
  1434. if (file.isFolder()) {
  1435. return file;
  1436. } else if (getStorageManager() != null) {
  1437. String parentPath = file.getRemotePath().substring(0,
  1438. file.getRemotePath().lastIndexOf(file.getFileName()));
  1439. return getStorageManager().getFileByPath(parentPath);
  1440. }
  1441. }
  1442. return null;
  1443. }
  1444. /**
  1445. * Starts an operation to refresh the requested folder.
  1446. * <p/>
  1447. * The operation is run in a new background thread created on the fly.
  1448. * <p/>
  1449. * The refresh updates is a "light sync": properties of regular files in folder are updated (including
  1450. * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
  1451. * synchronized too.
  1452. *
  1453. * @param folder Folder to refresh.
  1454. * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
  1455. * didn't change.
  1456. */
  1457. public void startSyncFolderOperation(final OCFile folder, final boolean ignoreETag) {
  1458. // the execution is slightly delayed to allow the activity get the window focus if it's being started
  1459. // or if the method is called from a dialog that is being dismissed
  1460. getHandler().postDelayed(
  1461. new Runnable() {
  1462. @Override
  1463. public void run() {
  1464. if (hasWindowFocus()) {
  1465. long currentSyncTime = System.currentTimeMillis();
  1466. mSyncInProgress = true;
  1467. // perform folder synchronization
  1468. RemoteOperation synchFolderOp = new RefreshFolderOperation(folder,
  1469. currentSyncTime,
  1470. false,
  1471. getFileOperationsHelper().isSharedSupported(),
  1472. ignoreETag,
  1473. getStorageManager(),
  1474. getAccount(),
  1475. getApplicationContext()
  1476. );
  1477. synchFolderOp.execute(
  1478. getAccount(),
  1479. MainApp.getAppContext(),
  1480. FileDisplayActivity.this,
  1481. null,
  1482. null
  1483. );
  1484. mProgressBar.setIndeterminate(true);
  1485. setBackgroundText();
  1486. } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
  1487. // another window floating over
  1488. }
  1489. },
  1490. DELAY_TO_REQUEST_OPERATIONS_LATER
  1491. );
  1492. }
  1493. /**
  1494. * Show untrusted cert dialog
  1495. */
  1496. public void showUntrustedCertDialog(RemoteOperationResult result) {
  1497. // Show a dialog with the certificate info
  1498. SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError(
  1499. (CertificateCombinedException) result.getException());
  1500. FragmentManager fm = getSupportFragmentManager();
  1501. FragmentTransaction ft = fm.beginTransaction();
  1502. dialog.show(ft, DIALOG_UNTRUSTED_CERT);
  1503. }
  1504. private void requestForDownload(OCFile file) {
  1505. Account account = getAccount();
  1506. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1507. Intent i = new Intent(this, FileDownloader.class);
  1508. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1509. i.putExtra(FileDownloader.EXTRA_FILE, file);
  1510. startService(i);
  1511. }
  1512. }
  1513. private void sendDownloadedFile() {
  1514. getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
  1515. mWaitingToSend = null;
  1516. }
  1517. /**
  1518. * Requests the download of the received {@link OCFile} , updates the UI
  1519. * to monitor the download progress and prepares the activity to send the file
  1520. * when the download finishes.
  1521. *
  1522. * @param file {@link OCFile} to download and preview.
  1523. */
  1524. public void startDownloadForSending(OCFile file) {
  1525. mWaitingToSend = file;
  1526. requestForDownload(mWaitingToSend);
  1527. boolean hasSecondFragment = (getSecondFragment() != null);
  1528. updateFragmentsVisibility(hasSecondFragment);
  1529. }
  1530. /**
  1531. * Opens the image gallery showing the image {@link OCFile} received as parameter.
  1532. *
  1533. * @param file Image {@link OCFile} to show.
  1534. */
  1535. public void startImagePreview(OCFile file) {
  1536. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  1537. showDetailsIntent.putExtra(EXTRA_FILE, file);
  1538. showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
  1539. startActivity(showDetailsIntent);
  1540. }
  1541. /**
  1542. * Stars the preview of an already down media {@link OCFile}.
  1543. *
  1544. * @param file Media {@link OCFile} to preview.
  1545. * @param startPlaybackPosition Media position where the playback will be started,
  1546. * in milliseconds.
  1547. * @param autoplay When 'true', the playback will start without user
  1548. * interactions.
  1549. */
  1550. public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
  1551. Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition,
  1552. autoplay);
  1553. setSecondFragment(mediaFragment);
  1554. updateFragmentsVisibility(true);
  1555. updateActionBarTitleAndHomeButton(file);
  1556. setFile(file);
  1557. }
  1558. /**
  1559. * Stars the preview of a text file {@link OCFile}.
  1560. *
  1561. * @param file Text {@link OCFile} to preview.
  1562. */
  1563. public void startTextPreview(OCFile file) {
  1564. Bundle args = new Bundle();
  1565. args.putParcelable(EXTRA_FILE, file);
  1566. args.putParcelable(EXTRA_ACCOUNT, getAccount());
  1567. Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(),
  1568. PreviewTextFragment.class.getName(), args);
  1569. setSecondFragment(textPreviewFragment);
  1570. updateFragmentsVisibility(true);
  1571. //updateNavigationElementsInActionBar(file);
  1572. setFile(file);
  1573. }
  1574. /**
  1575. * Requests the download of the received {@link OCFile} , updates the UI
  1576. * to monitor the download progress and prepares the activity to preview
  1577. * or open the file when the download finishes.
  1578. *
  1579. * @param file {@link OCFile} to download and preview.
  1580. */
  1581. public void startDownloadForPreview(OCFile file) {
  1582. Fragment detailFragment = FileDetailFragment.newInstance(file, getAccount());
  1583. setSecondFragment(detailFragment);
  1584. mWaitingToPreview = file;
  1585. requestForDownload();
  1586. updateFragmentsVisibility(true);
  1587. updateActionBarTitleAndHomeButton(file);
  1588. setFile(file);
  1589. }
  1590. public void cancelTransference(OCFile file) {
  1591. getFileOperationsHelper().cancelTransference(file);
  1592. if (mWaitingToPreview != null &&
  1593. mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
  1594. mWaitingToPreview = null;
  1595. }
  1596. if (mWaitingToSend != null &&
  1597. mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
  1598. mWaitingToSend = null;
  1599. }
  1600. onTransferStateChanged(file, false, false);
  1601. }
  1602. @Override
  1603. public void onRefresh(boolean ignoreETag) {
  1604. refreshList(ignoreETag);
  1605. }
  1606. @Override
  1607. public void onRefresh() {
  1608. refreshList(true);
  1609. }
  1610. private void refreshList(boolean ignoreETag) {
  1611. OCFileListFragment listOfFiles = getListOfFilesFragment();
  1612. if (listOfFiles != null) {
  1613. OCFile folder = listOfFiles.getCurrentFile();
  1614. if (folder != null) {
  1615. /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
  1616. listDirectory(mFile);*/
  1617. startSyncFolderOperation(folder, ignoreETag);
  1618. }
  1619. }
  1620. }
  1621. private void sortByDate(boolean ascending) {
  1622. getListOfFilesFragment().sortByDate(ascending);
  1623. }
  1624. private void sortBySize(boolean ascending) {
  1625. getListOfFilesFragment().sortBySize(ascending);
  1626. }
  1627. private void sortByName(boolean ascending) {
  1628. getListOfFilesFragment().sortByName(ascending);
  1629. }
  1630. private boolean isGridView() {
  1631. return getListOfFilesFragment().isGridView();
  1632. }
  1633. public void allFilesOption() {
  1634. browseToRoot();
  1635. }
  1636. }