ReceiveExternalFilesActivity.java 48 KB

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