Advertisement
Guest User

NetworkController

a guest
Apr 6th, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 21.92 KB | None | 0 0
  1. using System;
  2. using FormsApp.Model;
  3. using System.Collections.Generic;
  4. using Xamarin.Forms;
  5. using System.Net;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net.Http;
  9. using System.Net.Http.Headers;
  10. using Newtonsoft.Json;
  11. using System.Threading;
  12. using ModernHttpClient;
  13. using System.Threading.Tasks;
  14. using Connectivity.Plugin;
  15. using PanicModels;
  16.  
  17. namespace FormsApp.Controllers
  18. {
  19.     public class NetworkManager
  20.     {
  21. //      private static Profile ServerProfile = null;
  22.  
  23.         public static List<ExternalLoginViewModel> ExternalLogins = new List<ExternalLoginViewModel>();
  24.        
  25.         private static NetworkManager _networkManager = null;
  26.  
  27.         public string serverUrl = @"https://geoohrana.ru/";
  28.         public LoginToken sessionToken = null;
  29.         private HttpClient httpClient = null;
  30.         private HttpClient panicHttpClient = null;
  31.         static NetworkManager()
  32.         {
  33.             _networkManager = new NetworkManager();
  34.         }
  35.  
  36.         public NetworkManager()
  37.         {
  38.             httpClient = Init();
  39.             panicHttpClient = Init();
  40.         }
  41.  
  42.         public static NetworkManager Instance
  43.         {
  44.             get
  45.             {
  46.                 return _networkManager;
  47.             }
  48.         }
  49.  
  50.         public void InitHttp()
  51.         {
  52.             httpClient = Init();
  53.             panicHttpClient = Init();
  54.         }
  55.  
  56.         private HttpClient Init()
  57.         {
  58.             var httClient = new HttpClient(new NativeMessageHandler());
  59.             httClient.BaseAddress = new Uri(serverUrl);
  60.             httClient.DefaultRequestHeaders.Accept.Clear();
  61.             httClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  62.             httClient.Timeout = TimeSpan.FromSeconds(40);
  63.             if (sessionToken != null)
  64.                 httClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(sessionToken.token_type, sessionToken.access_token);
  65.             return httClient;
  66.         }
  67.  
  68.         public void SetExternalToken(string token)
  69.         {
  70.             sessionToken = new LoginToken{access_token = token, token_type = "Bearer"};
  71.             sessionToken.expires = DateTime.Now.AddHours(5);
  72.             ProfileController.Instance.SessionToken = JsonConvert.SerializeObject(sessionToken);
  73.             InitHttp();
  74.         }
  75.  
  76.         public async Task<List<ExternalLoginViewModel>> GetExternalLogins()
  77.         {
  78.             using (var httClient = new HttpClient(new NativeMessageHandler()))
  79.             {
  80.                 httClient.BaseAddress = new Uri(serverUrl);
  81.             try
  82.             {
  83.                 if (CrossConnectivity.Current.IsConnected)
  84.                 {
  85.                     var response = await httClient.GetAsync("api/Account/ExternalLogins?returnUrl=%2F&generateState=true");
  86.                    
  87.                     if (response.IsSuccessStatusCode)
  88.                     {
  89.                         ExternalLogins = await response.Content.ReadAsAsync<List<ExternalLoginViewModel>>();
  90.                         return ExternalLogins;
  91.                     }
  92.                 }
  93.                 return null;
  94.             }
  95.             catch (Exception ex)
  96.             {
  97.                 string exp = ex.Message;
  98.                 return null;
  99.             }
  100.             }
  101.            
  102.         }
  103.  
  104.         public async Task<ProfileModel> GetProfile ()
  105.         {
  106.             using (var httClient = Init())
  107.             {
  108.             try
  109.             {
  110.                 if (CrossConnectivity.Current.IsConnected)
  111.                 {
  112.                     var response = await httClient.GetAsync("api/Profile/Load");
  113.                     if (response.IsSuccessStatusCode)
  114.                     {
  115.                         return await response.Content.ReadAsAsync<ProfileModel>();
  116.                     }
  117.                 }
  118.                 return null;
  119.             }
  120.             catch (Exception ex)
  121.             {
  122.                 string exp = ex.Message;
  123.                 return null;
  124.             }
  125.             }
  126.         }
  127.        
  128.         public async Task<string> Login(string username, string password)
  129.         {
  130.             if (CrossConnectivity.Current.IsConnected)
  131.             {
  132.                 try{
  133.                 httpClient.CancelPendingRequests();
  134.                 string sData = "grant_type=password&username=" + username + "&password=" + password;
  135.                 HttpContent content = new System.Net.Http.StringContent(sData, System.Text.Encoding.UTF8,
  136.                     "application/x-www-form-urlencoded");
  137.  
  138.                 HttpResponseMessage response = await httpClient.PostAsync("Token", content);
  139.                 if (response.IsSuccessStatusCode)
  140.                 {
  141.                     sessionToken = await response.Content.ReadAsAsync<LoginToken>();
  142.                     sessionToken.expires = DateTime.Now.AddDays((int) (sessionToken.expires_in/60/60/24));
  143.                     ProfileController.Instance.SessionToken = JsonConvert.SerializeObject(sessionToken);
  144.                     InitHttp();
  145.                     return "OK";
  146.                 }
  147.                 return "Ошибка при входе. Проверьте имя пользователя и пароль";
  148.                
  149.                     }
  150.                     catch (Exception)
  151.                     {
  152.                         return "Проверьте интернет соединение.";
  153.                     }
  154.             }
  155.             return "Проверьте интернет соединение.";
  156.         }
  157.  
  158.         public async Task Logout()
  159.         {
  160.             if (CrossConnectivity.Current.IsConnected)
  161.             {
  162.                 try{
  163.                 httpClient.CancelPendingRequests();
  164.                     HttpContent content = new System.Net.Http.StringContent("", System.Text.Encoding.UTF8,
  165.                         "application/x-www-form-urlencoded");
  166.                     HttpResponseMessage response = await httpClient.PostAsync("api/Account/Logout", content);
  167.                     if (response.IsSuccessStatusCode)
  168.                     {
  169.  
  170.                     }
  171.                
  172.                     }
  173.                     catch (Exception)
  174.                     {
  175.                         return;
  176.                     }
  177.             }
  178.         }
  179.  
  180.         public async Task<string> CheckIfPanic(bool defaultValue = false)
  181.         {
  182.             if (CrossConnectivity.Current.IsConnected)
  183.             {
  184.                 using (var httClient = Init ()) {
  185.                     try {
  186.                         httClient.CancelPendingRequests ();
  187.                         HttpResponseMessage response = await httClient.GetAsync ("api/Panic/CheckIfPanic");
  188.                         if (response.IsSuccessStatusCode) {
  189.                             return (await response.Content.ReadAsAsync<bool> ()).ToString ().ToLower();
  190.                         }else
  191.                         {
  192.                             return "network";
  193.                         }
  194.                
  195.                     } catch (Exception ex) {
  196.                         return "network";
  197.                     }
  198.                 }
  199.             }
  200.             return "network";
  201.         }
  202.  
  203.         public async Task<string> UpdatePanicGeo(PanicRequest request)
  204.         {
  205.             if (request.Geo.Lat == 0 || request.Geo.Lon == 0)
  206.             {
  207.                 return "GPS";
  208.             }
  209.             if (CrossConnectivity.Current.IsConnected)
  210.             {
  211.                 panicHttpClient.CancelPendingRequests();
  212.                     string sData = Newtonsoft.Json.JsonConvert.SerializeObject(request);
  213.                     HttpContent content = new System.Net.Http.StringContent(sData, System.Text.Encoding.UTF8,
  214.                         "application/json");
  215.                 HttpResponseMessage response = null;
  216.                 try
  217.                 {
  218.  
  219.                     response = await panicHttpClient.PostAsync("api/Panic/Panic", content);
  220.                 }
  221.                 catch (Exception)
  222.                 {
  223.                     return "NETWORK";
  224.                 }
  225.                     string managerPhone = null;
  226.                     if (response!= null && response.IsSuccessStatusCode)
  227.                     {
  228.                         managerPhone = await response.Content.ReadAsAsync<string>();
  229.                         return managerPhone;
  230.                     }
  231.                     return "NETWORK";
  232.             }
  233.             return "NETWORK";
  234.         }
  235.  
  236.         private DateTime lastTrue = DateTime.Now;
  237.         public async Task<bool> CheckIfInArea()
  238.         {
  239.             bool result = false;
  240.                 if (CrossConnectivity.Current.IsConnected)
  241.                 {
  242.                     panicHttpClient.CancelPendingRequests();
  243.                     string sData = Newtonsoft.Json.JsonConvert.SerializeObject(PanicController.currentGeo);
  244.                     HttpContent content = new System.Net.Http.StringContent(sData, System.Text.Encoding.UTF8,
  245.                         "application/json");
  246.                     try
  247.                     {
  248.                         HttpResponseMessage response = await panicHttpClient.PostAsync("api/Panic/CheckIfActive", content);
  249.                         if (response.IsSuccessStatusCode)
  250.                         {
  251.                             var resp = await response.Content.ReadAsAsync<string>();
  252.                             if (resp == "OK")
  253.                             {
  254.                                 lastTrue = DateTime.Now;
  255.                                 return true;
  256.                             }
  257.                         }
  258.                     }
  259.                     catch (Exception)
  260.                     {
  261.                     }
  262.                 }
  263.                 if (lastTrue.AddSeconds (30) > DateTime.Now)
  264.                     result = true;
  265.                 return result;
  266.         }
  267.        
  268.         public async Task<string> Register(RegisterModel model)
  269.         {
  270.             if (CrossConnectivity.Current.IsConnected)
  271.             {
  272.                 try
  273.                 {
  274.                     sessionToken = null;
  275.                     InitHttp();
  276.                     httpClient.CancelPendingRequests();
  277.                     string sData = Newtonsoft.Json.JsonConvert.SerializeObject(model);
  278.                     HttpContent content = new System.Net.Http.StringContent(sData, System.Text.Encoding.UTF8,
  279.                         "application/json");
  280.                    
  281.                     HttpResponseMessage response = await httpClient.PostAsync("api/Account/Register", content);
  282.                     if (response.IsSuccessStatusCode)
  283.                     {
  284.                         var resp = await response.Content.ReadAsStringAsync();
  285.                         return "OK";
  286.                     }
  287.                     return response.ReasonPhrase;
  288.                
  289.  
  290.                 }
  291.                 catch (Exception)
  292.                 {
  293.                     return "timeout";
  294.                 }
  295.             }
  296.             return "404";
  297.         }
  298.         public async Task<bool> RegisterExternal(string username)
  299.         {
  300.             if (CrossConnectivity.Current.IsConnected)
  301.             {
  302.                 try
  303.                 {
  304.                 httpClient.CancelPendingRequests();
  305.                 string sData = Newtonsoft.Json.JsonConvert.SerializeObject(new RegisterExternalBindingModel{ Email = username});
  306.                 HttpContent content = new System.Net.Http.StringContent(sData, System.Text.Encoding.UTF8,
  307.                     "application/json");
  308.  
  309.                 HttpResponseMessage response = await httpClient.PostAsync("api/Account/RegisterExternal", content);
  310.                 if (response.IsSuccessStatusCode)
  311.                 {
  312.                     return true;
  313.                 }
  314.                 return false;
  315.                
  316.                     }
  317.                     catch (Exception)
  318.                     {
  319.                         return false;
  320.                     }
  321.             }
  322.             return false;
  323.         }
  324.  
  325.         public class AddExternalLoginBindingModel
  326.         {
  327.             public string ExternalAccessToken { get; set; }
  328.         }
  329.  
  330.  
  331.         public async Task<UserInfoViewModel> GetExternalUser()
  332.         {
  333.             if (CrossConnectivity.Current.IsConnected)
  334.             {
  335.                 try{
  336.                 httpClient.CancelPendingRequests();
  337.  
  338.                 HttpResponseMessage response = await httpClient.GetAsync("api/Account/UserInfo");
  339.                 if (response.IsSuccessStatusCode)
  340.                 {
  341.                     var user = await response.Content.ReadAsAsync<UserInfoViewModel>();/*
  342.                     if (!user.HasRegistered)
  343.                     {
  344.                         string sData = Newtonsoft.Json.JsonConvert.SerializeObject(new AddExternalLoginBindingModel { ExternalAccessToken = sessionToken.access_token});
  345.                         HttpContent content = new System.Net.Http.StringContent(sData, System.Text.Encoding.UTF8,
  346.                             "application/json");
  347.  
  348.                         response = await httpClient.PostAsync("api/Account/AddExternalLogin", content);
  349.                         if (response.IsSuccessStatusCode)
  350.                             return user;
  351.                     }
  352.                     response = await httpClient.GetAsync("api/Account/ExternalLogin?provider=" + user.LoginProvider);*/
  353.                     return user;
  354.                 }
  355.                
  356.  
  357.                 }
  358.                 catch (Exception)
  359.                 {
  360.                     return null;
  361.                 }
  362.                 return null;
  363.             }
  364.             return null;
  365.         }
  366.         public async Task<bool> ForgotPasswordRequest(string mail)
  367.         {
  368.  
  369.             if (CrossConnectivity.Current.IsConnected)
  370.             {
  371.                 try
  372.                 {
  373.                 httpClient.CancelPendingRequests();
  374.                     string sData = Newtonsoft.Json.JsonConvert.SerializeObject(new MailModel {email = mail});
  375.                     HttpContent content = new System.Net.Http.StringContent(sData, System.Text.Encoding.UTF8,
  376.                         "application/json");
  377.  
  378.                     HttpResponseMessage response = await httpClient.PostAsync("api/Account/ForgotPassword", content);
  379.                     if (response.IsSuccessStatusCode)
  380.                     {
  381.                         return true;
  382.                     }
  383.                     return false;
  384.                
  385.  
  386.                 }
  387.                 catch (Exception)
  388.                 {
  389.                     return false;
  390.                 }
  391.             }
  392.             return false;
  393.         }
  394.         public async Task<bool> ResetPassword(ResetModel model)
  395.         {
  396.  
  397.             if (CrossConnectivity.Current.IsConnected)
  398.             {
  399.                 try
  400.                 {
  401.                 httpClient.CancelPendingRequests();
  402.                     string sData = Newtonsoft.Json.JsonConvert.SerializeObject(model);
  403.                     HttpContent content = new System.Net.Http.StringContent(sData, System.Text.Encoding.UTF8,
  404.                         "application/json");
  405.  
  406.                     HttpResponseMessage response = await httpClient.PostAsync("api/Account/ResetPassword", content);
  407.                     if (response.IsSuccessStatusCode)
  408.                     {
  409.                         return true;
  410.                     }
  411.                     return false;
  412.                
  413.  
  414.                 }
  415.                 catch (Exception)
  416.                 {
  417.                     return false;
  418.                 }
  419.             }
  420.             return false;
  421.         }
  422.  
  423.         public async Task<bool> PostImage(ImageModel image)
  424.         {
  425.             using (var httClient = Init())
  426.             {
  427.                 try
  428.                 {
  429.                     if (CrossConnectivity.Current.IsConnected)
  430.                     {
  431.                         httClient.CancelPendingRequests();
  432.                         string sData = Newtonsoft.Json.JsonConvert.SerializeObject(image);
  433.                         HttpContent content = new System.Net.Http.StringContent(sData, System.Text.Encoding.UTF8,
  434.                             "application/json");
  435.  
  436.                         HttpResponseMessage response = await httClient.PostAsync("api/Profile/SaveImage", content);
  437.                         if (response.IsSuccessStatusCode)
  438.                         {
  439.                             return true;
  440.                         }
  441.                         return false;
  442.                     }
  443.  
  444.                 }
  445.                 catch (Exception ex)
  446.                 {
  447.                     return false;
  448.                 }
  449.                 return false;
  450.             }
  451.         }
  452.  
  453.         public async Task<ImageModel> GetImage()
  454.         {
  455.             using (var httClient = Init())
  456.             {
  457.  
  458.                 if (CrossConnectivity.Current.IsConnected)
  459.                 {
  460.                     try{
  461.                     HttpResponseMessage response = null;
  462.                     response = await httClient.GetAsync("api/Profile/LoadImage");
  463.  
  464.                     ImageModel image = null;
  465.                     if (response.IsSuccessStatusCode)
  466.                     {
  467.                         image = await response.Content.ReadAsAsync<ImageModel>();
  468.                         return image;
  469.                     }
  470.                    
  471.                     }
  472.                     catch (Exception)
  473.                     {
  474.                         return null;
  475.                     }
  476.                     return null;
  477.                 }
  478.                 return null;
  479.             }
  480.         }
  481.  
  482.         public async Task<List<PeriodModel>> GetPayPeriods()
  483.         {
  484.             if (CrossConnectivity.Current.IsConnected)
  485.             {
  486.                 try
  487.                 {
  488.                 httpClient.CancelPendingRequests();
  489.                     HttpResponseMessage response = await httpClient.GetAsync("api/Content/Periods");
  490.                     List<PeriodModel> periods = null;
  491.                     if (response.IsSuccessStatusCode)
  492.                     {
  493.                         periods = await response.Content.ReadAsAsync<List<PeriodModel>>();
  494.                         return periods;
  495.                     }
  496.                     return null;
  497.                
  498.                     }
  499.                     catch (Exception)
  500.                     {
  501.                         return null;
  502.                     }
  503.             }
  504.             return null;
  505.         }
  506.  
  507.         public async Task UpdateProfile(ProfileModel profile, EventHandler onSuccess)
  508.         {
  509.             if (CrossConnectivity.Current.IsConnected)
  510.             {
  511.                 try
  512.                 {
  513.                 httpClient.CancelPendingRequests();
  514.                     string sData = Newtonsoft.Json.JsonConvert.SerializeObject(profile);
  515.                     HttpContent content = new System.Net.Http.StringContent(sData, System.Text.Encoding.UTF8,
  516.                         "application/json");
  517.                     HttpResponseMessage response = await httpClient.PostAsync("api/Profile/Save", content);
  518.                     if (response.IsSuccessStatusCode)
  519.                     {
  520.                         var responsedProfile = await response.Content.ReadAsAsync<ProfileModel>();
  521.                         onSuccess(responsedProfile, EventArgs.Empty);
  522.                     }
  523.                
  524.                     }
  525.                     catch (Exception)
  526.                     {
  527.                         return;
  528.                     }
  529.             }
  530.         }
  531.  
  532.         public async Task<TextPageModel> GetTerms()
  533.         {
  534.             try
  535.             {
  536.             if (CrossConnectivity.Current.IsConnected)
  537.             {
  538.                 try
  539.                 {
  540.                 httpClient.CancelPendingRequests();
  541.                     httpClient.CancelPendingRequests();
  542.                     HttpResponseMessage response = await httpClient.GetAsync("api/Content/Terms");
  543.                     if (response.IsSuccessStatusCode)
  544.                     {
  545.                         return await response.Content.ReadAsAsync<TextPageModel>();
  546.                     }
  547.                
  548.                     }
  549.                     catch (Exception)
  550.                 {
  551.                     return new TextPageModel { Body = "нет соединения с сервером", Header = "", Name = "" };
  552.                     }
  553.             }
  554.             return new TextPageModel { Body = "нет соединения с сервером", Header = "", Name = "" };
  555.             }
  556.             catch (Exception)
  557.             {
  558.                 return new TextPageModel { Body = "нет соединения с сервером", Header = "", Name = "" };
  559.             }
  560.         }
  561.  
  562.         public async Task<TextPageModel> GetInstructions()
  563.         {
  564.             try
  565.             {
  566.                 if (CrossConnectivity.Current.IsConnected)
  567.                 {
  568.                     try
  569.                     {
  570.                     httpClient.CancelPendingRequests();
  571.                         HttpResponseMessage response = await httpClient.GetAsync("api/Content/Instructions");
  572.                         if (response.IsSuccessStatusCode)
  573.                         {
  574.                             return await response.Content.ReadAsAsync<TextPageModel>();
  575.                         }
  576.                    
  577.                     }
  578.                     catch (Exception)
  579.                     {
  580.                         return new TextPageModel { Body = "нет соединения с сервером", Header = "", Name = "" };
  581.                     }
  582.                 }
  583.                 return new TextPageModel { Body = "нет соединения с сервером", Header = "", Name = "" };
  584.             }
  585.             catch (Exception)
  586.             {
  587.                 return new TextPageModel { Body = "нет соединения с сервером", Header = "", Name = "" };
  588.             }
  589.         }
  590.  
  591.         public async Task<List<TariffViewModel>> GetTariffes()
  592.         {
  593.             if (CrossConnectivity.Current.IsConnected)
  594.             {
  595.                 httpClient.CancelPendingRequests();
  596.                     var list = new List<TariffViewModel>()
  597.                     {
  598.                         new TariffViewModel(),
  599.                         new TariffViewModel(),
  600.                         new TariffViewModel()
  601.                     };
  602.                 try
  603.                 {
  604.                     HttpResponseMessage response = await httpClient.GetAsync("api/Content/Tariffes");
  605.                     if (response.IsSuccessStatusCode)
  606.                     {
  607.                         var tariffes = await response.Content.ReadAsAsync<List<TariffModel>>();
  608.                         if (tariffes == null || tariffes.Count < 3)
  609.                             return list;
  610.  
  611.                         list = tariffes.Select((x) => new TariffViewModel
  612.                         {
  613.                             Name = x.Name,
  614.                             Descriptions = JsonConvert.DeserializeObject<List<TextPageModel>>(x.Descriptions),
  615.                             Price = x.Price,
  616.                             ShortDescription = x.ShortDescription,
  617.                             Id = x.Id,
  618.                             TextColor = x.TextColor,
  619.                             Type = x.Type,
  620.                             ImagePath = ""
  621.                         }).ToList();
  622.  
  623.                         list[0].ImagePath = "childTariff.png";
  624.                         list[0].TextColor = "#67b8f6";
  625.  
  626.                         list[1].ImagePath = "standartTariff.png";
  627.                         list[1].TextColor = "#9572ec";
  628.  
  629.                         list[2].ImagePath = "extremeTariff.png";
  630.                         list[2].TextColor = "#ad3bd3";
  631.  
  632.                         return list;
  633.  
  634.                     }
  635.                
  636.                
  637.                     }
  638.                     catch (Exception)
  639.                     {
  640.                         return list;
  641.                     }
  642.                     return null;
  643.             }
  644.             return null;
  645.         }
  646.     }
  647. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement