FileDisplayActivity.java 68 KB

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