-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
211 lines (206 loc) · 8.98 KB
/
Program.cs
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
using CommandLine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
namespace ReutersTopNews
{
class Program
{
public class Settings{
static public string topNewsUrl = "https://www.reuters.com/news/archive/newsOne";
static public string worldNewsUrl = "https://www.reuters.com/world";
static public string financeNewsUrl = "https://www.reuters.com/finance";
static public string breakingViewsUrl = "https://www.reuters.com/breakingviews";
static public string techNewsUrl = "https://www.reuters.com/technology";
static public string lifeUrl = "https://www.reuters.com/lifestyle";
static public string dataFolder = Environment.ExpandEnvironmentVariables("%TMP%/reuters/");
static public string dataPath = dataFolder + "/data";
}
// General
static List<string> getContentList(List<string> articles, Func<string,string> contentFunc){
List<string> listOfAttribute = new List<string>();
foreach(string article in articles){
listOfAttribute.Add(contentFunc(article));
}
return listOfAttribute;
}
static string getFirstContent(string source,Regex rx,string name){
MatchCollection matches = rx.Matches(source);
GroupCollection groups = matches[0].Groups;
return groups[name].Value;
}
static List<string> splitFileBy(string source,Regex rx){
List<string> contentList = new List<string>();
MatchCollection matches = rx.Matches(source);
foreach(Match match in matches){
contentList.Add(match.Value);
}
return contentList;
}
static string getHtmlStr(string URL){
WebClient web = new WebClient();
string htmlStr = web.DownloadString(URL);
return htmlStr;
}
static bool existData(){
if(!File.Exists(Settings.dataPath)){
return false;
}else{
return true;
}
}
static bool needUpdate(){
FileInfo fi = new FileInfo(Settings.dataPath);
var writeTime = fi.LastWriteTime;
var time = System.DateTime.Now;
var diffHours = (time - writeTime).TotalHours;
if(diffHours > 1){
return true;
}else{
return false;
}
}
static string wrapLine(string str,int length){
string res = str;
for(int i = length ; i < str.Length ; i+=length){
if(res[i-1] == ' ' || res[i] == ' '){
res = res.Insert(i,"\n");
}else{
res = res.Insert(i,"-\n");
}
}
return res;
}
static int newFolderIfNotExist(){
if(!Directory.Exists(Settings.dataFolder)){
Directory.CreateDirectory(Settings.dataFolder);
}
return 0;
}
// Article list
static List<string> getArticleList(string htmlStr){
Regex rx = new Regex(@"<article+.*?>(?<content>.*?)</article>", RegexOptions.Singleline);
return splitFileBy(htmlStr,rx);
}
static string getArticleUrl(string article){
Regex rx = new Regex(@"<a href=""(?<url>.*?)"">",RegexOptions.Singleline);
return getFirstContent(article,rx,"url");
}
static string getArticleTitle(string article){
Regex rx = new Regex(@"<h\d\sclass=.*?title.>\s*(?<title>.*?)</h.>",RegexOptions.Singleline);
return getFirstContent(article,rx,"title");
}
// Content page
static List<string> getParagraphList(string htmlStr){
Regex rx = new Regex(@"<p class=.Paragraph-paragraph+.*?>(?<content>.*?)</p>",RegexOptions.Singleline);
return splitFileBy(htmlStr,rx);
}
static string getParagraphContent(string paragraphHTML){
Regex rx = new Regex(@"<p class=.Paragraph-paragraph.*?>(?<content>.*?)</p>",RegexOptions.Singleline);
return getFirstContent(paragraphHTML,rx,"content");
}
static List<string> getFullArticle(string articleUrl){
articleUrl = "https://www.reuters.com" + articleUrl;
List<string> paragraphs = getParagraphList(getHtmlStr(articleUrl));
List<string> contents = getContentList(paragraphs,getParagraphContent);
return contents;
}
// Operation
static void print(List<string> target,bool showNumber = false,int wrap = -1){
int cnt = 0;
Action<string> printWithNumber = x => {
Console.WriteLine("[{0}] {1}",cnt,x);
cnt += 1;
};
Action<string> printWrap = x => Console.WriteLine(wrapLine(x,wrap));
Action<string> printRaw = x => Console.WriteLine(x);
switch ((showNumber,wrap)){
case (true,-1):
target.ForEach(printWithNumber);
break;
case (false,> 0):
target.ForEach(printWrap);
break;
default:
target.ForEach(printRaw);
break;
}
}
static (List<string>,List<string>,List<string>) load(string url,bool refresh = false,string source = "world"){
List<string> articles;
string rawContent;
if(existData()){
string[] lines = File.ReadAllLines(Settings.dataPath);
string lastLine = lines[^1];
if(lastLine != source){
refresh = true;
}
}
if(!refresh && existData() && !needUpdate()){
rawContent = System.IO.File.ReadAllText(Settings.dataPath);
} else{
rawContent = getHtmlStr(url);
System.IO.File.WriteAllText(Settings.dataPath,rawContent);
System.IO.File.AppendAllText(Settings.dataPath,source);
}
articles = getArticleList(rawContent);
List<string> titles = getContentList(articles,getArticleTitle);
List<string> urls = getContentList(articles,getArticleUrl);
return (articles,titles,urls);
}
public class Options
{
[Option('l',"list",Default=true,Required =false,HelpText ="List top news.")]
public bool isList { get; set; }
[Option('p',"page",Default="-1",Required =false,HelpText ="Load page n.")]
public string getPage { get; set; }
[Option('g',"goto",Default="-1",Required =false,HelpText ="Open specific article.")]
public string getNumber { get; set; }
[Option('w',"wrap",Default="100",Required =false,HelpText ="Set length of a single line. Set to 0 to output without wrapping.")]
public string getWrap { get; set; }
[Option('r',"refresh",Default=false,Required = false, HelpText = "Refresh list of article.")]
public bool isRefresh { get; set; }
[Option('s',"source",Default="world",Required = false, HelpText = "Choose news source from [top | world | tech | finance | breakingviews] news.")]
public string getSource { get; set; }
}
public static string selectURL(Options options){
switch (options.getSource){
case "top":
return Settings.topNewsUrl;
case "world":
return Settings.worldNewsUrl;
case "tech":
return Settings.techNewsUrl;
case "finance":
return Settings.financeNewsUrl;
case "breakingviews":
return Settings.breakingViewsUrl;
default:
return Settings.worldNewsUrl;
}
}
private static void Run(Options options) {
int pageNumber = Int32.Parse(options.getPage);
int articleNumber = Int32.Parse(options.getNumber);
List<string> articles, titles, urls;
string sourceUrl = selectURL(options);
if(pageNumber == -1){
(articles, titles, urls) = load(sourceUrl,refresh:options.isRefresh,source:options.getSource);
}else{
string newURL = sourceUrl + $"?view=page&page={pageNumber}&pageSize=10";
(articles, titles, urls) = load(newURL,refresh:true,source:options.getSource);
}
if (articleNumber < 0) {
print(titles,true);
} else {
print(getFullArticle(urls[articleNumber]),false,Int32.Parse(options.getWrap));
}
}
static void Main(string[] args) {
newFolderIfNotExist();
Parser.Default.ParseArguments<Options>(args).WithParsed(Run);
}
}
}