ReceiveExternalFilesActivity.java 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author masensio
  6. * @author Juan Carlos González Cabrero
  7. * @author David A. Velasco
  8. * Copyright (C) 2012 Bartek Przybylski
  9. * Copyright (C) 2016 ownCloud Inc.
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License version 2,
  13. * as published by the Free Software Foundation.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. package com.owncloud.android.ui.activity;
  24. import android.accounts.Account;
  25. import android.accounts.AccountManager;
  26. import android.accounts.AuthenticatorException;
  27. import android.app.Activity;
  28. import android.app.Dialog;
  29. import android.content.BroadcastReceiver;
  30. import android.content.Context;
  31. import android.content.Intent;
  32. import android.content.IntentFilter;
  33. import android.content.res.Resources.NotFoundException;
  34. import android.graphics.PorterDuff;
  35. import android.graphics.drawable.ColorDrawable;
  36. import android.graphics.drawable.Drawable;
  37. import android.os.Bundle;
  38. import android.os.Handler;
  39. import android.os.Looper;
  40. import android.os.Parcelable;
  41. import android.support.annotation.DrawableRes;
  42. import android.support.annotation.NonNull;
  43. import android.support.annotation.Nullable;
  44. import android.support.annotation.StringRes;
  45. import android.support.v4.app.DialogFragment;
  46. import android.support.v4.app.FragmentManager;
  47. import android.support.v4.content.ContextCompat;
  48. import android.support.v4.graphics.drawable.DrawableCompat;
  49. import android.support.v4.view.MenuItemCompat;
  50. import android.support.v7.app.ActionBar;
  51. import android.support.v7.app.AlertDialog;
  52. import android.support.v7.app.AlertDialog.Builder;
  53. import android.support.v7.widget.SearchView;
  54. import android.text.format.DateFormat;
  55. import android.view.LayoutInflater;
  56. import android.view.Menu;
  57. import android.view.MenuInflater;
  58. import android.view.MenuItem;
  59. import android.view.View;
  60. import android.view.WindowManager.LayoutParams;
  61. import android.widget.AdapterView;
  62. import android.widget.AdapterView.OnItemClickListener;
  63. import android.widget.ArrayAdapter;
  64. import android.widget.Button;
  65. import android.widget.EditText;
  66. import android.widget.ImageView;
  67. import android.widget.LinearLayout;
  68. import android.widget.ListView;
  69. import android.widget.ProgressBar;
  70. import android.widget.Spinner;
  71. import android.widget.TextView;
  72. import com.owncloud.android.MainApp;
  73. import com.owncloud.android.R;
  74. import com.owncloud.android.datamodel.OCFile;
  75. import com.owncloud.android.db.PreferenceManager;
  76. import com.owncloud.android.files.services.FileUploader;
  77. import com.owncloud.android.lib.common.operations.RemoteOperation;
  78. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  79. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  80. import com.owncloud.android.lib.common.utils.Log_OC;
  81. import com.owncloud.android.operations.CreateFolderOperation;
  82. import com.owncloud.android.operations.RefreshFolderOperation;
  83. import com.owncloud.android.operations.UploadFileOperation;
  84. import com.owncloud.android.syncadapter.FileSyncAdapter;
  85. import com.owncloud.android.ui.adapter.AccountListAdapter;
  86. import com.owncloud.android.ui.adapter.AccountListItem;
  87. import com.owncloud.android.ui.adapter.UploaderAdapter;
  88. import com.owncloud.android.ui.asynctasks.CopyAndUploadContentUrisTask;
  89. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  90. import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
  91. import com.owncloud.android.ui.dialog.SortingOrderDialogFragment;
  92. import com.owncloud.android.ui.fragment.TaskRetainerFragment;
  93. import com.owncloud.android.ui.helpers.UriUploader;
  94. import com.owncloud.android.utils.DataHolderUtil;
  95. import com.owncloud.android.utils.DisplayUtils;
  96. import com.owncloud.android.utils.ErrorMessageAdapter;
  97. import com.owncloud.android.utils.FileSortOrder;
  98. import com.owncloud.android.utils.MimeType;
  99. import com.owncloud.android.utils.ThemeUtils;
  100. import java.io.File;
  101. import java.io.FileWriter;
  102. import java.io.IOException;
  103. import java.io.UnsupportedEncodingException;
  104. import java.lang.reflect.Method;
  105. import java.util.ArrayList;
  106. import java.util.Arrays;
  107. import java.util.Calendar;
  108. import java.util.HashMap;
  109. import java.util.LinkedList;
  110. import java.util.List;
  111. import java.util.Stack;
  112. import java.util.Vector;
  113. /**
  114. * This can be used to upload things to an ownCloud instance.
  115. */
  116. public class ReceiveExternalFilesActivity extends FileActivity
  117. implements OnItemClickListener, View.OnClickListener, CopyAndUploadContentUrisTask.OnCopyTmpFilesTaskListener,
  118. SortingOrderDialogFragment.OnSortingOrderListener {
  119. private static final String TAG = ReceiveExternalFilesActivity.class.getSimpleName();
  120. private static final String FTAG_ERROR_FRAGMENT = "ERROR_FRAGMENT";
  121. public static final String TEXT_FILE_SUFFIX = ".txt";
  122. public static final String URL_FILE_SUFFIX = ".url";
  123. public static final String WEBLOC_FILE_SUFFIX = ".webloc";
  124. public static final String DESKTOP_FILE_SUFFIX = ".desktop";
  125. public static final int SINGLE_PARENT = 1;
  126. private AccountManager mAccountManager;
  127. private Stack<String> mParents = new Stack<>();
  128. private List<Parcelable> mStreamsToUpload;
  129. private String mUploadPath;
  130. private OCFile mFile;
  131. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  132. private boolean mSyncInProgress;
  133. private final static int REQUEST_CODE__SETUP_ACCOUNT = REQUEST_CODE__LAST_SHARED + 1;
  134. private final static String KEY_PARENTS = "PARENTS";
  135. private final static String KEY_FILE = "FILE";
  136. private boolean mUploadFromTmpFile;
  137. private String mSubjectText;
  138. private String mExtraText;
  139. private final static String FILENAME_ENCODING = "UTF-8";
  140. private LinearLayout mEmptyListContainer;
  141. private TextView mEmptyListMessage;
  142. private TextView mEmptyListHeadline;
  143. private ImageView mEmptyListIcon;
  144. private ProgressBar mEmptyListProgress;
  145. @Override
  146. protected void onCreate(Bundle savedInstanceState) {
  147. prepareStreamsToUpload();
  148. if (savedInstanceState != null) {
  149. String parentPath = savedInstanceState.getString(KEY_PARENTS);
  150. if (parentPath != null) {
  151. mParents.addAll(Arrays.asList(parentPath.split("/")));
  152. }
  153. mFile = savedInstanceState.getParcelable(KEY_FILE);
  154. }
  155. mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
  156. super.onCreate(savedInstanceState);
  157. // Listen for sync messages
  158. IntentFilter syncIntentFilter = new IntentFilter(RefreshFolderOperation.
  159. EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  160. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  161. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  162. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  163. // Init Fragment without UI to retain AsyncTask across configuration changes
  164. FragmentManager fm = getSupportFragmentManager();
  165. TaskRetainerFragment taskRetainerFragment =
  166. (TaskRetainerFragment) fm.findFragmentByTag(TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT);
  167. if (taskRetainerFragment == null) {
  168. taskRetainerFragment = new TaskRetainerFragment();
  169. fm.beginTransaction()
  170. .add(taskRetainerFragment, TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT).commit();
  171. } // else, Fragment already created and retained across configuration change
  172. }
  173. @Override
  174. protected void setAccount(Account account, boolean savedAccount) {
  175. Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAccountType(this));
  176. if (accounts.length == 0) {
  177. Log_OC.i(TAG, "No ownCloud account is available");
  178. DialogNoAccount dialog = new DialogNoAccount();
  179. dialog.show(getSupportFragmentManager(), null);
  180. } else if (!savedAccount) {
  181. setAccount(accounts[0]);
  182. }
  183. if (!somethingToUpload()) {
  184. showErrorDialog(
  185. R.string.uploader_error_message_no_file_to_upload,
  186. R.string.uploader_error_title_no_file_to_upload
  187. );
  188. }
  189. super.setAccount(account, savedAccount);
  190. }
  191. private void showAccountChooserDialog() {
  192. DialogMultipleAccount dialog = new DialogMultipleAccount();
  193. dialog.show(getSupportFragmentManager(), null);
  194. }
  195. private Activity getActivity() {
  196. return this;
  197. }
  198. @Override
  199. protected void onAccountSet(boolean stateWasRecovered) {
  200. super.onAccountSet(mAccountWasRestored);
  201. initTargetFolder();
  202. populateDirectoryList();
  203. }
  204. @Override
  205. protected void onSaveInstanceState(Bundle outState) {
  206. Log_OC.d(TAG, "onSaveInstanceState() start");
  207. super.onSaveInstanceState(outState);
  208. outState.putString(KEY_PARENTS, generatePath(mParents));
  209. outState.putParcelable(KEY_FILE, mFile);
  210. outState.putParcelable(FileActivity.EXTRA_ACCOUNT, getAccount());
  211. Log_OC.d(TAG, "onSaveInstanceState() end");
  212. }
  213. @Override
  214. protected void onDestroy() {
  215. if (mSyncBroadcastReceiver != null) {
  216. unregisterReceiver(mSyncBroadcastReceiver);
  217. }
  218. super.onDestroy();
  219. }
  220. @Override
  221. public void onSortingOrderChosen(FileSortOrder newSortOrder) {
  222. PreferenceManager.setSortOrder(getBaseContext(), mFile, newSortOrder);
  223. populateDirectoryList();
  224. }
  225. public static class DialogNoAccount extends DialogFragment {
  226. @NonNull
  227. @Override
  228. public Dialog onCreateDialog(Bundle savedInstanceState) {
  229. AlertDialog.Builder builder = new Builder(getActivity());
  230. builder.setIcon(R.drawable.ic_warning);
  231. builder.setTitle(R.string.uploader_wrn_no_account_title);
  232. builder.setMessage(String.format(getString(R.string.uploader_wrn_no_account_text),
  233. getString(R.string.app_name)));
  234. builder.setCancelable(false);
  235. builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, (dialog, which) -> {
  236. // using string value since in API7 this
  237. // constant is not defined
  238. // in API7 < this constant is defined in
  239. // Settings.ADD_ACCOUNT_SETTINGS
  240. // and Settings.EXTRA_AUTHORITIES
  241. Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
  242. intent.putExtra("authorities", new String[]{MainApp.getAuthTokenType()});
  243. startActivityForResult(intent, REQUEST_CODE__SETUP_ACCOUNT);
  244. });
  245. builder.setNegativeButton(R.string.uploader_wrn_no_account_quit_btn_text, (dialog, which) -> getActivity().finish());
  246. return builder.create();
  247. }
  248. }
  249. public static class DialogMultipleAccount extends DialogFragment {
  250. private AccountListAdapter mAccountListAdapter;
  251. private Drawable mTintedCheck;
  252. @NonNull
  253. @Override
  254. public Dialog onCreateDialog(Bundle savedInstanceState) {
  255. final ReceiveExternalFilesActivity parent = (ReceiveExternalFilesActivity) getActivity();
  256. AlertDialog.Builder builder = new Builder(parent);
  257. mTintedCheck = DrawableCompat.wrap(ContextCompat.getDrawable(parent, R.drawable.account_circle_white));
  258. int tint = ThemeUtils.primaryColor(getContext());
  259. DrawableCompat.setTint(mTintedCheck, tint);
  260. mAccountListAdapter = new AccountListAdapter(parent, getAccountListItems(parent), mTintedCheck);
  261. builder.setTitle(R.string.common_choose_account);
  262. builder.setAdapter(mAccountListAdapter, (dialog, which) -> {
  263. final ReceiveExternalFilesActivity parent1 = (ReceiveExternalFilesActivity) getActivity();
  264. parent1.setAccount(parent1.mAccountManager.getAccountsByType(
  265. MainApp.getAccountType(getActivity()))[which], false);
  266. parent1.onAccountSet(parent1.mAccountWasRestored);
  267. dialog.dismiss();
  268. });
  269. builder.setCancelable(true);
  270. return builder.create();
  271. }
  272. /**
  273. * creates the account list items list including the add-account action in case multiaccount_support is enabled.
  274. *
  275. * @return list of account list items
  276. */
  277. private List<AccountListItem> getAccountListItems(ReceiveExternalFilesActivity activity) {
  278. Account[] accountList = activity.mAccountManager.getAccountsByType(MainApp.getAccountType(getActivity()));
  279. List<AccountListItem> adapterAccountList = new ArrayList<>(accountList.length);
  280. for (Account account : accountList) {
  281. adapterAccountList.add(new AccountListItem(account));
  282. }
  283. return adapterAccountList;
  284. }
  285. }
  286. public static class DialogInputUploadFilename extends DialogFragment {
  287. private static final String KEY_SUBJECT_TEXT = "SUBJECT_TEXT";
  288. private static final String KEY_EXTRA_TEXT = "EXTRA_TEXT";
  289. private static final int CATEGORY_URL = 1;
  290. private static final int CATEGORY_MAPS_URL = 2;
  291. private static final int EXTRA_TEXT_LENGTH = 3;
  292. private static final int SINGLE_SPINNER_ENTRY = 1;
  293. private List<String> mFilenameBase;
  294. private List<String> mFilenameSuffix;
  295. private List<String> mText;
  296. private int mFileCategory;
  297. private Spinner mSpinner;
  298. public static DialogInputUploadFilename newInstance(String subjectText, String extraText) {
  299. DialogInputUploadFilename dialog = new DialogInputUploadFilename();
  300. Bundle args = new Bundle();
  301. args.putString(KEY_SUBJECT_TEXT, subjectText);
  302. args.putString(KEY_EXTRA_TEXT, extraText);
  303. dialog.setArguments(args);
  304. return dialog;
  305. }
  306. @NonNull
  307. @Override
  308. public Dialog onCreateDialog(Bundle savedInstanceState) {
  309. mFilenameBase = new ArrayList<>();
  310. mFilenameSuffix = new ArrayList<>();
  311. mText = new ArrayList<>();
  312. String subjectText = "";
  313. String extraText = "";
  314. if (getArguments() != null) {
  315. if (getArguments().getString(KEY_SUBJECT_TEXT) != null) {
  316. subjectText = getArguments().getString(KEY_SUBJECT_TEXT);
  317. }
  318. if (getArguments().getString(KEY_EXTRA_TEXT) != null) {
  319. extraText = getArguments().getString(KEY_EXTRA_TEXT);
  320. }
  321. }
  322. LayoutInflater layout = LayoutInflater.from(requireContext());
  323. View view = layout.inflate(R.layout.upload_file_dialog, null);
  324. ArrayAdapter<String> adapter
  325. = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item);
  326. adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  327. int selectPos = 0;
  328. String filename = renameSafeFilename(subjectText);
  329. if (filename == null) {
  330. filename = "";
  331. }
  332. adapter.add(getString(R.string.upload_file_dialog_filetype_snippet_text));
  333. mText.add(extraText);
  334. mFilenameBase.add(filename);
  335. mFilenameSuffix.add(TEXT_FILE_SUFFIX);
  336. if (isIntentStartWithUrl(extraText)) {
  337. String str = getString(R.string.upload_file_dialog_filetype_internet_shortcut);
  338. mText.add(internetShortcutUrlText(extraText));
  339. mFilenameBase.add(filename);
  340. mFilenameSuffix.add(URL_FILE_SUFFIX);
  341. adapter.add(String.format(str,URL_FILE_SUFFIX));
  342. mText.add(internetShortcutWeblocText(extraText));
  343. mFilenameBase.add(filename);
  344. mFilenameSuffix.add(WEBLOC_FILE_SUFFIX);
  345. adapter.add(String.format(str,WEBLOC_FILE_SUFFIX));
  346. mText.add(internetShortcutDesktopText(extraText, filename));
  347. mFilenameBase.add(filename);
  348. mFilenameSuffix.add(DESKTOP_FILE_SUFFIX);
  349. adapter.add(String.format(str,DESKTOP_FILE_SUFFIX));
  350. selectPos = PreferenceManager.getUploadUrlFileExtensionUrlSelectedPos(getActivity());
  351. mFileCategory = CATEGORY_URL;
  352. } else if (isIntentFromGoogleMap(subjectText, extraText)) {
  353. String str = getString(R.string.upload_file_dialog_filetype_googlemap_shortcut);
  354. String texts[] = extraText.split("\n");
  355. mText.add(internetShortcutUrlText(texts[2]));
  356. mFilenameBase.add(texts[0]);
  357. mFilenameSuffix.add(URL_FILE_SUFFIX);
  358. adapter.add(String.format(str,URL_FILE_SUFFIX));
  359. mText.add(internetShortcutWeblocText(texts[2]));
  360. mFilenameBase.add(texts[0]);
  361. mFilenameSuffix.add(WEBLOC_FILE_SUFFIX);
  362. adapter.add(String.format(str,WEBLOC_FILE_SUFFIX));
  363. mText.add(internetShortcutDesktopText(texts[2], texts[0]));
  364. mFilenameBase.add(texts[0]);
  365. mFilenameSuffix.add(DESKTOP_FILE_SUFFIX);
  366. adapter.add(String.format(str,DESKTOP_FILE_SUFFIX));
  367. selectPos = PreferenceManager.getUploadMapFileExtensionUrlSelectedPos(getActivity());
  368. mFileCategory = CATEGORY_MAPS_URL;
  369. }
  370. final EditText userInput = view.findViewById(R.id.user_input);
  371. setFilename(userInput, selectPos);
  372. userInput.requestFocus();
  373. final Spinner spinner = view.findViewById(R.id.file_type);
  374. setupSpinner(adapter, selectPos, userInput, spinner);
  375. if (adapter.getCount() == SINGLE_SPINNER_ENTRY) {
  376. view.findViewById(R.id.label_file_type).setVisibility(View.GONE);
  377. spinner.setVisibility(View.GONE);
  378. }
  379. mSpinner = spinner;
  380. Dialog filenameDialog = createFilenameDialog(view, userInput, spinner);
  381. if (filenameDialog.getWindow() != null) {
  382. filenameDialog.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
  383. }
  384. return filenameDialog;
  385. }
  386. private void setupSpinner(ArrayAdapter<String> adapter, int selectPos, final EditText userInput, Spinner spinner) {
  387. spinner.setAdapter(adapter);
  388. spinner.setSelection(selectPos, false);
  389. spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  390. @Override
  391. public void onItemSelected(AdapterView parent, View view, int position, long id) {
  392. Spinner spinner = (Spinner) parent;
  393. int selectPos = spinner.getSelectedItemPosition();
  394. setFilename(userInput, selectPos);
  395. saveSelection(selectPos);
  396. }
  397. @Override
  398. public void onNothingSelected(AdapterView<?> parent) {
  399. // nothing to do
  400. }
  401. });
  402. }
  403. @NonNull
  404. private Dialog createFilenameDialog(View view, final EditText userInput, final Spinner spinner) {
  405. Builder builder = new Builder(requireActivity());
  406. builder.setView(view);
  407. builder.setTitle(R.string.upload_file_dialog_title);
  408. builder.setPositiveButton(R.string.common_ok, (dialog, id) -> {
  409. int selectPos = spinner.getSelectedItemPosition();
  410. // verify if file name has suffix
  411. String filename = userInput.getText().toString();
  412. String suffix = mFilenameSuffix.get(selectPos);
  413. if (!filename.endsWith(suffix)) {
  414. filename += suffix;
  415. }
  416. File file = createTempFile(mText.get(selectPos));
  417. if (file == null) {
  418. getActivity().finish();
  419. } else {
  420. String tmpName = file.getAbsolutePath();
  421. ((ReceiveExternalFilesActivity) getActivity()).uploadFile(tmpName, filename);
  422. }
  423. });
  424. builder.setNegativeButton(R.string.common_cancel, (dialog, id) -> dialog.cancel());
  425. return builder.create();
  426. }
  427. public void onPause() {
  428. hideSpinnerDropDown(mSpinner);
  429. super.onPause();
  430. }
  431. private void saveSelection(int selectPos) {
  432. switch (mFileCategory) {
  433. case CATEGORY_URL:
  434. PreferenceManager.setUploadUrlFileExtensionUrlSelectedPos(getActivity(), selectPos);
  435. break;
  436. case CATEGORY_MAPS_URL:
  437. PreferenceManager.setUploadMapFileExtensionUrlSelectedPos(getActivity(), selectPos);
  438. break;
  439. default:
  440. Log_OC.d(TAG, "Simple text snippet only: no selection to be persisted");
  441. break;
  442. }
  443. }
  444. private void hideSpinnerDropDown(Spinner spinner) {
  445. try {
  446. Method method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
  447. method.setAccessible(true);
  448. method.invoke(spinner);
  449. } catch (Exception e) {
  450. Log_OC.e(TAG, "onDetachedFromWindow", e);
  451. }
  452. }
  453. private void setFilename(EditText inputText, int selectPos)
  454. {
  455. String filename = mFilenameBase.get(selectPos) + mFilenameSuffix.get(selectPos);
  456. inputText.setText(filename);
  457. int selectionStart = 0;
  458. int extensionStart = filename.lastIndexOf('.');
  459. int selectionEnd = extensionStart >= 0 ? extensionStart : filename.length();
  460. if (selectionEnd >= 0) {
  461. inputText.setSelection(
  462. Math.min(selectionStart, selectionEnd),
  463. Math.max(selectionStart, selectionEnd));
  464. }
  465. }
  466. private boolean isIntentFromGoogleMap(String subjectText, String extraText) {
  467. String texts[] = extraText.split("\n");
  468. if (texts.length != EXTRA_TEXT_LENGTH) {
  469. return false;
  470. }
  471. if (texts[0].length() == 0 || !subjectText.equals(texts[0])) {
  472. return false;
  473. }
  474. return texts[2].startsWith("https://goo.gl/maps/");
  475. }
  476. private boolean isIntentStartWithUrl(String extraText) {
  477. return extraText.startsWith("http://") || extraText.startsWith("https://");
  478. }
  479. @Nullable
  480. private String renameSafeFilename(String filename) {
  481. String safeFilename = filename;
  482. safeFilename = safeFilename.replaceAll("[?]", "_");
  483. safeFilename = safeFilename.replaceAll("\"", "_");
  484. safeFilename = safeFilename.replaceAll("/", "_");
  485. safeFilename = safeFilename.replaceAll("<", "_");
  486. safeFilename = safeFilename.replaceAll(">", "_");
  487. safeFilename = safeFilename.replaceAll("[*]", "_");
  488. safeFilename = safeFilename.replaceAll("[|]", "_");
  489. safeFilename = safeFilename.replaceAll(";", "_");
  490. safeFilename = safeFilename.replaceAll("=", "_");
  491. safeFilename = safeFilename.replaceAll(",", "_");
  492. try {
  493. int maxLength = 128;
  494. if (safeFilename.getBytes(FILENAME_ENCODING).length > maxLength) {
  495. safeFilename = new String(safeFilename.getBytes(FILENAME_ENCODING), 0, maxLength, FILENAME_ENCODING);
  496. }
  497. } catch (UnsupportedEncodingException e) {
  498. Log_OC.e(TAG, "rename failed ", e);
  499. return null;
  500. }
  501. return safeFilename;
  502. }
  503. private String internetShortcutUrlText(String url) {
  504. return "[InternetShortcut]\r\n" +
  505. "URL=" + url + "\r\n";
  506. }
  507. private String internetShortcutWeblocText(String url) {
  508. return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
  509. "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" +
  510. "<plist version=\"1.0\">\n" +
  511. "<dict>\n" +
  512. "<key>URL</key>\n" +
  513. "<string>" + url + "</string>\n" +
  514. "</dict>\n" +
  515. "</plist>\n";
  516. }
  517. private String internetShortcutDesktopText(String url, String filename) {
  518. return "[Desktop Entry]\n" +
  519. "Encoding=UTF-8\n" +
  520. "Name=" + filename + "\n" +
  521. "Type=Link\n" +
  522. "URL=" + url + "\n" +
  523. "Icon=text-html";
  524. }
  525. @Nullable
  526. private File createTempFile(String text) {
  527. File file = new File(getActivity().getCacheDir(), "tmp.tmp");
  528. FileWriter fw = null;
  529. try {
  530. fw = new FileWriter(file);
  531. fw.write(text);
  532. } catch (IOException e) {
  533. Log_OC.d(TAG, "Error ", e);
  534. return null;
  535. } finally {
  536. if (fw != null) {
  537. try {
  538. fw.close();
  539. } catch (IOException e) {
  540. Log_OC.d(TAG, "Error closing file writer ", e);
  541. }
  542. }
  543. }
  544. return file;
  545. }
  546. }
  547. @Override
  548. public void onBackPressed() {
  549. if (mParents.size() <= SINGLE_PARENT) {
  550. super.onBackPressed();
  551. } else {
  552. mParents.pop();
  553. String full_path = generatePath(mParents);
  554. startSyncFolderOperation(getStorageManager().getFileByPath(full_path));
  555. populateDirectoryList();
  556. }
  557. }
  558. @Override
  559. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  560. // click on folder in the list
  561. Log_OC.d(TAG, "on item click");
  562. List<OCFile> tmpFiles = getStorageManager().getFolderContent(mFile, false);
  563. tmpFiles = sortFileList(tmpFiles);
  564. if (tmpFiles.isEmpty()) {
  565. return;
  566. }
  567. // filter on dirtype
  568. Vector<OCFile> files = new Vector<>();
  569. files.addAll(tmpFiles);
  570. if (files.size() < position) {
  571. throw new IndexOutOfBoundsException("Incorrect item selected");
  572. }
  573. if (files.get(position).isFolder()){
  574. OCFile folderToEnter = files.get(position);
  575. startSyncFolderOperation(folderToEnter);
  576. mParents.push(folderToEnter.getFileName());
  577. populateDirectoryList();
  578. }
  579. }
  580. @Override
  581. public void onClick(View v) {
  582. // click on button
  583. switch (v.getId()) {
  584. case R.id.uploader_choose_folder:
  585. mUploadPath = ""; // first element in mParents is root dir, represented by "";
  586. // init mUploadPath with "/" results in a "//" prefix
  587. for (String p : mParents) {
  588. mUploadPath += p + OCFile.PATH_SEPARATOR;
  589. }
  590. if (mUploadFromTmpFile) {
  591. DialogInputUploadFilename dialog = DialogInputUploadFilename.newInstance(mSubjectText, mExtraText);
  592. dialog.show(getSupportFragmentManager(), null);
  593. } else {
  594. Log_OC.d(TAG, "Uploading file to dir " + mUploadPath);
  595. uploadFiles();
  596. }
  597. break;
  598. case R.id.uploader_cancel:
  599. finish();
  600. break;
  601. default:
  602. throw new IllegalArgumentException("Wrong element clicked");
  603. }
  604. }
  605. @Override
  606. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  607. super.onActivityResult(requestCode, resultCode, data);
  608. Log_OC.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);
  609. if (requestCode == REQUEST_CODE__SETUP_ACCOUNT) {
  610. if (resultCode == RESULT_CANCELED) {
  611. finish();
  612. }
  613. Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAuthTokenType());
  614. if (accounts.length == 0) {
  615. DialogNoAccount dialog = new DialogNoAccount();
  616. dialog.show(getSupportFragmentManager(), null);
  617. } else {
  618. // there is no need for checking for is there more then one
  619. // account at this point
  620. // since account setup can set only one account at time
  621. setAccount(accounts[0]);
  622. populateDirectoryList();
  623. }
  624. }
  625. }
  626. private void setupActionBarSubtitle() {
  627. if (isHaveMultipleAccount()) {
  628. ActionBar actionBar = getSupportActionBar();
  629. if (actionBar != null) {
  630. actionBar.setSubtitle(getAccount().name);
  631. }
  632. }
  633. }
  634. private void populateDirectoryList() {
  635. setContentView(R.layout.uploader_layout);
  636. setupEmptyList();
  637. setupToolbar();
  638. ActionBar actionBar = getSupportActionBar();
  639. setupActionBarSubtitle();
  640. ListView mListView = findViewById(android.R.id.list);
  641. String current_dir = mParents.peek();
  642. boolean notRoot = mParents.size() > 1;
  643. if (actionBar != null) {
  644. if ("".equals(current_dir)) {
  645. ThemeUtils.setColoredTitle(actionBar, R.string.uploader_top_message, this);
  646. } else {
  647. ThemeUtils.setColoredTitle(actionBar, current_dir, this);
  648. }
  649. actionBar.setDisplayHomeAsUpEnabled(notRoot);
  650. actionBar.setHomeButtonEnabled(notRoot);
  651. }
  652. String full_path = generatePath(mParents);
  653. Log_OC.d(TAG, "Populating view with content of : " + full_path);
  654. mFile = getStorageManager().getFileByPath(full_path);
  655. if (mFile != null) {
  656. List<OCFile> files = getStorageManager().getFolderContent(mFile, false);
  657. if (files.isEmpty()) {
  658. setMessageForEmptyList(R.string.file_list_empty_headline, R.string.empty,
  659. R.drawable.ic_list_empty_upload);
  660. } else {
  661. mEmptyListContainer.setVisibility(View.GONE);
  662. files = sortFileList(files);
  663. List<HashMap<String, Object>> data = new LinkedList<>();
  664. for (OCFile f : files) {
  665. HashMap<String, Object> h = new HashMap<>();
  666. h.put("dirname", f);
  667. data.add(h);
  668. }
  669. UploaderAdapter sa = new UploaderAdapter(this,
  670. data,
  671. R.layout.uploader_list_item_layout,
  672. new String[]{"dirname"},
  673. new int[]{R.id.filename},
  674. getStorageManager(), getAccount());
  675. mListView.setAdapter(sa);
  676. }
  677. Button btnChooseFolder = findViewById(R.id.uploader_choose_folder);
  678. btnChooseFolder.setOnClickListener(this);
  679. btnChooseFolder.getBackground().setColorFilter(ThemeUtils.primaryColor(getAccount(), true, this),
  680. PorterDuff.Mode.SRC_ATOP);
  681. btnChooseFolder.setTextColor(ThemeUtils.fontColor(this));
  682. if (getSupportActionBar() != null) {
  683. getSupportActionBar().setBackgroundDrawable(new ColorDrawable(
  684. ThemeUtils.primaryColor(getAccount(), false, this)));
  685. }
  686. ThemeUtils.colorStatusBar(this, ThemeUtils.primaryDarkColor(getAccount(), this));
  687. ThemeUtils.colorToolbarProgressBar(this, ThemeUtils.primaryColor(getAccount(), false, this));
  688. Drawable backArrow = getResources().getDrawable(R.drawable.ic_arrow_back);
  689. if (actionBar != null) {
  690. actionBar.setHomeAsUpIndicator(ThemeUtils.tintDrawable(backArrow, ThemeUtils.fontColor(this)));
  691. }
  692. Button btnNewFolder = findViewById(R.id.uploader_cancel);
  693. btnNewFolder.setOnClickListener(this);
  694. mListView.setOnItemClickListener(this);
  695. }
  696. }
  697. protected void setupEmptyList() {
  698. mEmptyListContainer = findViewById(R.id.empty_list_view);
  699. mEmptyListMessage = findViewById(R.id.empty_list_view_text);
  700. mEmptyListHeadline = findViewById(R.id.empty_list_view_headline);
  701. mEmptyListIcon = findViewById(R.id.empty_list_icon);
  702. mEmptyListProgress = findViewById(R.id.empty_list_progress);
  703. mEmptyListProgress.getIndeterminateDrawable().setColorFilter(ThemeUtils.primaryColor(this),
  704. PorterDuff.Mode.SRC_IN);
  705. }
  706. public void setMessageForEmptyList(@StringRes final int headline, @StringRes final int message,
  707. @DrawableRes final int icon) {
  708. new Handler(Looper.getMainLooper()).post(() -> {
  709. if (mEmptyListContainer != null && mEmptyListMessage != null) {
  710. mEmptyListHeadline.setText(headline);
  711. mEmptyListMessage.setText(message);
  712. mEmptyListIcon.setImageDrawable(ThemeUtils.tintDrawable(icon, ThemeUtils.primaryColor(this, true)));
  713. mEmptyListIcon.setVisibility(View.VISIBLE);
  714. mEmptyListProgress.setVisibility(View.GONE);
  715. mEmptyListMessage.setVisibility(View.VISIBLE);
  716. }
  717. });
  718. }
  719. @Override
  720. public void onSavedCertificate() {
  721. startSyncFolderOperation(getCurrentDir());
  722. }
  723. private void startSyncFolderOperation(OCFile folder) {
  724. long currentSyncTime = System.currentTimeMillis();
  725. mSyncInProgress = true;
  726. // perform folder synchronization
  727. RemoteOperation syncFolderOp = new RefreshFolderOperation(folder,
  728. currentSyncTime,
  729. false,
  730. false,
  731. getStorageManager(),
  732. getAccount(),
  733. getApplicationContext()
  734. );
  735. syncFolderOp.execute(getAccount(), this, null, null);
  736. }
  737. private List<OCFile> sortFileList(List<OCFile> files) {
  738. FileSortOrder sortOrder = PreferenceManager.getSortOrderByFolder(this, mFile);
  739. return sortOrder.sortCloudFiles(files);
  740. }
  741. private String generatePath(Stack<String> dirs) {
  742. String full_path = "";
  743. for (String a : dirs) {
  744. full_path += a + "/";
  745. }
  746. return full_path;
  747. }
  748. private void prepareStreamsToUpload() {
  749. Intent intent = getIntent();
  750. if (Intent.ACTION_SEND.equals(intent.getAction())) {
  751. mStreamsToUpload = new ArrayList<>();
  752. mStreamsToUpload.add(intent.getParcelableExtra(Intent.EXTRA_STREAM));
  753. } else if (Intent.ACTION_SEND_MULTIPLE.equals(intent.getAction())) {
  754. mStreamsToUpload = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
  755. }
  756. if (mStreamsToUpload == null || mStreamsToUpload.isEmpty() || mStreamsToUpload.get(0) == null) {
  757. mStreamsToUpload = null;
  758. saveTextsFromIntent(intent);
  759. }
  760. }
  761. private void saveTextsFromIntent(Intent intent) {
  762. if (!MimeType.TEXT_PLAIN.equals(intent.getType())) {
  763. return;
  764. }
  765. mUploadFromTmpFile = true;
  766. mSubjectText = intent.getStringExtra(Intent.EXTRA_SUBJECT);
  767. if (mSubjectText == null) {
  768. mSubjectText = intent.getStringExtra(Intent.EXTRA_TITLE);
  769. if (mSubjectText == null) {
  770. mSubjectText = DateFormat.format("yyyyMMdd_kkmmss", Calendar.getInstance()).toString();
  771. }
  772. }
  773. mExtraText = intent.getStringExtra(Intent.EXTRA_TEXT);
  774. }
  775. private boolean somethingToUpload() {
  776. return (mStreamsToUpload != null && mStreamsToUpload.size() > 0 && mStreamsToUpload.get(0) != null ||
  777. mUploadFromTmpFile);
  778. }
  779. public void uploadFile(String tmpName, String filename) {
  780. FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
  781. requester.uploadNewFile(
  782. getBaseContext(),
  783. getAccount(),
  784. tmpName,
  785. mFile.getRemotePath() + filename,
  786. FileUploader.LOCAL_BEHAVIOUR_COPY,
  787. null,
  788. true,
  789. UploadFileOperation.CREATED_BY_USER,
  790. false,
  791. false
  792. );
  793. finish();
  794. }
  795. public void uploadFiles() {
  796. UriUploader uploader = new UriUploader(
  797. this,
  798. mStreamsToUpload,
  799. mUploadPath,
  800. getAccount(),
  801. FileUploader.LOCAL_BEHAVIOUR_FORGET,
  802. true, // Show waiting dialog while file is being copied from private storage
  803. this // Copy temp task listener
  804. );
  805. UriUploader.UriUploaderResultCode resultCode = uploader.uploadUris();
  806. // Save the path to shared preferences; even if upload is not possible, user chose the folder
  807. PreferenceManager.setLastUploadPath(this, mUploadPath);
  808. if (resultCode == UriUploader.UriUploaderResultCode.OK) {
  809. finish();
  810. } else {
  811. int messageResTitle = R.string.uploader_error_title_file_cannot_be_uploaded;
  812. int messageResId = R.string.common_error_unknown;
  813. if (resultCode == UriUploader.UriUploaderResultCode.ERROR_NO_FILE_TO_UPLOAD) {
  814. messageResId = R.string.uploader_error_message_no_file_to_upload;
  815. messageResTitle = R.string.uploader_error_title_no_file_to_upload;
  816. } else if (resultCode == UriUploader.UriUploaderResultCode.ERROR_READ_PERMISSION_NOT_GRANTED) {
  817. messageResId = R.string.uploader_error_message_read_permission_not_granted;
  818. } else if (resultCode == UriUploader.UriUploaderResultCode.ERROR_UNKNOWN) {
  819. messageResId = R.string.common_error_unknown;
  820. }
  821. showErrorDialog(
  822. messageResId,
  823. messageResTitle
  824. );
  825. }
  826. }
  827. @Override
  828. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  829. super.onRemoteOperationFinish(operation, result);
  830. if (operation instanceof CreateFolderOperation) {
  831. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  832. }
  833. }
  834. /**
  835. * Updates the view associated to the activity after the finish of an operation
  836. * trying create a new folder
  837. *
  838. * @param operation Creation operation performed.
  839. * @param result Result of the creation.
  840. */
  841. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  842. RemoteOperationResult result) {
  843. if (result.isSuccess()) {
  844. String remotePath = operation.getRemotePath().substring(0, operation.getRemotePath().length() - 1);
  845. String newFolder = remotePath.substring(remotePath.lastIndexOf('/') + 1);
  846. mParents.push(newFolder);
  847. populateDirectoryList();
  848. } else {
  849. try {
  850. DisplayUtils.showSnackMessage(
  851. this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources())
  852. );
  853. } catch (NotFoundException e) {
  854. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  855. }
  856. }
  857. }
  858. /**
  859. * Loads the target folder initialize shown to the user.
  860. * <p/>
  861. * The target account has to be chosen before this method is called.
  862. */
  863. private void initTargetFolder() {
  864. if (getStorageManager() == null) {
  865. throw new IllegalStateException("Do not call this method before initializing mStorageManager");
  866. }
  867. if (mParents.empty()) {
  868. String lastPath = PreferenceManager.getLastUploadPath(this);
  869. // "/" equals root-directory
  870. if ("/".equals(lastPath)) {
  871. mParents.add("");
  872. } else {
  873. String[] dir_names = lastPath.split("/");
  874. mParents.clear();
  875. mParents.addAll(Arrays.asList(dir_names));
  876. }
  877. }
  878. // make sure that path still exists, if it doesn't pop the stack and try the previous path
  879. while (!getStorageManager().fileExists(generatePath(mParents)) && mParents.size() > 1) {
  880. mParents.pop();
  881. }
  882. }
  883. private boolean isHaveMultipleAccount() {
  884. return mAccountManager.getAccountsByType(MainApp.getAccountType(this)).length > 1;
  885. }
  886. @Override
  887. public boolean onCreateOptionsMenu(Menu menu) {
  888. MenuInflater inflater = getMenuInflater();
  889. inflater.inflate(R.menu.receive_file_menu, menu);
  890. if (!isHaveMultipleAccount()) {
  891. MenuItem switchAccountMenu = menu.findItem(R.id.action_switch_account);
  892. switchAccountMenu.setVisible(false);
  893. }
  894. // tint search event
  895. final MenuItem item = menu.findItem(R.id.action_search);
  896. SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
  897. // hacky as no default way is provided
  898. int fontColor = ThemeUtils.fontColor(this);
  899. EditText editText = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
  900. editText.setHintTextColor(fontColor);
  901. editText.setTextColor(fontColor);
  902. ImageView searchClose = searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
  903. searchClose.setColorFilter(ThemeUtils.fontColor(this));
  904. ImageView searchButton = searchView.findViewById(android.support.v7.appcompat.R.id.search_button);
  905. searchButton.setColorFilter(ThemeUtils.fontColor(this));
  906. return true;
  907. }
  908. @Override
  909. public boolean onOptionsItemSelected(MenuItem item) {
  910. boolean retval = true;
  911. switch (item.getItemId()) {
  912. case R.id.action_create_dir:
  913. CreateFolderDialogFragment dialog = CreateFolderDialogFragment.newInstance(mFile);
  914. dialog.show(getSupportFragmentManager(), CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT);
  915. break;
  916. case android.R.id.home:
  917. if (mParents.size() > SINGLE_PARENT) {
  918. onBackPressed();
  919. }
  920. break;
  921. case R.id.action_switch_account:
  922. showAccountChooserDialog();
  923. break;
  924. case R.id.action_sort:
  925. SortingOrderDialogFragment mSortingOrderDialogFragment = SortingOrderDialogFragment.newInstance(
  926. PreferenceManager.getSortOrderByFolder(this, mFile));
  927. mSortingOrderDialogFragment.show(getSupportFragmentManager(),
  928. SortingOrderDialogFragment.SORTING_ORDER_FRAGMENT);
  929. break;
  930. default:
  931. retval = super.onOptionsItemSelected(item);
  932. break;
  933. }
  934. return retval;
  935. }
  936. private OCFile getCurrentFolder(){
  937. OCFile file = mFile;
  938. if (file != null) {
  939. if (file.isFolder()) {
  940. return file;
  941. } else if (getStorageManager() != null) {
  942. return getStorageManager().getFileByPath(file.getParentRemotePath());
  943. }
  944. }
  945. return null;
  946. }
  947. private void browseToRoot() {
  948. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  949. mFile = root;
  950. startSyncFolderOperation(root);
  951. }
  952. private class SyncBroadcastReceiver extends BroadcastReceiver {
  953. /**
  954. * {@link BroadcastReceiver} to enable syncing feedback in UI
  955. */
  956. @Override
  957. public void onReceive(Context context, Intent intent) {
  958. try {
  959. String event = intent.getAction();
  960. Log_OC.d(TAG, "Received broadcast " + event);
  961. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  962. String syncFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  963. RemoteOperationResult syncResult = (RemoteOperationResult)
  964. DataHolderUtil.getInstance().retrieve(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  965. boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name)
  966. && getStorageManager() != null;
  967. if (sameAccount) {
  968. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  969. mSyncInProgress = true;
  970. } else {
  971. OCFile currentFile = (mFile == null) ? null :
  972. getStorageManager().getFileByPath(mFile.getRemotePath());
  973. OCFile currentDir = (getCurrentFolder() == null) ? null :
  974. getStorageManager().getFileByPath(getCurrentFolder().getRemotePath());
  975. if (currentDir == null) {
  976. // current folder was removed from the server
  977. DisplayUtils.showSnackMessage(
  978. getActivity(),
  979. R.string.sync_current_folder_was_removed,
  980. getCurrentFolder().getFileName()
  981. );
  982. browseToRoot();
  983. } else {
  984. if (currentFile == null && !mFile.isFolder()) {
  985. // currently selected file was removed in the server, and now we know it
  986. currentFile = currentDir;
  987. }
  988. if (currentDir.getRemotePath().equals(syncFolderRemotePath)) {
  989. populateDirectoryList();
  990. }
  991. mFile = currentFile;
  992. }
  993. mSyncInProgress = !FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  994. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event);
  995. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.equals(event)
  996. /// TODO refactor and make common
  997. && syncResult != null && !syncResult.isSuccess()) {
  998. if (syncResult.getCode() == ResultCode.UNAUTHORIZED ||
  999. (syncResult.isException() && syncResult.getException()
  1000. instanceof AuthenticatorException)) {
  1001. requestCredentialsUpdate(context);
  1002. } else if (RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(syncResult.getCode())) {
  1003. showUntrustedCertDialog(syncResult);
  1004. }
  1005. }
  1006. }
  1007. removeStickyBroadcast(intent);
  1008. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  1009. }
  1010. } catch (RuntimeException e) {
  1011. // avoid app crashes after changing the serial id of RemoteOperationResult
  1012. // in owncloud library with broadcast notifications pending to process
  1013. removeStickyBroadcast(intent);
  1014. DataHolderUtil.getInstance().delete(intent.getStringExtra(FileSyncAdapter.EXTRA_RESULT));
  1015. }
  1016. }
  1017. }
  1018. /**
  1019. * Process the result of CopyAndUploadContentUrisTask
  1020. */
  1021. @Override
  1022. public void onTmpFilesCopied(ResultCode result) {
  1023. dismissLoadingDialog();
  1024. finish();
  1025. }
  1026. /**
  1027. * Show an error dialog, forcing the user to click a single button to exit the activity
  1028. *
  1029. * @param messageResId Resource id of the message to show in the dialog.
  1030. * @param messageResTitle Resource id of the title to show in the dialog. 0 to show default alert message.
  1031. * -1 to show no title.
  1032. */
  1033. private void showErrorDialog(int messageResId, int messageResTitle) {
  1034. ConfirmationDialogFragment errorDialog = ConfirmationDialogFragment.newInstance(
  1035. messageResId,
  1036. new String[]{getString(R.string.app_name)}, // see uploader_error_message_* in strings.xml
  1037. messageResTitle,
  1038. R.string.common_back,
  1039. -1,
  1040. -1
  1041. );
  1042. errorDialog.setCancelable(false);
  1043. errorDialog.setOnConfirmationListener(
  1044. new ConfirmationDialogFragment.ConfirmationDialogFragmentListener() {
  1045. @Override
  1046. public void onConfirmation(String callerTag) {
  1047. finish();
  1048. }
  1049. @Override
  1050. public void onNeutral(String callerTag) {
  1051. // not used at the moment
  1052. }
  1053. @Override
  1054. public void onCancel(String callerTag) {
  1055. // not used at the moment
  1056. }
  1057. }
  1058. );
  1059. errorDialog.show(getSupportFragmentManager(), FTAG_ERROR_FRAGMENT);
  1060. }
  1061. }