ReceiveExternalFilesActivity.java 49 KB

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