ReceiveExternalFilesActivity.java 48 KB

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