FileDisplayActivity.java 59 KB

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