PageRenderTime 55ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/StarryEyes/Models/Subsystems/ContributionService.cs

https://github.com/a1lic/StarryEyes
C# | 87 lines | 78 code | 9 blank | 0 comment | 3 complexity | 150fad06baed2edc3806cdc28030820a MD5 | raw file
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Net.Http;
  5. using System.Reactive.Linq;
  6. using System.Threading.Tasks;
  7. using System.Xml.Linq;
  8. using Livet;
  9. using StarryEyes.Settings;
  10. namespace StarryEyes.Models.Subsystems
  11. {
  12. internal static class ContributionService
  13. {
  14. private static readonly ObservableSynchronizedCollectionEx<Contributor> _contributors =
  15. new ObservableSynchronizedCollectionEx<Contributor>();
  16. internal static ObservableSynchronizedCollectionEx<Contributor> Contributors
  17. {
  18. get { return _contributors; }
  19. }
  20. static ContributionService()
  21. {
  22. Observable.Timer(TimeSpan.FromSeconds(0), TimeSpan.FromHours(8))
  23. .Subscribe(_ => Task.Run(async () => await UpdateContributors()));
  24. }
  25. private static async Task UpdateContributors()
  26. {
  27. try
  28. {
  29. var vms = await Task.Run(async () =>
  30. {
  31. var hc = new HttpClient();
  32. var str = await hc.GetStringAsync(App.ContributorsUrl);
  33. using (var sr = new StringReader(str))
  34. {
  35. var xml = XDocument.Load(sr);
  36. return xml.Root
  37. .Descendants("contributor")
  38. .Where(
  39. e =>
  40. e.Attribute("visible") == null ||
  41. e.Attribute("visible").Value.ToLower() != "false")
  42. .Select(Contributor.FromXml)
  43. .ToArray();
  44. }
  45. });
  46. Contributors.Clear();
  47. vms.OrderBy(v => v.ScreenName ?? "~" + v.Name)
  48. .ForEach(Contributors.Add);
  49. }
  50. catch (Exception ex)
  51. {
  52. System.Diagnostics.Debug.WriteLine(ex);
  53. }
  54. }
  55. public static bool IsContributor()
  56. {
  57. var users = Contributors.Select(c => c.ScreenName).ToArray();
  58. return Setting.Accounts.Collection.Any(c => users.Contains(c.UnreliableScreenName));
  59. }
  60. }
  61. public class Contributor
  62. {
  63. public static Contributor FromXml(XElement xElement)
  64. {
  65. var twitter = xElement.Attribute("twitter");
  66. return twitter != null
  67. ? new Contributor(xElement.Value, twitter.Value)
  68. : new Contributor(xElement.Value, null);
  69. }
  70. public Contributor(string name, string screenName)
  71. {
  72. this.Name = name;
  73. this.ScreenName = screenName;
  74. }
  75. public string Name { get; set; }
  76. public string ScreenName { get; set; }
  77. }
  78. }