FileDisplayActivity.java 61 KB

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