FileDisplayActivity.java 73 KB

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