ReceiveExternalFilesActivity.java 50 KB

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