Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2018
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 35.08 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.IO;
  10. using System.Runtime.Serialization.Formatters.Binary;
  11. using System.Net;
  12. using System.Text.RegularExpressions;
  13. using System.Xml;
  14. using Thrift;
  15. using Thrift.Protocol;
  16. using Thrift.Collections;
  17. using Thrift.Transport;
  18. using Evernote.EDAM.Type;
  19. using Evernote.EDAM.UserStore;
  20. using Evernote.EDAM.NoteStore;
  21. using Evernote.EDAM.Error;
  22. using System.Runtime.InteropServices;
  23.  
  24. namespace SoccerwayWebScraper
  25. {
  26. public partial class Form1 : Form
  27. {
  28.  
  29. string getLeaguesUrlStart = "http://www.soccerway.com/a/block_teams_index_club_teams?block_id=page_teams_1_block_teams_index_club_teams_2&callback_params=%7B%22level%22%3A%222%22%7D&action=expandItem&params=%7B%22area_id%22%3A%22";
  30. string getLeaguesUrlEnd = "%22%2C%22level%22%3A2%2C%22item_key%22%3A%22area_id%22%7D";
  31.  
  32. string getTeamsUrlStart = "http://www.soccerway.com/a/block_teams_index_club_teams?block_id=page_teams_1_block_teams_index_club_teams_2&callback_params=%7B%22level%22%3A%222%22%7D&action=expandItem&params=%7B%22competition_id%22%3A%22";
  33. string getTeamsUrlEnd = "%22%2C%22level%22%3A3%2C%22item_key%22%3A%22competition_id%22%7D";
  34.  
  35. string getStatsUrlStart = "http://www.soccerway.com/a/block_team_squad?block_id=page_team_1_block_team_squad_7&callback_params=%7B%22team_id%22%3A%22";
  36. string getStatsUrlEnd = "%22%7D&action=changeView&params=%7B%22view%22%3A1%7D";
  37.  
  38. string authToken = "S=s1:U=94e77:E=16d5aa23a5c:C=16602f10d60:P=1cd:A=en-devtoken:V=2:H=cb38f20368a29a1b2b3f34cc38f95fce";
  39.  
  40. public Form1()
  41. {
  42. InitializeComponent();
  43. }
  44.  
  45. List<Country> ReadSerializedCountryList()
  46. {
  47. //Stream streamRead = new MemoryStream(Properties.Resources.Countries);
  48. Stream streamRead = File.OpenRead("Countries.serialized");
  49. BinaryFormatter binaryRead = new BinaryFormatter();
  50. List<Country> result = (List<Country>)binaryRead.Deserialize(streamRead);
  51. streamRead.Close();
  52. return result;
  53. }
  54.  
  55. List<League> ReadSerializedLeagueList(string path)
  56. {
  57. //Stream streamRead = new MemoryStream(Properties.Resources.Leagues);
  58. Stream streamRead = File.OpenRead(path);
  59. BinaryFormatter binaryRead = new BinaryFormatter();
  60. List<League> result = (List<League>)binaryRead.Deserialize(streamRead);
  61. streamRead.Close();
  62. return result;
  63. }
  64.  
  65. List<Country> ReadCountries(string filename)
  66. {
  67. string file = File.ReadAllText(filename);
  68.  
  69. List<string> rawCountries = file.Split(new string[1] {"</li>"}, StringSplitOptions.RemoveEmptyEntries).ToList();
  70. rawCountries.Remove(rawCountries.Last());
  71.  
  72. List<Country> countries = new List<Country>();
  73.  
  74. foreach (string country in rawCountries)
  75. {
  76. int index1 = country.IndexOf("data-area_id=\"") + "data-area_id=\"".Length;
  77. int index2 = country.IndexOf("\">\r\n <div class=\"row\">");
  78. string temp = country.Substring(index1, index2 - index1);
  79. int id = Int32.Parse(temp);
  80. index1 = country.IndexOf("\" >\r\n") + "\" >\r\n".Length;
  81. index2 = index1 + country.Remove(0, index1).IndexOf("\r\n");
  82. string name = country.Substring(index1, index2 - index1);
  83. name = name.Trim();
  84. countries.Add(new Country() { Id = id, Name = name });
  85. }
  86.  
  87. return countries;
  88. }
  89.  
  90. void SerializeCountryList()
  91. {
  92. Stream streamWrite = File.Create("Countries2.serialized");
  93. BinaryFormatter binaryWrite = new BinaryFormatter();
  94. binaryWrite.Serialize(streamWrite, allCountries);
  95. streamWrite.Close();
  96. }
  97.  
  98. void SerializeLeagues(List<League> l, string path)
  99. {
  100. Stream streamWrite = File.Create(path);
  101. BinaryFormatter binaryWrite = new BinaryFormatter();
  102. binaryWrite.Serialize(streamWrite, l);
  103. streamWrite.Close();
  104. }
  105.  
  106. void BuildLeagueListFromFiles()
  107. {
  108. allLeagues = new List<League>();
  109.  
  110. foreach (Country c in allCountries)
  111. {
  112.  
  113. string text = File.ReadAllText(c.Name);
  114. if (!text.Contains("<ul class=\\\"competitions\\\""))
  115. continue;
  116. text = text.Substring(text.IndexOf("<ul"), text.IndexOf("<\\/ul") - text.IndexOf("<ul"));
  117. List<string> rawLeagues = text.Split(new string[1] { "<li" }, StringSplitOptions.RemoveEmptyEntries).ToList();
  118. rawLeagues.Remove(rawLeagues.First());
  119. foreach (string s in rawLeagues)
  120. {
  121. int index1 = s.IndexOf("data-competition_id=\\\"") + "data-competition_id=\\\"".Length;
  122. int index2 = s.IndexOf("\\\"><div class=\\\"row\\\"");
  123. string temp = s.Substring(index1, index2 - index1);
  124. index1 = s.IndexOf("class=\\\"competition\\\" >") + "class=\\\"competition\\\" >".Length;
  125. index2 = s.IndexOf("<\\/a><span class=\\\"expand_icon\\\">");
  126. string name = s.Substring(index1, index2 - index1);
  127. allLeagues.Add(new League() { CountryId = c.Id, Id = temp, Name = name });
  128. }
  129.  
  130. }
  131. }
  132.  
  133. Random r = new Random();
  134.  
  135. void SaveAllCountryLeaguesToFiles()
  136. {
  137. foreach (Country c in allCountries)
  138. {
  139. string url = getLeaguesUrlStart + c.Id.ToString() + getLeaguesUrlEnd;
  140. WebClient wc = new WebClient();
  141. wc.Headers.Add("User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7");
  142. wc.DownloadFile(url, c.Name);
  143. System.Threading.Thread.Sleep(r.Next(1000, 4000));
  144. }
  145. }
  146.  
  147. List<Country> allCountries;
  148. List<League> allLeagues;
  149.  
  150. List<League> monitoredLeagues;
  151.  
  152. private void Form1_Load(object sender, EventArgs e)
  153. {
  154. SetPassword();
  155. SetLocation();
  156.  
  157. allCountries = ReadSerializedCountryList();
  158. allLeagues = ReadSerializedLeagueList("Leagues.serialized");
  159.  
  160. monitoredLeagues = ReadSerializedLeagueList("Monitored.serialized");
  161.  
  162. PopulateComboBox();
  163. PopulateListBox();
  164. }
  165.  
  166. void UpdateAllLeaguesToEvernote()
  167. {
  168. // im not sure whether we need this, but im too lazy to test
  169. List<League> unupdatedLeagues = (List<League>)Ext.Clone(monitoredLeagues);
  170.  
  171. everythingFinishedUpdating = false;
  172.  
  173. DoDelayedLeagueUpdate(unupdatedLeagues);
  174.  
  175. }
  176.  
  177. bool leagueFinishedUpdating = false;
  178. bool everythingFinishedUpdating = false;
  179.  
  180. // same as teams
  181. void DoDelayedLeagueUpdate(List<League> unupdatedLeagues)
  182. {
  183. if (SomethingDown())
  184. {
  185. everythingFinishedUpdating = true;
  186. return;
  187. }
  188.  
  189. if (unupdatedLeagues.Count() == 0)
  190. {
  191. //finished everything
  192. everythingFinishedUpdating = true;
  193. return;
  194. }
  195.  
  196. leagueFinishedUpdating = false;
  197.  
  198. League leagueToBeUpdated = unupdatedLeagues.Last();
  199. UpdateLeagueToEvernote(leagueToBeUpdated);
  200. unupdatedLeagues.Remove(leagueToBeUpdated);
  201.  
  202. Timer t = new Timer() { Interval = r.Next(10000, 20000) };
  203. t.Tick += delegate { if (leagueFinishedUpdating) { t.Stop(); DoDelayedLeagueUpdate(unupdatedLeagues); } };
  204. t.Start();
  205. }
  206.  
  207. void UpdateLeagueToEvernote(League l)
  208. {
  209. List<Team> rawTeams = GetAllTeams(l);
  210.  
  211. if (SomethingDown())
  212. {
  213. leagueFinishedUpdating = true;
  214. return;
  215. }
  216.  
  217. List<TeamWithStats> teamsWithStats = new List<TeamWithStats>();
  218.  
  219. DoDelayedTeamUpdate(l, rawTeams, teamsWithStats);
  220. }
  221.  
  222. // This function is called for EVERY team with a timer, this is done to not send 9999 requests at once, but in a human like 1-4 second intervals
  223. // it's kind of a delayed recursion
  224. void DoDelayedTeamUpdate(League l, List<Team> teamsLeftToUpdate, List<TeamWithStats> teamsUpdated)
  225. {
  226. if (SomethingDown())
  227. {
  228. leagueFinishedUpdating = true;
  229. return;
  230. }
  231.  
  232. if (teamsLeftToUpdate.Count() == 0)
  233. {
  234. updateMsg = "Now sending team stats to evernote...";
  235. UpdateNotebook(l, teamsUpdated);
  236.  
  237. leagueFinishedUpdating = true;
  238. return;
  239. }
  240.  
  241. Team teamToUpdate = teamsLeftToUpdate.Last();
  242. updateMsg = "Getting stats table for " + l.QualifiedName + " team " + teamToUpdate.Name;
  243. TeamWithStats updatedTeam = new TeamWithStats(teamToUpdate, GetTeamStatsTable(teamToUpdate));
  244.  
  245. if (SomethingDown())
  246. {
  247. leagueFinishedUpdating = true;
  248. return;
  249. }
  250.  
  251. teamsLeftToUpdate.Remove(teamToUpdate);
  252. teamsUpdated.Add(updatedTeam);
  253.  
  254. Timer t = new Timer() { Interval = r.Next(1000, 3000) };
  255. t.Tick += delegate { t.Stop(); DoDelayedTeamUpdate(l, teamsLeftToUpdate, teamsUpdated); };
  256. t.Start();
  257. }
  258.  
  259. bool SomethingDown()
  260. {
  261. if (offline || evernoteUnreachable || soccerwayUnreachable)
  262. return true;
  263.  
  264. return false;
  265. }
  266.  
  267. string FormartAsEvernote(string html, bool replacements)
  268. {
  269. if (replacements)
  270. {
  271. // remove all invalid attributes and tags
  272. List<string> res = new List<string>() { "(class|id|data-season_id|data-people_id)=\"[^\"]{0,}\"", "</?a[^>]{0,}>" };
  273.  
  274. foreach (string re in res)
  275. {
  276. html = Regex.Replace(html, re, "");
  277. }
  278.  
  279. // close any img tags
  280. html = html.Replace("</img>", "");
  281.  
  282. // src because it also can contain a close tag / like src="http://", so we skip it here
  283. string unclosedImg = "<img[^>]{0,}src=\"[^>]{0,}\"[^/>]{0,}>";
  284. MatchCollection mc = Regex.Matches(html, unclosedImg);
  285.  
  286. foreach (Match match in mc)
  287. {
  288. string temp = match.Value.Replace(">", "/>");
  289. html = html.Replace(match.Value, temp);
  290. }
  291. }
  292.  
  293. return @"<?xml version=""1.0"" encoding=""UTF-8""?>
  294. <!DOCTYPE en-note SYSTEM ""http://xml.evernote.com/pub/enml2.dtd"">
  295. <en-note>" + html + "</en-note>";
  296. }
  297.  
  298. void PopulateComboBox()
  299. {
  300. foreach (Country c in allCountries)
  301. {
  302. comboBox1.Items.Add(c);
  303. }
  304.  
  305. comboBox1.SelectedIndex = 0;
  306. }
  307.  
  308. void PopulateListBox()
  309. {
  310. listBox1.Items.Clear();
  311.  
  312. foreach (League l in monitoredLeagues)
  313. {
  314. listBox1.Items.Add(l);
  315.  
  316. }
  317. }
  318.  
  319. List<Team> GetAllTeams(League l)
  320. {
  321. List<Team> teams = new List<Team>();
  322.  
  323. string url = getTeamsUrlStart + l.Id + getTeamsUrlEnd;
  324. WebClient wc = new WebClient();
  325. wc.Headers.Add("User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7");
  326.  
  327. string raw = "";
  328.  
  329. int i = 0;
  330.  
  331. while (true)
  332. {
  333. if (!Online())
  334. {
  335. offline = true;
  336. return teams;
  337. }
  338.  
  339. try
  340. {
  341. raw = wc.DownloadString(url);
  342. break;
  343. }
  344. catch
  345. {
  346.  
  347. }
  348.  
  349. if (i++ > 20)
  350. {
  351. soccerwayUnreachable = true;
  352. return teams;
  353. }
  354. }
  355.  
  356. raw = raw.Remove(raw.IndexOf("<\\/ul"));
  357. List<string> rawTeams = raw.Split(new string[] { "<li" }, StringSplitOptions.RemoveEmptyEntries).ToList();
  358. rawTeams.Remove(rawTeams.First());
  359.  
  360. foreach (string s in rawTeams)
  361. {
  362. int index1 = s.IndexOf("<a href=\\\"\\") + "<a href=\\\"\\".Length;
  363. int index2 = s.IndexOf("\\\" class=");
  364. string urlOfTeam = s.Substring(index1, index2 - index1);
  365. urlOfTeam = urlOfTeam.Replace("\\", "");
  366. index1 = s.IndexOf("class=\\\"team\\\" >") + "class=\\\"team\\\" >".Length;
  367. index2 = s.IndexOf("<\\/a>");
  368. string name = s.Substring(index1, index2 - index1);
  369. teams.Add(new Team() { LeagueId = l.Id, Name = Regex.Unescape(name), Url = urlOfTeam });
  370. }
  371.  
  372. // " class=\\\" \\\" ><div class=\\\"row\\\"><a href=\\\"\\/teams\\/albania\\/ks-apolonia-fier\\/\\\" class=\\\"team\\\" >Apolonia Fier<\\/a><\\/div><\\/li>"
  373.  
  374. return teams;
  375. }
  376.  
  377. string GetTeamIdFromUrl(string url)
  378. {
  379. WebClient wc = new WebClient();
  380. wc.Headers.Add("User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7");
  381.  
  382. string html = "";
  383.  
  384. int i = 0;
  385.  
  386. while (true)
  387. {
  388. if (!Online())
  389. {
  390. offline = true;
  391. return "";
  392. }
  393.  
  394. try
  395. {
  396. html = wc.DownloadString("http://www.soccerway.com" + url);
  397. break;
  398. }
  399. catch
  400. {
  401.  
  402. }
  403.  
  404. if (i++ > 20)
  405. {
  406. soccerwayUnreachable = true;
  407. return "";
  408. }
  409. }
  410.  
  411. int index1 = html.IndexOf("\"team_id\":") + "\"team_id\":".Length;
  412. int index2 = html.IndexOf(",\"competition_id\"");
  413. html = html.Substring(index1, index2 - index1);
  414. return html;
  415. }
  416.  
  417. string GetTeamStatsTable(Team t)
  418. {
  419. string url = getStatsUrlStart + GetTeamIdFromUrl(t.Url) + getStatsUrlEnd;
  420.  
  421. if (SomethingDown())
  422. {
  423. return "";
  424. }
  425.  
  426. WebClient wc = new WebClient();
  427. wc.Headers.Add("User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7");
  428.  
  429. string html = "";
  430.  
  431. int i = 0;
  432.  
  433. while (true)
  434. {
  435. if (!Online())
  436. {
  437. offline = true;
  438. return "";
  439. }
  440.  
  441. try
  442. {
  443. html = wc.DownloadString(url);
  444. break;
  445. }
  446. catch
  447. {
  448.  
  449. }
  450.  
  451. if (i++ > 20)
  452. {
  453. soccerwayUnreachable = true;
  454. return "";
  455. }
  456. }
  457.  
  458. int index1 = html.IndexOf("<table");
  459. int index2 = html.IndexOf("<\\/table>") + "<\\/table>".Length;
  460.  
  461. if (index1 == -1)
  462. return TEAM_HAS_NO_STATS;
  463.  
  464. html = html.Substring(index1, index2 - index1);
  465. return Regex.Unescape(html);
  466. }
  467.  
  468. const string TEAM_HAS_NO_STATS = "<p>This team has no stats table.</p>";
  469.  
  470. private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
  471. {
  472. List<League> leagues = new List<League>();
  473.  
  474. foreach (League l in allLeagues)
  475. {
  476. Country c = (Country)comboBox1.SelectedItem;
  477. if (l.CountryId == c.Id)
  478. leagues.Add(l);
  479. }
  480.  
  481. comboBox2.Items.Clear();
  482.  
  483. foreach (League l in leagues)
  484. {
  485. comboBox2.Items.Add(l);
  486. }
  487.  
  488. comboBox2.SelectedIndex = 0;
  489. }
  490.  
  491. private void button2_Click(object sender, EventArgs e)
  492. {
  493. League toBeAddedLeague = (League)comboBox2.SelectedItem;
  494.  
  495. if (listBox1.Items.Contains(toBeAddedLeague))
  496. {
  497. MessageBox.Show("Already added!");
  498. return;
  499. }
  500.  
  501. monitoredLeagues.Add((League)comboBox2.SelectedItem);
  502. PopulateListBox();
  503. }
  504.  
  505. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  506. {
  507. if (started && !everythingFinishedUpdating)
  508. {
  509. MessageBox.Show("Can not exit while updating! Please wait.");
  510. e.Cancel = true;
  511. return;
  512. }
  513.  
  514. SaveLocation();
  515.  
  516. SerializeLeagues(monitoredLeagues, "Monitored.serialized");
  517. }
  518.  
  519. private void button1_Click(object sender, EventArgs e)
  520. {
  521. if (listBox1.SelectedItems.Count == 0)
  522. {
  523. MessageBox.Show("Nothing selected!");
  524. return;
  525. }
  526.  
  527. foreach(object obj in listBox1.SelectedItems)
  528. {
  529. monitoredLeagues.Remove((League)obj);
  530. }
  531.  
  532. PopulateListBox();
  533. }
  534.  
  535. // Creates a notebook if it doesnt exist
  536. // deletes all notes
  537. // adds a new note for every team
  538. // returns the error if any, if "" then it passed ok
  539. string UpdateNotebook(League l, List<TeamWithStats> teams)
  540. {
  541. int i = 0;
  542.  
  543. while (true)
  544. {
  545. if (!Online())
  546. {
  547. offline = true;
  548. return "";
  549. }
  550.  
  551. try
  552. {
  553. String username = textBox1.Text;
  554. String password = textBox2.Text;
  555.  
  556. String consumerKey = EVERNOTE_CONSUMER_KEY;
  557. String consumerSecret = EVERNOTE_CONSUMER_SECRET;
  558.  
  559. String evernoteHost = EVERNOTE_HOST;
  560. String edamBaseUrl = "http://" + evernoteHost; // do NOT use https - some kind of certificate errors
  561.  
  562. Uri userStoreUrl = new Uri(edamBaseUrl + "/edam/user");
  563. TTransport userStoreTransport = new THttpClient(userStoreUrl);
  564. TProtocol userStoreProtocol = new TBinaryProtocol(userStoreTransport);
  565. UserStore.Client userStore = new UserStore.Client(userStoreProtocol);
  566.  
  567. bool versionOK =
  568. userStore.checkVersion(CLIENT_NAME,
  569. Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MAJOR,
  570. Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MINOR);
  571.  
  572. if (!versionOK)
  573. {
  574. throw new Exception(ERROR_VERSION);
  575. }
  576.  
  577. AuthenticationResult authResult = null;
  578. String noteStoreUrlat = "";
  579. try
  580. {
  581. //authResult = userStore.authenticate(username, password,
  582. // consumerKey, consumerSecret);
  583. noteStoreUrlat = userStore.getNoteStoreUrl(authToken);
  584. }
  585. catch
  586. {
  587. throw new Exception(ERROR_RUNTIME_LOGIN);
  588. }
  589.  
  590. //User user = authResult.User;
  591. //String authToken = authResult.AuthenticationToken;
  592. //String authToken = "";
  593.  
  594.  
  595. //Uri noteStoreUrl = new Uri(edamBaseUrl + "/edam/note/" + user.ShardId);
  596. Uri noteStoreUrl = new Uri(noteStoreUrlat);
  597. TTransport noteStoreTransport = new THttpClient(noteStoreUrl);
  598. TProtocol noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
  599. NoteStore.Client noteStore = new NoteStore.Client(noteStoreProtocol);
  600.  
  601. List<Notebook> notebooks = noteStore.listNotebooks(authToken);
  602.  
  603. string openNotebookGuid = "";
  604.  
  605. foreach (Notebook n in notebooks)
  606. {
  607. if (n.Name == l.QualifiedName)
  608. openNotebookGuid = n.Guid;
  609. }
  610.  
  611. if (openNotebookGuid == "")
  612. {
  613. // we need to create one
  614. openNotebookGuid = noteStore.createNotebook(authToken, new Notebook() { Name = l.QualifiedName }).Guid;
  615. }
  616.  
  617. // We get all the notes in the league notebook
  618. NoteList nl = noteStore.findNotes(authToken, new NoteFilter() { NotebookGuid = openNotebookGuid }, 0, 999); // 999 is the maximum number of teams possible in a league...
  619.  
  620. // and delete them
  621. foreach (Note n in nl.Notes)
  622. {
  623. noteStore.deleteNote(authToken, n.Guid);
  624. }
  625.  
  626. // and now add the new ones
  627. foreach (TeamWithStats t in teams)
  628. {
  629. updateMsg = "Updating team " + l.QualifiedName + " " + t.Name + " to evernote";
  630. Note newTeamStatsNote = new Note();
  631. newTeamStatsNote.NotebookGuid = openNotebookGuid;
  632. newTeamStatsNote.Title = t.Name.Trim();
  633. newTeamStatsNote.Content = t.Stats == TEAM_HAS_NO_STATS ? FormartAsEvernote(t.Stats, false) : FormartAsEvernote(t.Stats, true);
  634. noteStore.createNote(authToken, newTeamStatsNote);
  635. }
  636.  
  637. return ""; //"" is everything is ok == no error
  638. }
  639. catch(Exception e)
  640. {
  641. if (e.Message == ERROR_RUNTIME_LOGIN || e.Message == ERROR_VERSION)
  642. throw;
  643. }
  644.  
  645. if (i++ > 20)
  646. {
  647. evernoteUnreachable = true;
  648. return "";
  649. }
  650. }
  651. }
  652.  
  653. bool started = false;
  654.  
  655. private void button3_Click_1(object sender, EventArgs e)
  656. {
  657. if (listBox1.Items.Count == 0)
  658. {
  659. MessageBox.Show("Please select some leagues to monitor. Then click this!");
  660. return;
  661. }
  662.  
  663. //if (textBox1.Text.Trim() == "" || textBox2.Text.Trim() == "")
  664. //{
  665. // MessageBox.Show("Please enter username and password.");
  666. // return;
  667. //}
  668.  
  669. if (!CanLogin(textBox1.Text, textBox2.Text))
  670. {
  671. MessageBox.Show("Cant login. You have mistyped your username or password.");
  672. return;
  673. }
  674.  
  675. groupBox1.Enabled = false;
  676. groupBox2.Enabled = false;
  677. groupBox3.Enabled = false;
  678. button4.Enabled = true;
  679. button5.Enabled = true;
  680.  
  681. if (checkBox1.Checked)
  682. {
  683. SavePassword();
  684. }
  685. else
  686. {
  687. ClearPassword();
  688. }
  689.  
  690. started = true;
  691. BeginWebScraping();
  692. textBox3.Text = "Please wait...";
  693. }
  694.  
  695. void SetPassword()
  696. {
  697. if (Properties.Settings.Default.PasswordSet)
  698. {
  699. textBox1.Text = Properties.Settings.Default.Username;
  700. textBox2.Text = Properties.Settings.Default.Password;
  701. }
  702. }
  703.  
  704. void SetLocation()
  705. {
  706. if (Properties.Settings.Default.LocationSet)
  707. {
  708. this.Location = new Point(Properties.Settings.Default.LocationX, Properties.Settings.Default.LocationY);
  709. }
  710. }
  711.  
  712. void SaveLocation()
  713. {
  714. Properties.Settings.Default.LocationSet = true;
  715. Properties.Settings.Default.LocationX = this.Location.X;
  716. Properties.Settings.Default.LocationY = this.Location.Y;
  717. Properties.Settings.Default.Save();
  718. }
  719.  
  720. void SavePassword()
  721. {
  722. Properties.Settings.Default.PasswordSet = true;
  723. Properties.Settings.Default.Username = textBox1.Text;
  724. Properties.Settings.Default.Password = textBox2.Text;
  725. Properties.Settings.Default.Save();
  726. }
  727.  
  728. void ClearPassword()
  729. {
  730. Properties.Settings.Default.PasswordSet = false;
  731. Properties.Settings.Default.Save();
  732. }
  733.  
  734. DateTime nextUpdate;
  735.  
  736. // this is NOT the forms timer - intentional!
  737. Timer everythingUpdateTimer;
  738.  
  739. // THIS IS CALLED BY "UPDATERIGHTNOW" BUTTON BE VERY CAREFUL ABOUT MODIFYING ***ANYTHING***
  740. void BeginWebScraping()
  741. {
  742. // here we try again, if any of these are true, they will be made so by methods that access the net further down
  743. offline = false;
  744. evernoteUnreachable = false;
  745. soccerwayUnreachable = false;
  746.  
  747. UpdateAllLeaguesToEvernote();
  748.  
  749. everythingUpdateTimer = new Timer() { Interval = 500 };
  750. everythingUpdateTimer.Tick += delegate
  751. {
  752. // not yet
  753. if (DateTime.Compare(DateTime.Now, nextUpdate) < 0)
  754. {
  755. if (SomethingDown())
  756. {
  757. // The last update FAILED, we will try again after an hour
  758. if (DateTime.Compare(DateTime.Now.Add(new TimeSpan(0, 1, 0)), nextUpdate) < 0)
  759. {
  760. TimeSpan tsFailed = new TimeSpan(0, 1, 0);
  761. nextUpdate = DateTime.Now.Add(tsFailed);
  762. }
  763. }
  764.  
  765. return;
  766. }
  767. else // let's try again because it's time
  768. {
  769. offline = false;
  770. evernoteUnreachable = false;
  771. soccerwayUnreachable = false;
  772. }
  773.  
  774. if(everythingFinishedUpdating) // theoretically this could happen if there are way too many leagues and an update time of 1 hour
  775. UpdateAllLeaguesToEvernote();
  776.  
  777. TimeSpan ts = new TimeSpan((int)numericUpDown1.Value, 0, 0);
  778. nextUpdate = DateTime.Now.Add(ts);
  779. };
  780.  
  781. everythingUpdateTimer.Start();
  782.  
  783. // DO NOT INCREASE THE 480 HOUR LIMIT! IT WILL OVERFLOW INT32.MAXVALUE
  784. TimeSpan initialts = new TimeSpan((int)numericUpDown1.Value, 0, 0); // same as ts
  785. nextUpdate = DateTime.Now.Add(initialts);
  786. }
  787.  
  788. const string EVERNOTE_CONSUMER_KEY = "soccerwayscraper";
  789. const string EVERNOTE_CONSUMER_SECRET = "5ff315a2191d98d1";
  790. //const string EVERNOTE_HOST = "evernote.com"; // to switch between the sanbox.evernote.com
  791. const string EVERNOTE_HOST = "www.evernote.com"; // to switch between the sanbox.evernote.com
  792. const string CLIENT_NAME = "Simple note storer v1.0"; // coulnt think of anything better
  793.  
  794. const string ERROR_VERSION = "Evernote has changed it's API protocol, this application needs to be updated.";
  795. const string ERROR_RUNTIME_LOGIN = "Failed to login. Perhaps the password is changed while this program was running or the user deleted."; // not the same as simple login
  796.  
  797. bool CanLogin(string user, string pass)
  798. {
  799. int i = 0;
  800.  
  801. while (true) // try has a return
  802. {
  803. if (!Online())
  804. {
  805. textBox3.Text = "No internet.";
  806. return false;
  807. }
  808. else
  809. {
  810. textBox3.Text = "Please add leagues, enter username and password and click \"Begin web scraping\".";
  811. }
  812.  
  813. try
  814. {
  815. String username = user;
  816. String password = pass;
  817.  
  818. String consumerKey = EVERNOTE_CONSUMER_KEY;
  819. String consumerSecret = EVERNOTE_CONSUMER_SECRET;
  820.  
  821. String evernoteHost = EVERNOTE_HOST;
  822. String edamBaseUrl = "http://" + evernoteHost;
  823.  
  824. Uri userStoreUrl = new Uri(edamBaseUrl + "/edam/user");
  825. TTransport userStoreTransport = new THttpClient(userStoreUrl);
  826. TProtocol userStoreProtocol = new TBinaryProtocol(userStoreTransport);
  827. UserStore.Client userStore = new UserStore.Client(userStoreProtocol);
  828.  
  829. bool versionOK =
  830. userStore.checkVersion(CLIENT_NAME,
  831. Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MAJOR,
  832. Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MINOR);
  833.  
  834. if (!versionOK)
  835. {
  836. throw new Exception(ERROR_VERSION);
  837. }
  838.  
  839. AuthenticationResult authResult = null;
  840. try
  841. {
  842. //authResult = userStore.authenticate(username, password,consumerKey, consumerSecret);
  843. }
  844. catch
  845. {
  846. return false;
  847. }
  848.  
  849. return true;
  850. }
  851. catch(Exception e)
  852. {
  853. if (e.Message == ERROR_VERSION)
  854. throw;
  855. }
  856.  
  857. if (i++ > 20)
  858. throw new Exception("Failed to connect to evernote. This application can not be started.");
  859. }
  860. }
  861.  
  862. // There was a prettier method I used a lot, but it gave a lot of false positives, this works better
  863. bool Online()
  864. {
  865. try
  866. {
  867. string myAddress = "www.google.com";
  868. IPAddress[] addresslist = Dns.GetHostAddresses(myAddress);
  869.  
  870. if (addresslist[0].ToString().Length > 6)
  871. {
  872. return true;
  873. }
  874. else
  875. return false;
  876.  
  877. }
  878. catch
  879. {
  880. return false;
  881. }
  882. }
  883.  
  884. private void button4_Click(object sender, EventArgs e)
  885. {
  886.  
  887. if (!everythingFinishedUpdating)
  888. {
  889. MessageBox.Show("Can not exit while updating! Please wait.");
  890. return;
  891. }
  892.  
  893. Application.Restart();
  894. }
  895.  
  896. string updateMsg;
  897.  
  898. bool offline = false;
  899. bool evernoteUnreachable = false;
  900. bool soccerwayUnreachable = false;
  901.  
  902. private void timer1_Tick(object sender, EventArgs e)
  903. {
  904. if (!started)
  905. return;
  906.  
  907. if (everythingFinishedUpdating)
  908. {
  909. TimeSpan timeToNextUpdate = nextUpdate.Subtract(DateTime.Now);
  910.  
  911. textBox3.Text = "";
  912.  
  913. if (offline)
  914. textBox3.Text += "Offline.\r\n";
  915.  
  916. if (evernoteUnreachable)
  917. textBox3.Text += "Evernote unreachable.\r\n";
  918.  
  919. if (soccerwayUnreachable)
  920. textBox3.Text += "Soccerway unreachable.\r\n";
  921.  
  922. textBox3.Text += "The next update will happen after " + timeToNextUpdate.Days + " days and " + timeToNextUpdate.Hours + ":" + timeToNextUpdate.Minutes + ":" + timeToNextUpdate.Seconds;
  923. }
  924. else
  925. {
  926. textBox3.Text = "Working right now. Please be patient! " + updateMsg;
  927. }
  928.  
  929. this.Refresh();
  930. }
  931.  
  932. private void button5_Click(object sender, EventArgs e)
  933. {
  934. if (!everythingFinishedUpdating)
  935. {
  936. MessageBox.Show("Update is already under way!");
  937. return;
  938. }
  939.  
  940. everythingUpdateTimer.Stop();
  941.  
  942. BeginWebScraping();
  943. }
  944. }
  945.  
  946. [Serializable]
  947. struct Country
  948. {
  949. public int Id;
  950. public string Name;
  951.  
  952. public override string ToString()
  953. {
  954. return Name;
  955. }
  956. }
  957.  
  958. [Serializable]
  959. struct League : IEquatable<League>
  960. {
  961. public string Id; // "Other" leagues are like IDs "0-9", which is NaN
  962. public string Name;
  963. public int CountryId;
  964. public string CountryName;
  965. public string QualifiedName
  966. {
  967. get { return this.ToString(); }
  968. }
  969.  
  970. public override string ToString()
  971. {
  972. return CountryName + ": " + Name;
  973. }
  974.  
  975. public bool Equals(League l)
  976. {
  977. if (l.Id == this.Id)
  978. return true;
  979.  
  980. return false;
  981. }
  982.  
  983. }
  984.  
  985. class Team
  986. {
  987. public string Url;
  988. public string Name;
  989. public string LeagueId; // Intentional string
  990.  
  991. public override string ToString()
  992. {
  993. return Name;
  994. }
  995. }
  996.  
  997. class TeamWithStats : Team
  998. {
  999. public string Stats; //html
  1000.  
  1001. public TeamWithStats(Team t, string stats)
  1002. {
  1003. Stats = stats;
  1004. base.Name = t.Name;
  1005. base.Url = t.Url;
  1006. base.LeagueId = t.LeagueId;
  1007. }
  1008. }
  1009.  
  1010. // Binārā serializācija objektu instanču klonēšanai
  1011. static class Ext // Extensions
  1012. {
  1013. // Vienkārš objektu klonētajs, kurš izmanto serializāciju
  1014. public static object Clone(object obj)
  1015. {
  1016. object objResult = null;
  1017.  
  1018. using (MemoryStream ms = new MemoryStream())
  1019. {
  1020. BinaryFormatter bf = new BinaryFormatter();
  1021. bf.Serialize(ms, obj);
  1022.  
  1023. ms.Position = 0;
  1024. objResult = bf.Deserialize(ms);
  1025. }
  1026.  
  1027. return objResult;
  1028. }
  1029. }
  1030. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement