cleanup, moved to net.wpitchoune package
[pnews.git] / war / src / main / java / net / wpitchoune / pnews / servlet / ArticleProvider.java
1 package net.wpitchoune.pnews.servlet;
2
3 import java.io.IOException;
4 import java.net.MalformedURLException;
5 import java.net.URL;
6 import java.time.Instant;
7 import java.time.temporal.ChronoUnit;
8 import java.util.ArrayList;
9 import java.util.Collections;
10 import java.util.Comparator;
11 import java.util.Date;
12 import java.util.HashMap;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.concurrent.Executors;
16 import java.util.concurrent.ScheduledExecutorService;
17 import java.util.concurrent.TimeUnit;
18 import java.util.logging.Level;
19 import java.util.logging.Logger;
20
21 import org.jsoup.Jsoup;
22
23 import com.rometools.rome.feed.synd.SyndEnclosure;
24 import com.rometools.rome.feed.synd.SyndEntry;
25 import com.rometools.rome.feed.synd.SyndFeed;
26 import com.rometools.rome.io.FeedException;
27 import com.rometools.rome.io.SyndFeedInput;
28 import com.rometools.rome.io.XmlReader;
29
30 import net.wpitchoune.pnews.Article;
31 import net.wpitchoune.pnews.ArticleStore;
32 import net.wpitchoune.pnews.Category;
33 import net.wpitchoune.pnews.Config;
34 import net.wpitchoune.pnews.EntityStat;
35 import net.wpitchoune.pnews.Feed;
36 import net.wpitchoune.pnews.classifier.NamedEntityRecognizer;
37
38 public class ArticleProvider {
39         private static final String CLASS_NAME = ArticleProvider.class.getName();
40         private static final Logger LOG = Logger.getLogger(CLASS_NAME);
41         private final Map<Category, List<Article>> articlesByCategory = new HashMap<>();
42         private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
43         private final Config config;
44         
45         public ArticleProvider(Config config) {
46                 this.config = config;
47                 for (Category cat: config.getCategories())
48                         scheduler.scheduleAtFixedRate(new Refresher(cat), 2, 600, TimeUnit.SECONDS);
49         }
50         
51         private static SyndFeed getSyndFeed(String u) throws IllegalArgumentException, FeedException, MalformedURLException, IOException {
52                 XmlReader r;
53                 
54                 r = new XmlReader(new URL(u));
55                 
56                 return new SyndFeedInput().build(r);                
57         }
58         
59         private List<Article> getArticlesForUpdate(Category cat) {
60                 List<Article> result;
61                 
62                 synchronized (articlesByCategory) {
63                         result = articlesByCategory.get(cat);
64                         if (result == null) {
65                                 result = new ArrayList<>();
66                                 articlesByCategory.put(cat, result);
67                         }
68                         return result;
69                 }                
70         }
71         
72         private boolean exists(String articleLink, List<Article> articles) {
73                 synchronized (articles) {
74                         for (Article a: articles)
75                                 if (a.getLink().equals(articleLink))
76                                         return true;
77                 }
78                 return false;
79         }
80         
81         private Instant getArticleInstant(SyndEntry entry) {
82                 Date date;
83                 
84                 date = entry.getUpdatedDate();       
85                 if (date == null)
86                         date = entry.getPublishedDate();
87
88                 if (date == null)
89                         return Instant.now();
90                 
91                 return date.toInstant();
92         }
93         
94         private Article toArticle(String link, SyndEntry entry, SyndFeed feed, String lang, Instant instant) {
95                 String desc, title, thumbnail, feedTitle, str;
96                 List<String> entities;
97                 
98                 feedTitle = feed.getTitle();
99                 if (feedTitle != null) {
100                         feedTitle = feedTitle.trim();
101                 }
102                 
103                 thumbnail = null;
104                 for (SyndEnclosure e: entry.getEnclosures()) {
105                         if (e.getType().startsWith("image/"))
106                                 thumbnail = e.getUrl();    
107                         break;
108                 }
109                                 
110                 title = entry.getTitle().trim();
111                 
112                 if (entry.getDescription() != null) {
113                         str = entry.getDescription().getValue();
114                         desc = Jsoup.parse(str).text();
115                 } else {       
116                         desc = null;
117                         LOG.severe("No description for " + feedTitle + " - " + title);
118                 }
119                                 
120                 entities = new ArrayList<>();
121                 if (lang.equals("en"))
122                         try {
123                                 NamedEntityRecognizer.classify(title, entities, config);
124                                 if (desc != null)
125                                         NamedEntityRecognizer.classify(desc, entities, config);
126                         } catch (ClassCastException | ClassNotFoundException | IOException e1) {
127                                 LOG.log(Level.SEVERE, "Cannot classify " + feedTitle, e1);                         
128                         }
129                 
130                 return new Article(link, title, desc, thumbnail, instant, feedTitle, entities.toArray(new String[0]));
131         }
132         
133         private void addArticles(Category cat, SyndFeed feed) {
134                 String feedTitle;
135                 List<Article> articles;
136                 Article a;
137                 
138                 feedTitle = feed.getTitle().trim();
139                 
140                 LOG.info("addArticles " + cat.getLabel() + " " + feedTitle + " number of articles: " + feed.getEntries().size());
141                 
142                 for (SyndEntry entry: feed.getEntries()) {
143                         String link = entry.getLink().trim();
144                         articles = getArticlesForUpdate(cat);
145                         if (exists(link, articles)) {
146                                 LOG.fine("addArticles " + link + " is already present");
147                                 continue ;
148                         }
149                         
150                         final Instant instant = getArticleInstant(entry);
151                         
152                         if (config.isObsolete(instant))
153                                 continue ;
154                         
155                         a = ArticleStore.singleton.getArticle(link, ()->toArticle(link, entry, feed, cat.getLanguage(), instant));
156                         
157                         synchronized (articles) {
158                                 articles.add(a);
159
160                                 Collections.sort(articles, new Comparator<Article>() {
161                                         @Override
162                                         public int compare(Article o1, Article o2) {
163                                                 if (o1.getPublicationDate() == o2.getPublicationDate())
164                                                         return 0;
165                                                 if (o1.getPublicationDate() == null)
166                                                         return 1;
167                                                 if (o2.getPublicationDate() == null)
168                                                         return -1;
169                                                 return o2.getPublicationDate().compareTo(o1.getPublicationDate());
170                                         }
171                                 });
172                         }
173                 }          
174                 
175                 LOG.info("addArticles done " + cat.getLabel());
176         }
177              
178         private void retrieveArticles(Category cat) throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
179                 List<Feed> feeds;
180                 
181                 feeds = config.getFeedsByCategory().get(cat);
182                 
183                 if (feeds != null)
184                         for (Feed f: feeds)
185                                 try {
186                                         addArticles(cat, getSyndFeed(f.getURL()));
187                                 } catch (Throwable e) {
188                                         LOG.log(Level.SEVERE,
189                                                 "retrieveArticles failure " + cat.getLabel() + " " + f.toString(),
190                                                 e);
191                                 }
192                 else
193                         LOG.severe("No feed for category " + cat);
194         }
195         
196         /**
197          * Returns a copy.
198          */
199         public List<Article> getArticles(Category cat, String entity)
200                         throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
201                 List<Article> articles, result;                
202                 
203                 synchronized (articlesByCategory) {
204                         articles = getArticlesForUpdate(cat);
205                 }
206                 
207                 synchronized (articles) {                       
208                         if (entity == null)
209                                 return new ArrayList<>(articles);
210                         
211                         result = new ArrayList<>(articles.size());
212                         for (Article a: articles)
213                                 if (a.hasEntity(entity))
214                                         result.add(a);
215                         
216                         return result;
217                 }
218         }
219         
220         public List<EntityStat> getEntityStats(Category cat) throws IllegalArgumentException, MalformedURLException, FeedException, IOException {
221                 List<Article> articles;
222                 Map<String, EntityStat> entities;
223                 final String FUNCTION_NAME = "getEntities";
224                 EntityStat s;
225                 List<EntityStat> stats;
226                 Instant minInstant;
227                 
228                 LOG.entering(CLASS_NAME, FUNCTION_NAME, cat);
229                 
230                 articles = getArticles(cat, null);
231                 
232                 minInstant = Instant.now().minus(15, ChronoUnit.DAYS);
233                 
234                 entities = new HashMap<>();
235                 for (Article a: articles)
236                         if (a.getPublicationDate().isAfter(minInstant) && a.getEntities() != null)
237                                 for (String e: a.getEntities()) {
238                                         s = entities.get(e);
239                                         if (s == null) {
240                                                 s = new EntityStat(e);
241                                                 entities.put(e,  s);
242                                         }
243                                         s.increment();
244                                 }                
245                
246                 stats = new ArrayList<>(entities.values());
247                 stats.sort(new Comparator<EntityStat>() {
248
249                         @Override
250                         public int compare(EntityStat o1, EntityStat o2) {
251                                 return Integer.compare(o2.getCount(), o1.getCount());
252                         }
253                         
254                 });
255                 
256                 LOG.exiting(CLASS_NAME, FUNCTION_NAME, stats);
257                 
258                 return stats;
259         }
260         
261         private class Refresher implements Runnable {
262                 private final Category category;
263                 
264                 public Refresher(Category category) {
265                         this.category = category;
266                 }
267                 
268                 @Override
269                 public void run() {                       
270                         LOG.info("refresher "+ category.getLabel());
271                         
272                         try {
273                                 retrieveArticles(category);
274                         } catch (IllegalArgumentException | FeedException | IOException e) {
275                                 LOG.log(Level.SEVERE, "refresher failure", e);
276                         }                        
277                         
278                         LOG.info("refresher "+ category.getLabel() + " done");
279                 }                
280         }
281 }