FileDisplayActivity.java 64 KB

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