FileDisplayActivity.java 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  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 as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package com.owncloud.android.ui.activity;
  20. import java.io.File;
  21. import android.accounts.Account;
  22. import android.app.AlertDialog;
  23. import android.app.ProgressDialog;
  24. import android.app.AlertDialog.Builder;
  25. import android.app.Dialog;
  26. import android.content.BroadcastReceiver;
  27. import android.content.ComponentName;
  28. import android.content.ContentResolver;
  29. import android.content.Context;
  30. import android.content.DialogInterface;
  31. import android.content.DialogInterface.OnClickListener;
  32. import android.content.Intent;
  33. import android.content.IntentFilter;
  34. import android.content.ServiceConnection;
  35. import android.content.SharedPreferences;
  36. import android.content.SharedPreferences.Editor;
  37. import android.content.pm.PackageInfo;
  38. import android.content.pm.PackageManager.NameNotFoundException;
  39. import android.content.res.Resources.NotFoundException;
  40. import android.database.Cursor;
  41. import android.graphics.Bitmap;
  42. import android.graphics.drawable.BitmapDrawable;
  43. import android.net.Uri;
  44. import android.os.Bundle;
  45. import android.os.Handler;
  46. import android.os.IBinder;
  47. import android.preference.PreferenceManager;
  48. import android.provider.MediaStore;
  49. import android.support.v4.app.Fragment;
  50. import android.support.v4.app.FragmentTransaction;
  51. import android.util.Log;
  52. import android.view.View;
  53. import android.view.ViewGroup;
  54. import android.widget.ArrayAdapter;
  55. import android.widget.EditText;
  56. import android.widget.TextView;
  57. import android.widget.Toast;
  58. import com.actionbarsherlock.app.ActionBar;
  59. import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
  60. import com.actionbarsherlock.app.SherlockFragmentActivity;
  61. import com.actionbarsherlock.view.Menu;
  62. import com.actionbarsherlock.view.MenuInflater;
  63. import com.actionbarsherlock.view.MenuItem;
  64. import com.actionbarsherlock.view.Window;
  65. import com.owncloud.android.AccountUtils;
  66. import com.owncloud.android.authenticator.AccountAuthenticator;
  67. import com.owncloud.android.datamodel.DataStorageManager;
  68. import com.owncloud.android.datamodel.FileDataStorageManager;
  69. import com.owncloud.android.datamodel.OCFile;
  70. import com.owncloud.android.files.services.FileDownloader;
  71. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  72. import com.owncloud.android.files.services.FileObserverService;
  73. import com.owncloud.android.files.services.FileUploader;
  74. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  75. import com.owncloud.android.network.OwnCloudClientUtils;
  76. import com.owncloud.android.operations.OnRemoteOperationListener;
  77. import com.owncloud.android.operations.RemoteOperation;
  78. import com.owncloud.android.operations.RemoteOperationResult;
  79. import com.owncloud.android.operations.RemoveFileOperation;
  80. import com.owncloud.android.operations.RenameFileOperation;
  81. import com.owncloud.android.operations.SynchronizeFileOperation;
  82. import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
  83. import com.owncloud.android.syncadapter.FileSyncService;
  84. import com.owncloud.android.ui.dialog.ChangelogDialog;
  85. import com.owncloud.android.ui.dialog.EditNameDialog;
  86. import com.owncloud.android.ui.dialog.SslValidatorDialog;
  87. import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
  88. import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
  89. import com.owncloud.android.ui.fragment.FileDetailFragment;
  90. import com.owncloud.android.ui.fragment.FileFragment;
  91. import com.owncloud.android.ui.fragment.OCFileListFragment;
  92. import com.owncloud.android.ui.preview.PreviewImageActivity;
  93. import com.owncloud.android.ui.preview.PreviewImageFragment;
  94. import com.owncloud.android.ui.preview.PreviewMediaFragment;
  95. import com.owncloud.android.R;
  96. import eu.alefzero.webdav.WebdavClient;
  97. /**
  98. * Displays, what files the user has available in his ownCloud.
  99. *
  100. * @author Bartek Przybylski
  101. * @author David A. Velasco
  102. */
  103. public class FileDisplayActivity extends SherlockFragmentActivity implements
  104. OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener, OnRemoteOperationListener, EditNameDialogListener {
  105. private ArrayAdapter<String> mDirectories;
  106. private OCFile mCurrentDir = null;
  107. private OCFile mCurrentFile = null;
  108. private DataStorageManager mStorageManager;
  109. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  110. private UploadFinishReceiver mUploadFinishReceiver;
  111. private DownloadFinishReceiver mDownloadFinishReceiver;
  112. private FileDownloaderBinder mDownloaderBinder = null;
  113. private FileUploaderBinder mUploaderBinder = null;
  114. private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
  115. private RemoteOperationResult mLastSslUntrustedServerResult = null;
  116. private OCFileListFragment mFileList;
  117. private boolean mDualPane;
  118. private static final int DIALOG_SETUP_ACCOUNT = 0;
  119. private static final int DIALOG_CREATE_DIR = 1;
  120. private static final int DIALOG_ABOUT_APP = 2;
  121. public static final int DIALOG_SHORT_WAIT = 3;
  122. private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 4;
  123. private static final int DIALOG_SSL_VALIDATOR = 5;
  124. private static final int DIALOG_CERT_NOT_SAVED = 6;
  125. private static final String DIALOG_CHANGELOG_TAG = "DIALOG_CHANGELOG";
  126. private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
  127. private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
  128. private static final String TAG = "FileDisplayActivity";
  129. private static int[] mMenuIdentifiersToPatch = {R.id.action_about_app};
  130. private OCFile mWaitingToPreview;
  131. private Handler mHandler;
  132. @Override
  133. public void onCreate(Bundle savedInstanceState) {
  134. Log.d(getClass().toString(), "onCreate() start");
  135. super.onCreate(savedInstanceState);
  136. /// Load of parameters from received intent
  137. Account account = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT);
  138. if (account != null && AccountUtils.setCurrentOwnCloudAccount(this, account.name)) {
  139. mCurrentDir = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
  140. }
  141. /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
  142. if(savedInstanceState != null) {
  143. // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
  144. mCurrentDir = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
  145. mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDetailActivity.KEY_WAITING_TO_PREVIEW);
  146. } else {
  147. mWaitingToPreview = null;
  148. }
  149. if (!AccountUtils.accountsAreSetup(this)) {
  150. /// no account available: FORCE ACCOUNT CREATION
  151. mStorageManager = null;
  152. createFirstAccount();
  153. } else { /// at least an account is available
  154. initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
  155. }
  156. mUploadConnection = new ListServiceConnection();
  157. mDownloadConnection = new ListServiceConnection();
  158. bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
  159. bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
  160. // PIN CODE request ; best location is to decide, let's try this first
  161. if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
  162. requestPinCode();
  163. }
  164. // file observer
  165. Intent observer_intent = new Intent(this, FileObserverService.class);
  166. observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
  167. startService(observer_intent);
  168. /// USER INTERFACE
  169. requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
  170. // Drop-down navigation
  171. mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
  172. OCFile currFile = mCurrentDir;
  173. while(mStorageManager != null && currFile != null && currFile.getFileName() != OCFile.PATH_SEPARATOR) {
  174. mDirectories.add(currFile.getFileName());
  175. currFile = mStorageManager.getFileById(currFile.getParentId());
  176. }
  177. mDirectories.add(OCFile.PATH_SEPARATOR);
  178. // Inflate and set the layout view
  179. setContentView(R.layout.files);
  180. mFileList = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
  181. mDualPane = (findViewById(R.id.file_details_container) != null);
  182. if (mDualPane) {
  183. initFileDetailsInDualPane();
  184. } else {
  185. // quick patchES to fix problem in turn from landscape to portrait, when a file is selected in the right pane
  186. // TODO serious refactorization in activities and fragments providing file browsing and handling
  187. if (mCurrentFile != null) {
  188. onFileClick(mCurrentFile);
  189. mCurrentFile = null;
  190. }
  191. Fragment rightPanel = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
  192. if (rightPanel != null) {
  193. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  194. transaction.remove(rightPanel);
  195. transaction.commit();
  196. }
  197. }
  198. // Action bar setup
  199. ActionBar actionBar = getSupportActionBar();
  200. actionBar.setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
  201. actionBar.setDisplayHomeAsUpEnabled(mCurrentDir != null && mCurrentDir.getParentId() != 0);
  202. actionBar.setDisplayShowTitleEnabled(false);
  203. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
  204. actionBar.setListNavigationCallbacks(mDirectories, this);
  205. setSupportProgressBarIndeterminateVisibility(false); // always AFTER setContentView(...) ; to workaround bug in its implementation
  206. // show changelog, if needed
  207. //showChangeLog();
  208. Log.d(getClass().toString(), "onCreate() end");
  209. }
  210. /**
  211. * Shows a dialog with the change log of the current version after each app update
  212. *
  213. * TODO make it permanent; by now, only to advice the workaround app for 4.1.x
  214. */
  215. private void showChangeLog() {
  216. if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.JELLY_BEAN) {
  217. final String KEY_VERSION = "version";
  218. SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  219. int currentVersionNumber = 0;
  220. int savedVersionNumber = sharedPref.getInt(KEY_VERSION, 0);
  221. try {
  222. PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
  223. currentVersionNumber = pi.versionCode;
  224. } catch (Exception e) {}
  225. if (currentVersionNumber > savedVersionNumber) {
  226. ChangelogDialog.newInstance(true).show(getSupportFragmentManager(), DIALOG_CHANGELOG_TAG);
  227. Editor editor = sharedPref.edit();
  228. editor.putInt(KEY_VERSION, currentVersionNumber);
  229. editor.commit();
  230. }
  231. }
  232. }
  233. /**
  234. * Launches the account creation activity. To use when no ownCloud account is available
  235. */
  236. private void createFirstAccount() {
  237. Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
  238. intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
  239. startActivity(intent); // the new activity won't be created until this.onStart() and this.onResume() are finished;
  240. }
  241. /**
  242. * Load of state dependent of the existence of an ownCloud account
  243. */
  244. private void initDataFromCurrentAccount() {
  245. /// Storage manager initialization - access to local database
  246. mStorageManager = new FileDataStorageManager(
  247. AccountUtils.getCurrentOwnCloudAccount(this),
  248. getContentResolver());
  249. /// Check if mCurrentDir is a directory
  250. if(mCurrentDir != null && !mCurrentDir.isDirectory()) {
  251. mCurrentFile = mCurrentDir;
  252. mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
  253. }
  254. /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
  255. if (mCurrentDir != null) {
  256. mCurrentDir = mStorageManager.getFileByPath(mCurrentDir.getRemotePath()); // mCurrentDir == null if it is not in the current account
  257. }
  258. if (mCurrentFile != null) {
  259. if (mCurrentFile.fileExists()) {
  260. mCurrentFile = mStorageManager.getFileByPath(mCurrentFile.getRemotePath()); // mCurrentFile == null if it is not in the current account
  261. } // else : keep mCurrentFile with the received value; this is currently the case of an upload in progress, when the user presses the status notification in a landscape tablet
  262. }
  263. /// Default to root if mCurrentDir was not found
  264. if (mCurrentDir == null) {
  265. mCurrentDir = mStorageManager.getFileByPath("/"); // will be NULL if the database was never synchronized
  266. }
  267. }
  268. private void initFileDetailsInDualPane() {
  269. if (mDualPane && getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG) == null) {
  270. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  271. if (mCurrentFile != null) {
  272. if (PreviewMediaFragment.canBePreviewed(mCurrentFile)) {
  273. if (mCurrentFile.isDown()) {
  274. transaction.replace(R.id.file_details_container, new PreviewMediaFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
  275. } else {
  276. transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
  277. mWaitingToPreview = mCurrentFile;
  278. }
  279. } else {
  280. transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
  281. }
  282. mCurrentFile = null;
  283. } else {
  284. transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
  285. }
  286. transaction.commit();
  287. }
  288. }
  289. @Override
  290. public void onDestroy() {
  291. super.onDestroy();
  292. if (mDownloadConnection != null)
  293. unbindService(mDownloadConnection);
  294. if (mUploadConnection != null)
  295. unbindService(mUploadConnection);
  296. }
  297. @Override
  298. public boolean onCreateOptionsMenu(Menu menu) {
  299. MenuInflater inflater = getSherlock().getMenuInflater();
  300. inflater.inflate(R.menu.main_menu, menu);
  301. patchHiddenAccents(menu);
  302. return true;
  303. }
  304. /**
  305. * Workaround for this: <a href="http://code.google.com/p/android/issues/detail?id=3974">http://code.google.com/p/android/issues/detail?id=3974</a>
  306. *
  307. * @param menu Menu to patch
  308. */
  309. private void patchHiddenAccents(Menu menu) {
  310. for (int i = 0; i < mMenuIdentifiersToPatch.length ; i++) {
  311. MenuItem aboutItem = menu.findItem(mMenuIdentifiersToPatch[i]);
  312. if (aboutItem != null && aboutItem.getIcon() instanceof BitmapDrawable) {
  313. // Clip off the bottom three (density independent) pixels of transparent padding
  314. Bitmap original = ((BitmapDrawable) aboutItem.getIcon()).getBitmap();
  315. float scale = getResources().getDisplayMetrics().density;
  316. int clippedHeight = (int) (original.getHeight() - (3 * scale));
  317. Bitmap scaled = Bitmap.createBitmap(original, 0, 0, original.getWidth(), clippedHeight);
  318. aboutItem.setIcon(new BitmapDrawable(getResources(), scaled));
  319. }
  320. }
  321. }
  322. @Override
  323. public boolean onOptionsItemSelected(MenuItem item) {
  324. boolean retval = true;
  325. switch (item.getItemId()) {
  326. case R.id.action_create_dir: {
  327. EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.uploader_info_dirname), "", this);
  328. dialog.show(getSupportFragmentManager(), "createdirdialog");
  329. break;
  330. }
  331. case R.id.action_sync_account: {
  332. startSynchronization();
  333. break;
  334. }
  335. case R.id.action_upload: {
  336. showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
  337. break;
  338. }
  339. case R.id.action_settings: {
  340. Intent settingsIntent = new Intent(this, Preferences.class);
  341. startActivity(settingsIntent);
  342. break;
  343. }
  344. case R.id.action_about_app: {
  345. showDialog(DIALOG_ABOUT_APP);
  346. break;
  347. }
  348. case android.R.id.home: {
  349. if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
  350. onBackPressed();
  351. }
  352. break;
  353. }
  354. default:
  355. retval = super.onOptionsItemSelected(item);
  356. }
  357. return retval;
  358. }
  359. private void startSynchronization() {
  360. ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE); // cancel the current synchronizations of any ownCloud account
  361. Bundle bundle = new Bundle();
  362. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  363. ContentResolver.requestSync(
  364. AccountUtils.getCurrentOwnCloudAccount(this),
  365. AccountAuthenticator.AUTH_TOKEN_TYPE, bundle);
  366. }
  367. @Override
  368. public boolean onNavigationItemSelected(int itemPosition, long itemId) {
  369. int i = itemPosition;
  370. while (i-- != 0) {
  371. onBackPressed();
  372. }
  373. // the next operation triggers a new call to this method, but it's necessary to
  374. // ensure that the name exposed in the action bar is the current directory when the
  375. // user selected it in the navigation list
  376. if (itemPosition != 0)
  377. getSupportActionBar().setSelectedNavigationItem(0);
  378. return true;
  379. }
  380. /**
  381. * Called, when the user selected something for uploading
  382. */
  383. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  384. if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  385. requestSimpleUpload(data, resultCode);
  386. } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
  387. requestMultipleUpload(data, resultCode);
  388. }
  389. }
  390. private void requestMultipleUpload(Intent data, int resultCode) {
  391. String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
  392. if (filePaths != null) {
  393. String[] remotePaths = new String[filePaths.length];
  394. String remotePathBase = "";
  395. for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
  396. remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
  397. }
  398. if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
  399. remotePathBase += OCFile.PATH_SEPARATOR;
  400. for (int j = 0; j< remotePaths.length; j++) {
  401. remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
  402. }
  403. Intent i = new Intent(this, FileUploader.class);
  404. i.putExtra(FileUploader.KEY_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
  405. i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
  406. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
  407. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
  408. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  409. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  410. startService(i);
  411. } else {
  412. Log.d("FileDisplay", "User clicked on 'Update' with no selection");
  413. Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
  414. t.show();
  415. return;
  416. }
  417. }
  418. private void requestSimpleUpload(Intent data, int resultCode) {
  419. String filepath = null;
  420. try {
  421. Uri selectedImageUri = data.getData();
  422. String filemanagerstring = selectedImageUri.getPath();
  423. String selectedImagePath = getPath(selectedImageUri);
  424. if (selectedImagePath != null)
  425. filepath = selectedImagePath;
  426. else
  427. filepath = filemanagerstring;
  428. } catch (Exception e) {
  429. Log.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
  430. e.printStackTrace();
  431. } finally {
  432. if (filepath == null) {
  433. Log.e("FileDisplay", "Couldnt resolve path to file");
  434. Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
  435. t.show();
  436. return;
  437. }
  438. }
  439. Intent i = new Intent(this, FileUploader.class);
  440. i.putExtra(FileUploader.KEY_ACCOUNT,
  441. AccountUtils.getCurrentOwnCloudAccount(this));
  442. String remotepath = new String();
  443. for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
  444. remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
  445. }
  446. if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
  447. remotepath += OCFile.PATH_SEPARATOR;
  448. remotepath += new File(filepath).getName();
  449. i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
  450. i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
  451. i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
  452. if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
  453. i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
  454. startService(i);
  455. }
  456. @Override
  457. public void onBackPressed() {
  458. if (mDirectories.getCount() <= 1) {
  459. finish();
  460. return;
  461. }
  462. popDirname();
  463. mFileList.onNavigateUp();
  464. mCurrentDir = mFileList.getCurrentFile();
  465. if (mDualPane) {
  466. // Resets the FileDetailsFragment on Tablets so that it always displays
  467. Fragment fileFragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
  468. if (fileFragment != null && (fileFragment instanceof PreviewMediaFragment || !((FileDetailFragment) fileFragment).isEmpty())) {
  469. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  470. transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
  471. transaction.commit();
  472. }
  473. }
  474. if(mCurrentDir.getParentId() == 0){
  475. ActionBar actionBar = getSupportActionBar();
  476. actionBar.setDisplayHomeAsUpEnabled(false);
  477. }
  478. }
  479. @Override
  480. protected void onSaveInstanceState(Bundle outState) {
  481. // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
  482. Log.d(getClass().toString(), "onSaveInstanceState() start");
  483. super.onSaveInstanceState(outState);
  484. outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);
  485. if (mDualPane) {
  486. FileFragment fragment = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
  487. if (fragment != null) {
  488. OCFile file = fragment.getFile();
  489. if (file != null) {
  490. outState.putParcelable(FileDetailFragment.EXTRA_FILE, file);
  491. }
  492. }
  493. }
  494. outState.putParcelable(FileDetailActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
  495. Log.d(getClass().toString(), "onSaveInstanceState() end");
  496. }
  497. @Override
  498. public void onResume() {
  499. Log.d(getClass().toString(), "onResume() start");
  500. super.onResume();
  501. if (AccountUtils.accountsAreSetup(this)) {
  502. if (mStorageManager == null) {
  503. // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
  504. initDataFromCurrentAccount();
  505. if (mDualPane) {
  506. initFileDetailsInDualPane();
  507. }
  508. }
  509. // Listen for sync messages
  510. IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
  511. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  512. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  513. // Listen for upload messages
  514. IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
  515. mUploadFinishReceiver = new UploadFinishReceiver();
  516. registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
  517. // Listen for download messages
  518. IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
  519. downloadIntentFilter.addAction(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
  520. mDownloadFinishReceiver = new DownloadFinishReceiver();
  521. registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
  522. // List current directory
  523. mFileList.listDirectory(mCurrentDir); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
  524. } else {
  525. mStorageManager = null; // an invalid object will be there if all the ownCloud accounts are removed
  526. showDialog(DIALOG_SETUP_ACCOUNT);
  527. }
  528. Log.d(getClass().toString(), "onResume() end");
  529. }
  530. @Override
  531. public void onPause() {
  532. Log.d(getClass().toString(), "onPause() start");
  533. super.onPause();
  534. if (mSyncBroadcastReceiver != null) {
  535. unregisterReceiver(mSyncBroadcastReceiver);
  536. mSyncBroadcastReceiver = null;
  537. }
  538. if (mUploadFinishReceiver != null) {
  539. unregisterReceiver(mUploadFinishReceiver);
  540. mUploadFinishReceiver = null;
  541. }
  542. if (mDownloadFinishReceiver != null) {
  543. unregisterReceiver(mDownloadFinishReceiver);
  544. mDownloadFinishReceiver = null;
  545. }
  546. if (!AccountUtils.accountsAreSetup(this)) {
  547. dismissDialog(DIALOG_SETUP_ACCOUNT);
  548. }
  549. Log.d(getClass().toString(), "onPause() end");
  550. }
  551. @Override
  552. protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
  553. if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {
  554. ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
  555. }
  556. }
  557. @Override
  558. protected Dialog onCreateDialog(int id) {
  559. Dialog dialog = null;
  560. AlertDialog.Builder builder;
  561. switch (id) {
  562. case DIALOG_SETUP_ACCOUNT: {
  563. builder = new AlertDialog.Builder(this);
  564. builder.setTitle(R.string.main_tit_accsetup);
  565. builder.setMessage(R.string.main_wrn_accsetup);
  566. builder.setCancelable(false);
  567. builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
  568. public void onClick(DialogInterface dialog, int which) {
  569. createFirstAccount();
  570. dialog.dismiss();
  571. }
  572. });
  573. String message = String.format(getString(R.string.common_exit), getString(R.string.app_name));
  574. builder.setNegativeButton(message, new OnClickListener() {
  575. public void onClick(DialogInterface dialog, int which) {
  576. dialog.dismiss();
  577. finish();
  578. }
  579. });
  580. //builder.setNegativeButton(android.R.string.cancel, this);
  581. dialog = builder.create();
  582. break;
  583. }
  584. case DIALOG_ABOUT_APP: {
  585. builder = new AlertDialog.Builder(this);
  586. builder.setTitle(getString(R.string.about_title));
  587. PackageInfo pkg;
  588. try {
  589. pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
  590. builder.setMessage(String.format(getString(R.string.about_message), getString(R.string.app_name), pkg.versionName));
  591. builder.setIcon(android.R.drawable.ic_menu_info_details);
  592. dialog = builder.create();
  593. } catch (NameNotFoundException e) {
  594. builder = null;
  595. dialog = null;
  596. Log.e(TAG, "Error while showing about dialog", e);
  597. }
  598. break;
  599. }
  600. case DIALOG_CREATE_DIR: {
  601. builder = new Builder(this);
  602. final EditText dirNameInput = new EditText(getBaseContext());
  603. builder.setView(dirNameInput);
  604. builder.setTitle(R.string.uploader_info_dirname);
  605. int typed_color = getResources().getColor(R.color.setup_text_typed);
  606. dirNameInput.setTextColor(typed_color);
  607. builder.setPositiveButton(android.R.string.ok,
  608. new OnClickListener() {
  609. public void onClick(DialogInterface dialog, int which) {
  610. String directoryName = dirNameInput.getText().toString();
  611. if (directoryName.trim().length() == 0) {
  612. dialog.cancel();
  613. return;
  614. }
  615. // Figure out the path where the dir needs to be created
  616. String path;
  617. if (mCurrentDir == null) {
  618. // this is just a patch; we should ensure that mCurrentDir never is null
  619. if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
  620. OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
  621. mStorageManager.saveFile(file);
  622. }
  623. mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
  624. }
  625. path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
  626. // Create directory
  627. path += directoryName + OCFile.PATH_SEPARATOR;
  628. Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
  629. thread.start();
  630. dialog.dismiss();
  631. showDialog(DIALOG_SHORT_WAIT);
  632. }
  633. });
  634. builder.setNegativeButton(R.string.common_cancel,
  635. new OnClickListener() {
  636. public void onClick(DialogInterface dialog, int which) {
  637. dialog.cancel();
  638. }
  639. });
  640. dialog = builder.create();
  641. break;
  642. }
  643. case DIALOG_SHORT_WAIT: {
  644. ProgressDialog working_dialog = new ProgressDialog(this);
  645. working_dialog.setMessage(getResources().getString(
  646. R.string.wait_a_moment));
  647. working_dialog.setIndeterminate(true);
  648. working_dialog.setCancelable(false);
  649. dialog = working_dialog;
  650. break;
  651. }
  652. case DIALOG_CHOOSE_UPLOAD_SOURCE: {
  653. String[] items = null;
  654. String[] allTheItems = { getString(R.string.actionbar_upload_files),
  655. getString(R.string.actionbar_upload_from_apps),
  656. getString(R.string.actionbar_failed_instant_upload) };
  657. String[] commonItems = { getString(R.string.actionbar_upload_files),
  658. getString(R.string.actionbar_upload_from_apps) };
  659. if (InstantUploadActivity.IS_ENABLED)
  660. items = allTheItems;
  661. else
  662. items = commonItems;
  663. builder = new AlertDialog.Builder(this);
  664. builder.setTitle(R.string.actionbar_upload);
  665. builder.setItems(items, new DialogInterface.OnClickListener() {
  666. public void onClick(DialogInterface dialog, int item) {
  667. if (item == 0) {
  668. // if (!mDualPane) {
  669. Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
  670. action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT,
  671. AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this));
  672. startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
  673. // } else {
  674. // TODO create and handle new fragment
  675. // LocalFileListFragment
  676. // }
  677. } else if (item == 1) {
  678. Intent action = new Intent(Intent.ACTION_GET_CONTENT);
  679. action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
  680. startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
  681. ACTION_SELECT_CONTENT_FROM_APPS);
  682. } else if (item == 2 && InstantUploadActivity.IS_ENABLED) {
  683. Account account = AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this);
  684. Intent action = new Intent(FileDisplayActivity.this, InstantUploadActivity.class);
  685. action.putExtra(FileUploader.KEY_ACCOUNT, account);
  686. startActivity(action);
  687. }
  688. }
  689. });
  690. dialog = builder.create();
  691. break;
  692. }
  693. case DIALOG_SSL_VALIDATOR: {
  694. dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
  695. break;
  696. }
  697. case DIALOG_CERT_NOT_SAVED: {
  698. builder = new AlertDialog.Builder(this);
  699. builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
  700. builder.setCancelable(false);
  701. builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
  702. @Override
  703. public void onClick(DialogInterface dialog, int which) {
  704. dialog.dismiss();
  705. };
  706. });
  707. dialog = builder.create();
  708. break;
  709. }
  710. default:
  711. dialog = null;
  712. }
  713. return dialog;
  714. }
  715. /**
  716. * Translates a content URI of an image to a physical path
  717. * on the disk
  718. * @param uri The URI to resolve
  719. * @return The path to the image or null if it could not be found
  720. */
  721. public String getPath(Uri uri) {
  722. String[] projection = { MediaStore.Images.Media.DATA };
  723. Cursor cursor = managedQuery(uri, projection, null, null, null);
  724. if (cursor != null) {
  725. int column_index = cursor
  726. .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  727. cursor.moveToFirst();
  728. return cursor.getString(column_index);
  729. }
  730. return null;
  731. }
  732. /**
  733. * Pushes a directory to the drop down list
  734. * @param directory to push
  735. * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
  736. */
  737. public void pushDirname(OCFile directory) {
  738. if(!directory.isDirectory()){
  739. throw new IllegalArgumentException("Only directories may be pushed!");
  740. }
  741. mDirectories.insert(directory.getFileName(), 0);
  742. mCurrentDir = directory;
  743. }
  744. /**
  745. * Pops a directory name from the drop down list
  746. * @return True, unless the stack is empty
  747. */
  748. public boolean popDirname() {
  749. mDirectories.remove(mDirectories.getItem(0));
  750. return !mDirectories.isEmpty();
  751. }
  752. private class DirectoryCreator implements Runnable {
  753. private String mTargetPath;
  754. private Account mAccount;
  755. private Handler mHandler;
  756. public DirectoryCreator(String targetPath, Account account, Handler handler) {
  757. mTargetPath = targetPath;
  758. mAccount = account;
  759. mHandler = handler;
  760. }
  761. @Override
  762. public void run() {
  763. WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
  764. boolean created = wdc.createDirectory(mTargetPath);
  765. if (created) {
  766. mHandler.post(new Runnable() {
  767. @Override
  768. public void run() {
  769. dismissDialog(DIALOG_SHORT_WAIT);
  770. // Save new directory in local database
  771. OCFile newDir = new OCFile(mTargetPath);
  772. newDir.setMimetype("DIR");
  773. newDir.setParentId(mCurrentDir.getFileId());
  774. mStorageManager.saveFile(newDir);
  775. // Display the new folder right away
  776. mFileList.listDirectory();
  777. }
  778. });
  779. } else {
  780. mHandler.post(new Runnable() {
  781. @Override
  782. public void run() {
  783. dismissDialog(DIALOG_SHORT_WAIT);
  784. try {
  785. Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
  786. msg.show();
  787. } catch (NotFoundException e) {
  788. Log.e(TAG, "Error while trying to show fail message " , e);
  789. }
  790. }
  791. });
  792. }
  793. }
  794. }
  795. // Custom array adapter to override text colors
  796. private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
  797. public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
  798. super(ctx, view);
  799. }
  800. public View getView(int position, View convertView, ViewGroup parent) {
  801. View v = super.getView(position, convertView, parent);
  802. ((TextView) v).setTextColor(getResources().getColorStateList(
  803. android.R.color.white));
  804. return v;
  805. }
  806. public View getDropDownView(int position, View convertView,
  807. ViewGroup parent) {
  808. View v = super.getDropDownView(position, convertView, parent);
  809. ((TextView) v).setTextColor(getResources().getColorStateList(
  810. android.R.color.white));
  811. return v;
  812. }
  813. }
  814. private class SyncBroadcastReceiver extends BroadcastReceiver {
  815. /**
  816. * {@link BroadcastReceiver} to enable syncing feedback in UI
  817. */
  818. @Override
  819. public void onReceive(Context context, Intent intent) {
  820. boolean inProgress = intent.getBooleanExtra(
  821. FileSyncService.IN_PROGRESS, false);
  822. String accountName = intent
  823. .getStringExtra(FileSyncService.ACCOUNT_NAME);
  824. Log.d("FileDisplay", "sync of account " + accountName
  825. + " is in_progress: " + inProgress);
  826. if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
  827. String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
  828. boolean fillBlankRoot = false;
  829. if (mCurrentDir == null) {
  830. mCurrentDir = mStorageManager.getFileByPath("/");
  831. fillBlankRoot = (mCurrentDir != null);
  832. }
  833. if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
  834. || fillBlankRoot ) {
  835. if (!fillBlankRoot)
  836. mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
  837. OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager()
  838. .findFragmentById(R.id.fileList);
  839. if (fileListFragment != null) {
  840. fileListFragment.listDirectory(mCurrentDir);
  841. }
  842. }
  843. setSupportProgressBarIndeterminateVisibility(inProgress);
  844. removeStickyBroadcast(intent);
  845. }
  846. RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT);
  847. if (synchResult != null) {
  848. if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
  849. mLastSslUntrustedServerResult = synchResult;
  850. showDialog(DIALOG_SSL_VALIDATOR);
  851. }
  852. }
  853. }
  854. }
  855. private class UploadFinishReceiver extends BroadcastReceiver {
  856. /**
  857. * Once the file upload has finished -> update view
  858. * @author David A. Velasco
  859. * {@link BroadcastReceiver} to enable upload feedback in UI
  860. */
  861. @Override
  862. public void onReceive(Context context, Intent intent) {
  863. String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  864. String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
  865. boolean sameAccount = accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name);
  866. boolean isDescendant = (mCurrentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
  867. if (sameAccount && isDescendant) {
  868. OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
  869. if (fileListFragment != null) {
  870. fileListFragment.listDirectory();
  871. }
  872. }
  873. }
  874. }
  875. /**
  876. * Class waiting for broadcast events from the {@link FielDownloader} service.
  877. *
  878. * Updates the UI when a download is started or finished, provided that it is relevant for the
  879. * current folder.
  880. */
  881. private class DownloadFinishReceiver extends BroadcastReceiver {
  882. @Override
  883. public void onReceive(Context context, Intent intent) {
  884. boolean sameAccount = isSameAccount(context, intent);
  885. String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  886. boolean isDescendant = isDescendant(downloadedRemotePath);
  887. if (sameAccount && isDescendant) {
  888. updateLeftPanel();
  889. if (mDualPane) {
  890. updateRightPanel(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
  891. }
  892. }
  893. removeStickyBroadcast(intent);
  894. }
  895. private boolean isDescendant(String downloadedRemotePath) {
  896. return (mCurrentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
  897. }
  898. private boolean isSameAccount(Context context, Intent intent) {
  899. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  900. return (accountName != null && accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name));
  901. }
  902. }
  903. protected void updateLeftPanel() {
  904. OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
  905. if (fileListFragment != null) {
  906. fileListFragment.listDirectory();
  907. }
  908. }
  909. protected void updateRightPanel(String downloadEvent, String downloadedRemotePath, boolean success) {
  910. Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
  911. boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
  912. if (fragment != null && fragment instanceof FileDetailFragment) {
  913. FileDetailFragment detailsFragment = (FileDetailFragment) fragment;
  914. OCFile fileInFragment = detailsFragment.getFile();
  915. if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
  916. // the user browsed to other file ; forget the automatic preview
  917. mWaitingToPreview = null;
  918. } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_ADDED_MESSAGE)) {
  919. // grant that the right panel updates the progress bar
  920. detailsFragment.listenForTransferProgress();
  921. detailsFragment.updateFileDetails(true, false);
  922. } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
  923. // update the right panel
  924. if (success && waitedPreview) {
  925. mWaitingToPreview = mStorageManager.getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
  926. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  927. transaction.replace(R.id.file_details_container, new PreviewMediaFragment(mWaitingToPreview, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
  928. transaction.commit();
  929. mWaitingToPreview = null;
  930. } else {
  931. detailsFragment.updateFileDetails(false, (success));
  932. }
  933. }
  934. }
  935. }
  936. /**
  937. * {@inheritDoc}
  938. */
  939. @Override
  940. public DataStorageManager getStorageManager() {
  941. return mStorageManager;
  942. }
  943. /**
  944. * {@inheritDoc}
  945. */
  946. @Override
  947. public void onDirectoryClick(OCFile directory) {
  948. pushDirname(directory);
  949. ActionBar actionBar = getSupportActionBar();
  950. actionBar.setDisplayHomeAsUpEnabled(true);
  951. if (mDualPane) {
  952. // Resets the FileDetailsFragment on Tablets so that it always displays
  953. Fragment fileFragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
  954. if (fileFragment != null && (fileFragment instanceof PreviewMediaFragment || !((FileDetailFragment) fileFragment).isEmpty())) {
  955. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  956. transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
  957. transaction.commit();
  958. }
  959. }
  960. }
  961. /**
  962. * {@inheritDoc}
  963. */
  964. @Override
  965. public void onFileClick(OCFile file) {
  966. if (file != null && PreviewImageFragment.canBePreviewed(file)) {
  967. // preview image - it handles the download, if needed
  968. startPreviewImage(file);
  969. } else if (file != null && PreviewMediaFragment.canBePreviewed(file)) {
  970. if (file.isDown()) {
  971. // general preview
  972. startMediaPreview(file);
  973. } else {
  974. // automatic download, preview on finish
  975. startDownloadForPreview(file);
  976. }
  977. } else {
  978. // details view
  979. startDetails(file);
  980. }
  981. }
  982. private void startPreviewImage(OCFile file) {
  983. Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  984. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
  985. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
  986. startActivity(showDetailsIntent);
  987. }
  988. private void startMediaPreview(OCFile file) {
  989. if (mDualPane) {
  990. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  991. transaction.replace(R.id.file_details_container, new PreviewMediaFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
  992. transaction.commit();
  993. } else {
  994. Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
  995. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
  996. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
  997. startActivity(showDetailsIntent);
  998. }
  999. }
  1000. private void startDownloadForPreview(OCFile file) {
  1001. if (mDualPane) {
  1002. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  1003. transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
  1004. transaction.commit();
  1005. mWaitingToPreview = file;
  1006. requestForDownload();
  1007. } else {
  1008. Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
  1009. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
  1010. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
  1011. startActivity(showDetailsIntent);
  1012. }
  1013. }
  1014. private void startDetails(OCFile file) {
  1015. if (mDualPane && !file.isImage()) {
  1016. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  1017. transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
  1018. transaction.commit();
  1019. } else {
  1020. Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
  1021. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
  1022. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
  1023. startActivity(showDetailsIntent);
  1024. }
  1025. }
  1026. /**
  1027. * {@inheritDoc}
  1028. */
  1029. @Override
  1030. public OCFile getInitialDirectory() {
  1031. return mCurrentDir;
  1032. }
  1033. /**
  1034. * {@inheritDoc}
  1035. */
  1036. @Override
  1037. public void onFileStateChanged() {
  1038. OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
  1039. if (fileListFragment != null) {
  1040. fileListFragment.listDirectory();
  1041. }
  1042. }
  1043. /**
  1044. * {@inheritDoc}
  1045. */
  1046. @Override
  1047. public FileDownloaderBinder getFileDownloaderBinder() {
  1048. return mDownloaderBinder;
  1049. }
  1050. /**
  1051. * {@inheritDoc}
  1052. */
  1053. @Override
  1054. public FileUploaderBinder getFileUploaderBinder() {
  1055. return mUploaderBinder;
  1056. }
  1057. /** Defines callbacks for service binding, passed to bindService() */
  1058. private class ListServiceConnection implements ServiceConnection {
  1059. @Override
  1060. public void onServiceConnected(ComponentName component, IBinder service) {
  1061. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1062. Log.d(TAG, "Download service connected");
  1063. mDownloaderBinder = (FileDownloaderBinder) service;
  1064. if (mWaitingToPreview != null) {
  1065. requestForDownload();
  1066. }
  1067. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1068. Log.d(TAG, "Upload service connected");
  1069. mUploaderBinder = (FileUploaderBinder) service;
  1070. } else {
  1071. return;
  1072. }
  1073. // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
  1074. if (mFileList != null)
  1075. mFileList.listDirectory();
  1076. if (mDualPane) {
  1077. Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
  1078. if (fragment != null && fragment instanceof FileDetailFragment) {
  1079. FileDetailFragment detailFragment = (FileDetailFragment)fragment;
  1080. detailFragment.listenForTransferProgress();
  1081. detailFragment.updateFileDetails(false, false);
  1082. }
  1083. }
  1084. }
  1085. @Override
  1086. public void onServiceDisconnected(ComponentName component) {
  1087. if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
  1088. Log.d(TAG, "Download service disconnected");
  1089. mDownloaderBinder = null;
  1090. } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
  1091. Log.d(TAG, "Upload service disconnected");
  1092. mUploaderBinder = null;
  1093. }
  1094. }
  1095. };
  1096. /**
  1097. * Launch an intent to request the PIN code to the user before letting him use the app
  1098. */
  1099. private void requestPinCode() {
  1100. boolean pinStart = false;
  1101. SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  1102. pinStart = appPrefs.getBoolean("set_pincode", false);
  1103. if (pinStart) {
  1104. Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
  1105. i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
  1106. startActivity(i);
  1107. }
  1108. }
  1109. @Override
  1110. public void onSavedCertificate() {
  1111. startSynchronization();
  1112. }
  1113. @Override
  1114. public void onFailedSavingCertificate() {
  1115. showDialog(DIALOG_CERT_NOT_SAVED);
  1116. }
  1117. /**
  1118. * Updates the view associated to the activity after the finish of some operation over files
  1119. * in the current account.
  1120. *
  1121. * @param operation Removal operation performed.
  1122. * @param result Result of the removal.
  1123. */
  1124. @Override
  1125. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1126. if (operation instanceof RemoveFileOperation) {
  1127. onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
  1128. } else if (operation instanceof RenameFileOperation) {
  1129. onRenameFileOperationFinish((RenameFileOperation)operation, result);
  1130. } else if (operation instanceof SynchronizeFileOperation) {
  1131. onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
  1132. }
  1133. }
  1134. /**
  1135. * Updates the view associated to the activity after the finish of an operation trying to remove a
  1136. * file.
  1137. *
  1138. * @param operation Removal operation performed.
  1139. * @param result Result of the removal.
  1140. */
  1141. private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
  1142. dismissDialog(DIALOG_SHORT_WAIT);
  1143. if (result.isSuccess()) {
  1144. Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
  1145. msg.show();
  1146. OCFile removedFile = operation.getFile();
  1147. if (mDualPane) {
  1148. FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
  1149. if (details != null && removedFile.equals(details.getFile())) {
  1150. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  1151. transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
  1152. transaction.commit();
  1153. }
  1154. }
  1155. if (mStorageManager.getFileById(removedFile.getParentId()).equals(mCurrentDir)) {
  1156. mFileList.listDirectory();
  1157. }
  1158. } else {
  1159. Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
  1160. msg.show();
  1161. if (result.isSslRecoverableException()) {
  1162. mLastSslUntrustedServerResult = result;
  1163. showDialog(DIALOG_SSL_VALIDATOR);
  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. dismissDialog(DIALOG_SHORT_WAIT);
  1176. OCFile renamedFile = operation.getFile();
  1177. if (result.isSuccess()) {
  1178. if (mDualPane) {
  1179. FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
  1180. if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
  1181. ((FileDetailFragment) details).updateFileDetails(renamedFile, AccountUtils.getCurrentOwnCloudAccount(this));
  1182. }
  1183. }
  1184. if (mStorageManager.getFileById(renamedFile.getParentId()).equals(mCurrentDir)) {
  1185. mFileList.listDirectory();
  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. } else {
  1193. Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
  1194. msg.show();
  1195. if (result.isSslRecoverableException()) {
  1196. mLastSslUntrustedServerResult = result;
  1197. showDialog(DIALOG_SSL_VALIDATOR);
  1198. }
  1199. }
  1200. }
  1201. }
  1202. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
  1203. dismissDialog(DIALOG_SHORT_WAIT);
  1204. OCFile syncedFile = operation.getLocalFile();
  1205. if (!result.isSuccess()) {
  1206. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  1207. Intent i = new Intent(this, ConflictsResolveActivity.class);
  1208. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
  1209. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
  1210. startActivity(i);
  1211. } else {
  1212. Toast msg = Toast.makeText(this, R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
  1213. msg.show();
  1214. }
  1215. } else {
  1216. if (operation.transferWasRequested()) {
  1217. mFileList.listDirectory();
  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. /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
  1231. if (fileListFragment != null) {
  1232. fileListFragment.listDirectory();
  1233. }*/
  1234. if (mDualPane) {
  1235. FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
  1236. if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
  1237. if (downloading || uploading) {
  1238. ((FileDetailFragment)details).updateFileDetails(file, AccountUtils.getCurrentOwnCloudAccount(this));
  1239. } else {
  1240. ((FileDetailFragment)details).updateFileDetails(false, true);
  1241. }
  1242. }
  1243. }
  1244. }
  1245. @Override
  1246. public void showFragmentWithDetails(OCFile file) {
  1247. if (mDualPane) {
  1248. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  1249. transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
  1250. transaction.commit();
  1251. } else {
  1252. Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
  1253. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
  1254. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
  1255. showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
  1256. startActivity(showDetailsIntent);
  1257. }
  1258. }
  1259. public void onDismiss(EditNameDialog dialog) {
  1260. //dialog.dismiss();
  1261. if (dialog.getResult()) {
  1262. String newDirectoryName = dialog.getNewFilename().trim();
  1263. Log.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
  1264. if (newDirectoryName.length() > 0) {
  1265. String path;
  1266. if (mCurrentDir == null) {
  1267. // this is just a patch; we should ensure that mCurrentDir never is null
  1268. if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
  1269. OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
  1270. mStorageManager.saveFile(file);
  1271. }
  1272. mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
  1273. }
  1274. path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
  1275. // Create directory
  1276. path += newDirectoryName + OCFile.PATH_SEPARATOR;
  1277. Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
  1278. thread.start();
  1279. showDialog(DIALOG_SHORT_WAIT);
  1280. }
  1281. }
  1282. }
  1283. private void requestForDownload() {
  1284. Account account = AccountUtils.getCurrentOwnCloudAccount(this);
  1285. if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
  1286. Intent i = new Intent(this, FileDownloader.class);
  1287. i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
  1288. i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
  1289. startService(i);
  1290. }
  1291. }
  1292. }