Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CertificateExportActivity.java « preference « mumla « lublin « se « java « main « src « app - gitlab.com/quite/mumla.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 5446e79b95055cc8d896fb19ccd07296e235df83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/*
 * Copyright (C) 2016 Andrew Comminos <andrew@comminos.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package se.lublin.mumla.preference;

import static android.os.Build.VERSION.SDK_INT;

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts.CreateDocument;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.documentfile.provider.DocumentFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import se.lublin.mumla.Constants;
import se.lublin.mumla.R;
import se.lublin.mumla.db.DatabaseCertificate;
import se.lublin.mumla.db.MumlaDatabase;
import se.lublin.mumla.db.MumlaSQLiteDatabase;

/**
 * Created by andrew on 12/01/16.
 */
public class CertificateExportActivity extends AppCompatActivity implements DialogInterface.OnClickListener {
    /**
     * The name of the directory to export to on external storage.
     */
    private static final String EXTERNAL_STORAGE_DIR = "Mumla";

    private MumlaDatabase mDatabase;
    private List<DatabaseCertificate> mCertificates;

    private final ActivityResultLauncher<String> documentCreator =
            registerForActivityResult(new CreateDocument(), this::onDocumentCreated);
    private static final int PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 2;
    private DatabaseCertificate mCertificatePending = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDatabase = new MumlaSQLiteDatabase(this);
        mCertificates = mDatabase.getCertificates();

        CharSequence[] labels = new CharSequence[mCertificates.size()];
        for (int i = 0; i < labels.length; i++) {
            labels[i] = mCertificates.get(i).getName();
        }

        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        adb.setTitle(R.string.pref_export_certificate_title);
        adb.setItems(labels, this);
        adb.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        adb.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDatabase.close();
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        DatabaseCertificate certificate = mCertificates.get(which);
        if (SDK_INT >= Build.VERSION_CODES.R) {
            // TODO Should always use this method?
            mCertificatePending = certificate;
            documentCreator.launch(certificate.getName());
        } else {
            saveCertificateClassic(certificate);
        }
    }

    private void onDocumentCreated(Uri uri) {
        if (uri != null && mCertificatePending != null) {
            try {
                OutputStream os = getContentResolver().openOutputStream(uri);
                DocumentFile df = DocumentFile.fromSingleUri(this, uri);
                writeCertificate(os, mCertificatePending, df != null ? df.getName() : "<unknown>");
            } catch (FileNotFoundException e) {
                showErrorDialog(R.string.externalStorageUnavailable);
                Log.w(Constants.TAG, "FileNotFound on output file picked by user?!");
            }
        } else if (mCertificatePending == null) {
            Log.w(Constants.TAG, "No pending certificate after user picked output file");
        }
        finish();
    }

    private void saveCertificateClassic(DatabaseCertificate certificate) {
        if (ContextCompat.checkSelfPermission(CertificateExportActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(CertificateExportActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
            mCertificatePending = certificate;
            return;
        }

        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            showErrorDialog(R.string.externalStorageUnavailable);
            return;
        }
        File storageDirectory = Environment.getExternalStorageDirectory();
        File mumlaDirectory = new File(storageDirectory, EXTERNAL_STORAGE_DIR);
        if (!mumlaDirectory.exists() && !mumlaDirectory.mkdir()) {
            showErrorDialog(R.string.externalStorageUnavailable);
            return;
        }
        File outputFile = new File(mumlaDirectory, certificate.getName());
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(outputFile);
        } catch (FileNotFoundException e) {
            showErrorDialog(R.string.externalStorageUnavailable);
            return;
        }
        writeCertificate(fos, certificate, outputFile.getAbsolutePath());
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (mCertificatePending != null) {
                    saveCertificateClassic(mCertificatePending);
                } else {
                    Log.w(Constants.TAG, "No pending certificate after permission was granted");
                }
            } else {
                Toast.makeText(CertificateExportActivity.this, getString(R.string.grant_perm_storage),
                        Toast.LENGTH_LONG).show();
            }
            mCertificatePending = null;
        }
    }

    private void writeCertificate(OutputStream fos, DatabaseCertificate cert, String path) {
        byte[] data = mDatabase.getCertificateData(cert.getId());
        try {
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(data);
            bos.close();
            Toast.makeText(this, getString(R.string.export_success, path), Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
            showErrorDialog(R.string.error_writing_to_storage);
        }
    }

    private void showErrorDialog(int resourceId) {
        AlertDialog.Builder errorDialog = new AlertDialog.Builder(this);
        errorDialog.setMessage(resourceId);
        errorDialog.setPositiveButton(android.R.string.ok, null);
        errorDialog.show();
    }
}