Added README.txt and GPL Header to Source Files
[DHBWCampusApp.git] / app / src / main / java / de / dhbwloe / campusapp / news / NewsManager.java
1 /* NewsManager.java
2  *
3  * This program is free software: you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation, either version 3 of the License, or
6  * (at your option) any later version.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program. If not, see <http://www.gnu.org/licenses/>.
15  */
16 package de.dhbwloe.campusapp.news;
17 import android.util.Base64;
18 import android.util.Log;
19
20 import java.io.UnsupportedEncodingException;
21 import java.net.URLEncoder;
22 import java.text.DateFormat;
23 import java.text.ParseException;
24 import java.text.SimpleDateFormat;
25 import java.util.ArrayList;
26 import java.util.Date;
27 import java.util.List;
28 import java.util.Locale;
29
30 import de.dhbwloe.campusapp.CampusAppContext;
31 import de.dhbwloe.campusapp.mensaplan.MensaplanManagerInterface;
32 import de.dhbwloe.campusapp.network.XmlEntry;
33 import de.dhbwloe.campusapp.network.XmlRequestHelper;
34 import de.dhbwloe.campusapp.search.SearchIndices;
35
36 /**
37  * Created by pk910 on 22.01.2016.
38  */
39 public class NewsManager extends XmlRequestHelper {
40     private static final String[][] NEWS_SOURCES = {
41         {"DHBW", "http://www.dhbw-loerrach.de/index.php?id=59&type=100"},
42         {"STUV", "http://stuv-loerrach.de/feed"},
43     };
44
45
46     private CampusAppContext AppContext;
47     private boolean bRequestRunning = false;
48     private ArrayList<NewsManagerInterface> aCallbackInterfaces = new ArrayList<NewsManagerInterface>();
49     private String[] source;
50
51     public NewsManager(CampusAppContext context, String source) {
52         AppContext = context;
53
54         for(String[] src : NEWS_SOURCES) {
55             if(src[0].equalsIgnoreCase(source)) {
56                 this.source = src;
57             }
58         }
59     }
60
61     public void performSynchronisation(NewsManagerInterface callback) {
62         aCallbackInterfaces.add(callback);
63         if(bRequestRunning || this.source == null)
64             return;
65
66         bRequestRunning = true;
67         requestXmlFromWeb(this.source[1], "channel", "item");
68     }
69
70     private long getTimeFromDateString(String timestamp) {
71         // Thu, 08 Oct 2015 08:00:34 +0000
72         if(timestamp == null)
73             return 0;
74         DateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
75         try {
76             Date result =  df.parse(timestamp);
77             return result.getTime()/1000;
78         } catch (ParseException e) {
79             return 0;
80         }
81     }
82
83     @Override
84     protected void onXmlReceived(List<XmlEntry> entries) {
85         ArrayList<SearchIndices> newIndices = new ArrayList<SearchIndices>();
86
87         Log.i("NMSync", "Received News XML");
88         for(XmlEntry entry : entries) {
89             Log.i("NMSync", "Parse News");
90             XmlEntry centry;
91
92             centry = XmlEntry.FindXmlEntryByName(entry, "pubDate");
93             long time = (centry == null ? 0 : getTimeFromDateString(centry.getValue()));
94             if(time == 0)
95                 continue;
96
97             centry = XmlEntry.FindXmlEntryByName(entry, "link");
98             String link = (centry == null ? null : centry.getValue());
99             centry = XmlEntry.FindXmlEntryByName(entry, "uuid");
100             String uuid = (centry == null ? null : centry.getValue());
101
102             String uniqueid;
103             if(uuid == null) {
104                 if(link == null)
105                     continue;
106                 byte[] data = new byte[0];
107                 try {
108                     data = link.getBytes("UTF-8");
109                 } catch (UnsupportedEncodingException e) {
110                     continue;
111                 }
112                 uniqueid = Base64.encodeToString(data, Base64.DEFAULT);
113             } else {
114                 byte[] data = new byte[0];
115                 try {
116                     data = uuid.getBytes("UTF-8");
117                 } catch (UnsupportedEncodingException e) {
118                     continue;
119                 }
120                 uniqueid = Base64.encodeToString(data, Base64.DEFAULT);
121             }
122
123             centry = XmlEntry.FindXmlEntryByName(entry, "title");
124             String title = (centry == null ? null : centry.getValue());
125
126             centry = XmlEntry.FindXmlEntryByName(entry, "description");
127             String summary = (centry == null ? null : centry.getValue());
128
129             centry = XmlEntry.FindXmlEntryByName(entry, "content");
130             String content = (centry == null ? null : centry.getValue());
131
132             centry = XmlEntry.FindXmlEntryByName(entry, "creator");
133             String creator = (centry == null ? null : centry.getValue());
134             if(creator != null) {
135                 if(content != null)
136                     content = creator + ": " + content;
137                 else
138                     content = creator;
139             }
140
141             StringBuilder categories = new StringBuilder();
142             XmlEntry[] centries = XmlEntry.FindXmlEntriesByName(entry, "category");
143             for(XmlEntry centry2 : centries) {
144                 if(categories.length() > 0)
145                     categories.append(",");
146                 categories.append(centry2.getValue());
147             }
148
149             NewsItem newsitem = new NewsItem(0, source[0], time, uniqueid, 0, title, summary, content, link, categories.toString());
150             newsitem.calculateChkSum();
151
152             AppContext.getDatabaseManager().updateNewsItem(newsitem);
153             if(newsitem.getIsNew(true)) {
154                 SearchIndices indices = new SearchIndices("NewsItem#"+newsitem.getId(), false);
155                 indices.setTarget("#News#shownews=" + newsitem.getId());
156                 indices.setTitle(newsitem.getSource() + " News (" + newsitem.getFormatedDate() + ")");
157                 indices.setDescription(newsitem.getTitle() + ": " + newsitem.getSummary());
158                 indices.setUpdateTime(newsitem.getTime());
159                 indices.addKeyWord(newsitem.getTitle());
160                 indices.addKeyWord(newsitem.getSummary());
161                 indices.addKeyWord(newsitem.getContent());
162                 newIndices.add(indices);
163             }
164         }
165
166         SearchIndices[] newIndicesArr = new SearchIndices[newIndices.size()];
167         newIndicesArr = newIndices.toArray(newIndicesArr);
168         AppContext.addSearchIndices(newIndicesArr);
169
170         for(NewsManagerInterface callback : aCallbackInterfaces) {
171             callback.onNewsUpdateDone();
172         }
173         aCallbackInterfaces.clear();
174         bRequestRunning = false;
175     }
176
177     @Override
178     protected void onXmlRequestFail(int statusCode, String errorMessage) {
179         for(NewsManagerInterface callback : aCallbackInterfaces) {
180             callback.onNewsUpdateFail("error " + statusCode + ": " + errorMessage);
181         }
182         aCallbackInterfaces.clear();
183         bRequestRunning = false;
184     }
185 }