summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/backup/OpmlBackupAgent.java
blob: 56d1ca092fc0f24642c2b37fa4d94af394956f25 (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
201
202
203
204
205
206
207
208
209
210
211
212
package de.danoeh.antennapod.backup;

import android.app.backup.BackupAgentHelper;
import android.app.backup.BackupDataInputStream;
import android.app.backup.BackupDataOutput;
import android.app.backup.BackupHelper;
import android.content.Context;
import android.os.ParcelFileDescriptor;
import android.util.Log;

import de.danoeh.antennapod.BuildConfig;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.math.BigInteger;
import java.security.DigestInputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.feed.Feed;
import de.danoeh.antennapod.opml.OpmlElement;
import de.danoeh.antennapod.opml.OpmlReader;
import de.danoeh.antennapod.opml.OpmlWriter;
import de.danoeh.antennapod.storage.DBReader;
import de.danoeh.antennapod.storage.DownloadRequestException;
import de.danoeh.antennapod.storage.DownloadRequester;
import de.danoeh.antennapod.util.LangUtils;

public class OpmlBackupAgent extends BackupAgentHelper {
    private static final String OPML_BACKUP_KEY = "opml";

    @Override
    public void onCreate() {
        addHelper(OPML_BACKUP_KEY, new OpmlBackupHelper(this));
    }

    private static final void LOGD(String tag, String msg) {
        if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.DEBUG)) {
            Log.d(tag, msg);
        }
    }

    private static final void LOGD(String tag, String msg, Throwable tr) {
        if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.DEBUG)) {
            Log.d(tag, msg, tr);
        }
    }

    /** Class for backing up and restoring the OPML file. */
    private static class OpmlBackupHelper implements BackupHelper {
        private static final String TAG = "OpmlBackupHelper";

        private static final String OPML_ENTITY_KEY = "antennapod-feeds.opml";

        private final Context mContext;

        /** Checksum of restored OPML file */
        private byte[] mChecksum;

        public OpmlBackupHelper(Context context) {
            mContext = context;
        }

        @Override
        public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) {
            Log.d(TAG, "Performing backup");
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            MessageDigest digester = null;
            Writer writer;

            try {
                digester = MessageDigest.getInstance("MD5");
                writer = new OutputStreamWriter(new DigestOutputStream(byteStream, digester),
                        LangUtils.UTF_8);
            } catch (NoSuchAlgorithmException e) {
                writer = new OutputStreamWriter(byteStream, LangUtils.UTF_8);
            }

            try {
                // Write OPML
                new OpmlWriter().writeDocument(DBReader.getFeedList(mContext), writer);

                // Compare checksum of new and old file to see if we need to perform a backup at all
                if (digester != null) {
                    byte[] newChecksum = digester.digest();
                    LOGD(TAG, "New checksum: " + new BigInteger(1, newChecksum).toString(16));

                    // Get the old checksum
                    if (oldState != null) {
                        FileInputStream inState = new FileInputStream(oldState.getFileDescriptor());
                        int len = inState.read();

                        if (len != -1) {
                            byte[] oldChecksum = new byte[len];
                            inState.read(oldChecksum);
                            LOGD(TAG, "Old checksum: " + new BigInteger(1, oldChecksum).toString(16));

                            if (Arrays.equals(oldChecksum, newChecksum)) {
                                LOGD(TAG, "Checksums are the same; won't backup");
                                return;
                            }
                        }
                    }

                    writeNewStateDescription(newState, newChecksum);
                }

                LOGD(TAG, "Backing up OPML");
                byte[] bytes = byteStream.toByteArray();
                data.writeEntityHeader(OPML_ENTITY_KEY, bytes.length);
                data.writeEntityData(bytes, bytes.length);
            } catch (IOException e) {
                Log.e(TAG, "Error during backup", e);
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                    }
                }
            }
        }

        @Override
        public void restoreEntity(BackupDataInputStream data) {
            LOGD(TAG, "Backup restore");

            if (!OPML_ENTITY_KEY.equals(data.getKey())) {
                LOGD(TAG, "Unknown entity key: " + data.getKey());
                return;
            }

            MessageDigest digester = null;
            Reader reader;

            try {
                digester = MessageDigest.getInstance("MD5");
                reader = new InputStreamReader(new DigestInputStream(data, digester),
                        LangUtils.UTF_8);
            } catch (NoSuchAlgorithmException e) {
                reader = new InputStreamReader(data, LangUtils.UTF_8);
            }

            try {
                ArrayList<OpmlElement> opmlElements = new OpmlReader().readDocument(reader);
                mChecksum = digester == null ? null : digester.digest();
                DownloadRequester downloader = DownloadRequester.getInstance();
                Date lastUpdated = new Date();

                for (OpmlElement opmlElem : opmlElements) {
                    Feed feed = new Feed(opmlElem.getXmlUrl(), lastUpdated, opmlElem.getText());

                    try {
                        downloader.downloadFeed(mContext, feed);
                    } catch (DownloadRequestException e) {
                        LOGD(TAG, "Error while restoring/downloading feed", e);
                    }
                }
            } catch (XmlPullParserException e) {
                Log.e(TAG, "Error while parsing the OPML file", e);
            } catch (IOException e) {
                Log.e(TAG, "Failed to restore OPML backup", e);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                    }
                }
            }
        }

        @Override
        public void writeNewStateDescription(ParcelFileDescriptor newState) {
            writeNewStateDescription(newState, mChecksum);
        }

        /**
         * Writes the new state description, which is the checksum of the OPML file.
         *
         * @param newState
         * @param checksum
         */
        private void writeNewStateDescription(ParcelFileDescriptor newState, byte[] checksum) {
            if (checksum == null) {
                return;
            }

            try {
                FileOutputStream outState = new FileOutputStream(newState.getFileDescriptor());
                outState.write(checksum.length);
                outState.write(checksum);
                outState.flush();
                outState.close();
            } catch (IOException e) {
                Log.e(TAG, "Failed to write new state description", e);
            }
        }
    }
}