ChooseTemplateDialogFragment.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /*
  2. * Nextcloud Android client application
  3. *
  4. * @author Tobias Kaminsky
  5. * @author Chris Narkiewicz
  6. *
  7. * Copyright (C) 2018 Tobias Kaminsky
  8. * Copyright (C) 2018 Nextcloud GmbH.
  9. * Copyright (C) 2019 Chris Narkiewicz <hello@ezaquarii.com>
  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 as published by
  13. * the Free Software Foundation, either version 3 of the License, or
  14. * (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  23. */
  24. package com.owncloud.android.ui.dialog;
  25. import android.annotation.SuppressLint;
  26. import android.app.Activity;
  27. import android.app.Dialog;
  28. import android.content.Context;
  29. import android.content.DialogInterface;
  30. import android.content.Intent;
  31. import android.graphics.PorterDuff;
  32. import android.os.AsyncTask;
  33. import android.os.Bundle;
  34. import android.view.LayoutInflater;
  35. import android.view.View;
  36. import android.view.Window;
  37. import android.view.WindowManager.LayoutParams;
  38. import android.widget.EditText;
  39. import com.nextcloud.android.lib.resources.directediting.DirectEditingCreateFileRemoteOperation;
  40. import com.nextcloud.android.lib.resources.directediting.DirectEditingObtainListOfTemplatesRemoteOperation;
  41. import com.nextcloud.client.account.CurrentAccountProvider;
  42. import com.nextcloud.client.account.User;
  43. import com.nextcloud.client.di.Injectable;
  44. import com.nextcloud.client.network.ClientFactory;
  45. import com.owncloud.android.MainApp;
  46. import com.owncloud.android.R;
  47. import com.owncloud.android.datamodel.FileDataStorageManager;
  48. import com.owncloud.android.datamodel.OCFile;
  49. import com.owncloud.android.lib.common.Creator;
  50. import com.owncloud.android.lib.common.OwnCloudClient;
  51. import com.owncloud.android.lib.common.Template;
  52. import com.owncloud.android.lib.common.TemplateList;
  53. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  54. import com.owncloud.android.lib.common.utils.Log_OC;
  55. import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation;
  56. import com.owncloud.android.lib.resources.files.model.RemoteFile;
  57. import com.owncloud.android.ui.activity.ExternalSiteWebView;
  58. import com.owncloud.android.ui.activity.TextEditorWebView;
  59. import com.owncloud.android.ui.adapter.TemplateAdapter;
  60. import com.owncloud.android.utils.DisplayUtils;
  61. import com.owncloud.android.utils.FileStorageUtils;
  62. import com.owncloud.android.utils.ThemeUtils;
  63. import java.lang.ref.WeakReference;
  64. import javax.inject.Inject;
  65. import androidx.annotation.NonNull;
  66. import androidx.appcompat.app.AlertDialog;
  67. import androidx.fragment.app.DialogFragment;
  68. import androidx.recyclerview.widget.GridLayoutManager;
  69. import androidx.recyclerview.widget.RecyclerView;
  70. import butterknife.BindView;
  71. import butterknife.ButterKnife;
  72. /**
  73. * Dialog to show templates for new documents/spreadsheets/presentations.
  74. */
  75. public class ChooseTemplateDialogFragment extends DialogFragment implements DialogInterface.OnClickListener,
  76. TemplateAdapter.ClickListener, Injectable {
  77. private static final String ARG_PARENT_FOLDER = "PARENT_FOLDER";
  78. private static final String ARG_CREATOR = "CREATOR";
  79. private static final String TAG = ChooseTemplateDialogFragment.class.getSimpleName();
  80. private static final String DOT = ".";
  81. private TemplateAdapter adapter;
  82. private OCFile parentFolder;
  83. @Inject ClientFactory clientFactory;
  84. private Creator creator;
  85. @Inject CurrentAccountProvider currentAccount;
  86. public enum Type {
  87. DOCUMENT,
  88. SPREADSHEET,
  89. PRESENTATION
  90. }
  91. @BindView(R.id.list)
  92. RecyclerView listView;
  93. @BindView(R.id.filename)
  94. EditText fileName;
  95. public static ChooseTemplateDialogFragment newInstance(OCFile parentFolder, Creator creator) {
  96. ChooseTemplateDialogFragment frag = new ChooseTemplateDialogFragment();
  97. Bundle args = new Bundle();
  98. args.putParcelable(ARG_PARENT_FOLDER, parentFolder);
  99. args.putParcelable(ARG_CREATOR, creator);
  100. frag.setArguments(args);
  101. return frag;
  102. }
  103. @Override
  104. public void onStart() {
  105. super.onStart();
  106. int color = ThemeUtils.primaryAccentColor(getContext());
  107. AlertDialog alertDialog = (AlertDialog) getDialog();
  108. alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(color);
  109. alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(color);
  110. }
  111. @NonNull
  112. @Override
  113. public Dialog onCreateDialog(Bundle savedInstanceState) {
  114. Bundle arguments = getArguments();
  115. if (arguments == null) {
  116. throw new IllegalArgumentException("Arguments may not be null");
  117. }
  118. Activity activity = getActivity();
  119. if (activity == null) {
  120. throw new IllegalArgumentException("Activity may not be null");
  121. }
  122. int accentColor = ThemeUtils.primaryAccentColor(getContext());
  123. parentFolder = arguments.getParcelable(ARG_PARENT_FOLDER);
  124. creator = arguments.getParcelable(ARG_CREATOR);
  125. // Inflate the layout for the dialog
  126. LayoutInflater inflater = activity.getLayoutInflater();
  127. @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.choose_template, null);
  128. ButterKnife.bind(this, view);
  129. fileName.requestFocus();
  130. fileName.getBackground().setColorFilter(accentColor, PorterDuff.Mode.SRC_ATOP);
  131. try {
  132. User user = currentAccount.getUser();
  133. new FetchTemplateTask(this, clientFactory, user, creator).execute();
  134. } catch (Exception e) {
  135. Log_OC.e(TAG, "Loading stream url not possible: " + e);
  136. }
  137. listView.setHasFixedSize(true);
  138. listView.setLayoutManager(new GridLayoutManager(activity, 2));
  139. adapter = new TemplateAdapter(creator.getMimetype(), this, getContext(), currentAccount, clientFactory);
  140. listView.setAdapter(adapter);
  141. // Build the dialog
  142. AlertDialog.Builder builder = new AlertDialog.Builder(activity);
  143. builder.setView(view)
  144. .setNegativeButton(R.string.common_cancel, this)
  145. .setTitle(ThemeUtils.getColoredTitle(getResources().getString(R.string.select_template), accentColor));
  146. Dialog dialog = builder.create();
  147. Window window = dialog.getWindow();
  148. if (window != null) {
  149. window.setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
  150. }
  151. return dialog;
  152. }
  153. private void createFromTemplate(Template template, String path) {
  154. new CreateFileFromTemplateTask(this, clientFactory, currentAccount.getUser(), template, path, creator).execute();
  155. }
  156. public void setTemplateList(TemplateList templateList) {
  157. adapter.setTemplateList(templateList);
  158. adapter.notifyDataSetChanged();
  159. }
  160. @Override
  161. public void onClick(Template template) {
  162. String name = fileName.getText().toString();
  163. String path = parentFolder.getRemotePath() + name;
  164. if (name.isEmpty() || name.equalsIgnoreCase(DOT + template.getExtension())) {
  165. DisplayUtils.showSnackMessage(listView, R.string.enter_filename);
  166. } else if (!name.endsWith(template.getExtension())) {
  167. createFromTemplate(template, path + DOT + template.getExtension());
  168. } else {
  169. createFromTemplate(template, path);
  170. }
  171. }
  172. @Override
  173. public void onClick(DialogInterface dialog, int which) {
  174. // cancel is handled by dialog itself, no other button available
  175. }
  176. private static class CreateFileFromTemplateTask extends AsyncTask<Void, Void, String> {
  177. private ClientFactory clientFactory;
  178. private WeakReference<ChooseTemplateDialogFragment> chooseTemplateDialogFragmentWeakReference;
  179. private Template template;
  180. private String path;
  181. private Creator creator;
  182. private User user;
  183. private OCFile file;
  184. CreateFileFromTemplateTask(ChooseTemplateDialogFragment chooseTemplateDialogFragment,
  185. ClientFactory clientFactory,
  186. User user,
  187. Template template,
  188. String path,
  189. Creator creator
  190. ) {
  191. this.clientFactory = clientFactory;
  192. this.chooseTemplateDialogFragmentWeakReference = new WeakReference<>(chooseTemplateDialogFragment);
  193. this.template = template;
  194. this.path = path;
  195. this.creator = creator;
  196. this.user = user;
  197. }
  198. @Override
  199. protected String doInBackground(Void... voids) {
  200. try {
  201. OwnCloudClient client = clientFactory.create(user);
  202. RemoteOperationResult result =
  203. new DirectEditingCreateFileRemoteOperation(path,
  204. creator.getEditor(),
  205. creator.getId(),
  206. template.getTitle()).execute(client);
  207. if (!result.isSuccess()) {
  208. return "";
  209. }
  210. RemoteOperationResult newFileResult = new ReadFileRemoteOperation(path).execute(client);
  211. if (!newFileResult.isSuccess()) {
  212. return "";
  213. }
  214. OCFile temp = FileStorageUtils.fillOCFile((RemoteFile) newFileResult.getData().get(0));
  215. final ChooseTemplateDialogFragment fragment = chooseTemplateDialogFragmentWeakReference.get();
  216. if (fragment == null) {
  217. return "";
  218. }
  219. final Context context = fragment.getContext();
  220. if (context == null) {
  221. // fragment has been detached
  222. return "";
  223. }
  224. FileDataStorageManager storageManager = new FileDataStorageManager(user.toPlatformAccount(),
  225. context.getContentResolver());
  226. storageManager.saveFile(temp);
  227. file = storageManager.getFileByPath(path);
  228. return result.getData().get(0).toString();
  229. } catch (ClientFactory.CreationException e) {
  230. Log_OC.e(TAG, "Error creating file from template!", e);
  231. return "";
  232. }
  233. }
  234. @Override
  235. protected void onPostExecute(String url) {
  236. final ChooseTemplateDialogFragment fragment = chooseTemplateDialogFragmentWeakReference.get();
  237. if (fragment != null && fragment.isAdded()) {
  238. if (url.isEmpty()) {
  239. DisplayUtils.showSnackMessage(fragment.listView, "Error creating file from template");
  240. } else {
  241. Intent editorWebView = new Intent(MainApp.getAppContext(), TextEditorWebView.class);
  242. editorWebView.putExtra(ExternalSiteWebView.EXTRA_TITLE, "Text");
  243. editorWebView.putExtra(ExternalSiteWebView.EXTRA_URL, url);
  244. editorWebView.putExtra(ExternalSiteWebView.EXTRA_FILE, file);
  245. editorWebView.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, false);
  246. fragment.startActivity(editorWebView);
  247. fragment.dismiss();
  248. }
  249. } else {
  250. Log_OC.e(TAG, "Error creating file from template!");
  251. }
  252. }
  253. }
  254. private static class FetchTemplateTask extends AsyncTask<Void, Void, TemplateList> {
  255. private User user;
  256. private ClientFactory clientFactory;
  257. private WeakReference<ChooseTemplateDialogFragment> chooseTemplateDialogFragmentWeakReference;
  258. private Creator creator;
  259. FetchTemplateTask(ChooseTemplateDialogFragment chooseTemplateDialogFragment,
  260. ClientFactory clientFactory,
  261. User user,
  262. Creator creator) {
  263. this.user = user;
  264. this.clientFactory = clientFactory;
  265. this.chooseTemplateDialogFragmentWeakReference = new WeakReference<>(chooseTemplateDialogFragment);
  266. this.creator = creator;
  267. }
  268. @Override
  269. protected TemplateList doInBackground(Void... voids) {
  270. try {
  271. OwnCloudClient client = clientFactory.create(user);
  272. RemoteOperationResult result = new DirectEditingObtainListOfTemplatesRemoteOperation(creator.getEditor(),
  273. creator.getId())
  274. .execute(client);
  275. if (!result.isSuccess()) {
  276. return new TemplateList();
  277. }
  278. return (TemplateList) result.getSingleData();
  279. } catch (ClientFactory.CreationException e) {
  280. Log_OC.e(TAG, "Could not fetch template", e);
  281. return new TemplateList();
  282. }
  283. }
  284. @Override
  285. protected void onPostExecute(TemplateList templateList) {
  286. ChooseTemplateDialogFragment fragment = chooseTemplateDialogFragmentWeakReference.get();
  287. if (fragment != null && fragment.isAdded()) {
  288. if (templateList.templates.isEmpty()) {
  289. DisplayUtils.showSnackMessage(fragment.listView, R.string.error_retrieving_templates);
  290. } else {
  291. fragment.setTemplateList(templateList);
  292. String name = DOT + templateList.templates.values().iterator().next().getExtension();
  293. fragment.fileName.setText(name);
  294. }
  295. } else {
  296. Log_OC.e(TAG, "Error streaming file: no previewMediaFragment!");
  297. }
  298. }
  299. }
  300. }