Advertisement
Guest User

Untitled

a guest
Jul 6th, 2015
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.43 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.Http;
  4. using System.Net.Http.Headers;
  5. using System.Threading.Tasks;
  6. using Newtonsoft.Json;
  7. using MusicPickerApp.Api.Util;
  8. using Quobject.SocketIoClientDotNet.Client;
  9.  
  10. namespace MusicPickerApp.Api {
  11.     /// <summary>
  12.     /// Singleton class which regroups every call to the server the application need to do (HttpRequests and WebSockets)
  13.     /// The server url is the localhost if you want deploy the server on your computer if not you can find the address of our server by mail
  14.     ///</summary>
  15.     public sealed class ApiClient {
  16.         private static readonly string SERVER_URL = "http://nodepicker.cloudapp.net/";
  17.         private static readonly ApiClient instance = new ApiClient();
  18.         private static readonly Uri endpoint = new Uri(SERVER_URL);
  19.         private string bearer;
  20.         private bool authenticated;
  21.         public Device CurrentDevice { get; set; }
  22.         public Artist CurrentArtist { get; set; }
  23.         public Album CurrentAlbum { get; set; }
  24.         public Track CurrentTrack { get; set; }
  25.  
  26.         public static bool isConnected = false;
  27.  
  28.         /*private HubConnection hubConnection;
  29.         private IHubProxy hubProxy;*/
  30.         private Socket socket;
  31.         public static ApiClient Instance {
  32.             get {
  33.                 return instance;
  34.             }
  35.         }
  36.  
  37.         private ApiClient() {
  38.         }
  39.  
  40.         public bool SignUp(string username, string password) {
  41.             Uri uri = new Uri(endpoint, "/api/Account/Register");
  42.             HttpContent content = new FormUrlEncodedContent(new[]
  43.             {
  44.                 new KeyValuePair<string, string>("Username", username),
  45.                 new KeyValuePair<string, string>("Password", password),
  46.                 new KeyValuePair<string, string>("ConfirmPassword", password),
  47.             });
  48.  
  49.             HttpResponseMessage result = (new HttpClient()).PostAsync(uri, content).Result;
  50.  
  51.             if (result.IsSuccessStatusCode) {
  52.                 return true;
  53.             }
  54.  
  55.             return false;
  56.         }
  57.  
  58.         public string RetrieveBearer() {
  59.             return this.bearer;
  60.         }
  61.  
  62.         public void ProvideBearer(string bearer) {
  63.             this.bearer = bearer;
  64.         }
  65.  
  66.         public bool LogIn(string username, string password) {
  67.             Uri uri = new Uri(endpoint, "/oauth/token");
  68.             HttpContent content = new FormUrlEncodedContent(new[]
  69.             {
  70.                 new KeyValuePair<string, string>("username", username),
  71.                 new KeyValuePair<string, string>("password", password),
  72.                 new KeyValuePair<string, string>("grant_type", "password")
  73.             });
  74.  
  75.             HttpResponseMessage result = (new HttpClient()).PostAsync(uri, content).Result;
  76.             if (!result.IsSuccessStatusCode) {
  77.                 throw new Exception("Can't connect to the server please retry");
  78.             }
  79.  
  80.             Dictionary<string, string> data =
  81.                 JsonConvert.DeserializeObject<Dictionary<string, string>>(result.Content.ReadAsStringAsync().Result);
  82.  
  83.             ProvideBearer(data["access_token"]);
  84.             return true;
  85.         }
  86.  
  87.         public int DeviceAdd(string name) {
  88.             Uri uri = new Uri(endpoint, "/api/Devices");
  89.             HttpContent content = new FormUrlEncodedContent(new[]
  90.             {
  91.                 new KeyValuePair<string, string>("name", name),
  92.             });
  93.  
  94.             HttpResponseMessage result = (new HttpClient() {
  95.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  96.             }).PostAsync(uri, content).Result;
  97.             if (!result.IsSuccessStatusCode) {
  98.                 throw new Exception("Can't connect to the server please retry");
  99.             }
  100.  
  101.             Dictionary<string, string> data =
  102.                JsonConvert.DeserializeObject<Dictionary<string, string>>(result.Content.ReadAsStringAsync().Result);
  103.  
  104.             return Convert.ToInt32(data["Id"]);
  105.         }
  106.  
  107.         public bool DeviceDelete(int deviceId) {
  108.             Uri uri = new Uri(endpoint, string.Format("/api/Devices/{0}", deviceId));
  109.  
  110.             HttpResponseMessage result = (new HttpClient() {
  111.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  112.             }).DeleteAsync(uri).Result;
  113.             if (!result.IsSuccessStatusCode) {
  114.                 return false;
  115.             }
  116.  
  117.             return true;
  118.         }
  119.  
  120.         public async Task<bool> DeviceCollectionSubmit(int deviceId, string collection) {
  121.             Uri uri = new Uri(endpoint, string.Format("/api/Devices/{0}/Submit", deviceId));
  122.  
  123.             HttpContent content = new StringContent(collection) {
  124.                 Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
  125.             };
  126.  
  127.             HttpResponseMessage result = await (new HttpClient() {
  128.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  129.             }).PostAsync(uri, content);
  130.  
  131.             if (!result.IsSuccessStatusCode) {
  132.                 return false;
  133.             }
  134.  
  135.             return true;
  136.         }
  137.  
  138.         public List<Device> DevicesGet() {
  139.             Uri uri = new Uri(endpoint, "/api/Devices");
  140.  
  141.             HttpResponseMessage result = (new HttpClient() {
  142.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  143.             }).GetAsync(uri).Result;
  144.  
  145.             if (!result.IsSuccessStatusCode) {
  146.                 throw new Exception("Can't connect to the server please retry");
  147.             }
  148.  
  149.             return JsonConvert.DeserializeObject<List<Device>>(result.Content.ReadAsStringAsync().Result);
  150.         }
  151.  
  152.         public int DeviceGetIdByName(string name) {
  153.             Uri uri = new Uri(endpoint, string.Format("/api/Devices?name={0}", name));
  154.             HttpResponseMessage result = (new HttpClient() {
  155.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  156.             }).GetAsync(uri).Result;
  157.  
  158.             if (!result.IsSuccessStatusCode) {
  159.                 throw new Exception("Can't connect to the server please retry");
  160.             }
  161.  
  162.             return JsonConvert.DeserializeObject<Device>(result.Content.ReadAsStringAsync().Result).Id;
  163.         }
  164.  
  165.         public Album DevicesGetAlbum(int albumId) {
  166.             Uri uri = new Uri(endpoint, string.Format("/api/Albums/{0}", albumId));
  167.  
  168.             HttpResponseMessage result = (new HttpClient() {
  169.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  170.             }).GetAsync(uri).Result;
  171.  
  172.             if (!result.IsSuccessStatusCode) {
  173.                 throw new Exception("Can't connect to the server please retry");
  174.             }
  175.  
  176.             return JsonConvert.DeserializeObject<Album>(result.Content.ReadAsStringAsync().Result);
  177.         }
  178.  
  179.         public List<Album> DeviceGetAlbums(int deviceId) {
  180.             Uri uri = new Uri(endpoint, string.Format("/api/Albums?device={0}", deviceId));
  181.  
  182.             HttpResponseMessage result = (new HttpClient() {
  183.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  184.             }).GetAsync(uri).Result;
  185.  
  186.             if (!result.IsSuccessStatusCode) {
  187.                 return null;
  188.             }
  189.  
  190.             return JsonConvert.DeserializeObject<List<Album>>(result.Content.ReadAsStringAsync().Result);
  191.         }
  192.  
  193.         public List<Album> DeviceGetAlbumsFromArtist(int deviceId, int artistId) {
  194.             Uri uri = new Uri(endpoint, string.Format("/api/Albums?device={0}&artist={1}", deviceId, artistId));
  195.  
  196.             HttpResponseMessage result = (new HttpClient() {
  197.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  198.             }).GetAsync(uri).Result;
  199.  
  200.             if (!result.IsSuccessStatusCode) {
  201.                 throw new Exception("Can't connect to the server please retry");
  202.             }
  203.  
  204.             return JsonConvert.DeserializeObject<List<Album>>(result.Content.ReadAsStringAsync().Result);
  205.         }
  206.  
  207.         public List<Track> DeviceGetTracks(int deviceId) {
  208.             Uri uri = new Uri(endpoint, string.Format("/api/Tracks?device={0}", deviceId));
  209.             HttpResponseMessage result = (new HttpClient() {
  210.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  211.             }).GetAsync(uri).Result;
  212.  
  213.             if (!result.IsSuccessStatusCode) {
  214.                 throw new Exception("Can't connect to the server please retry");
  215.             }
  216.  
  217.             return JsonConvert.DeserializeObject<List<Track>>(result.Content.ReadAsStringAsync().Result);
  218.         }
  219.  
  220.         public Track DevicesGetTrack(int trackId) {
  221.             Uri uri = new Uri(endpoint, string.Format("/api/Tracks/{0}", trackId));
  222.             HttpResponseMessage result = (new HttpClient() {
  223.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  224.             }).GetAsync(uri).Result;
  225.  
  226.             if (!result.IsSuccessStatusCode) {
  227.                 throw new Exception("Can't connect to the server please retry");
  228.             }
  229.  
  230.             return JsonConvert.DeserializeObject<Track>(result.Content.ReadAsStringAsync().Result);
  231.         }
  232.  
  233.         public List<Track> DeviceGetTracksFromAlbum(int deviceId, int albumId) {
  234.             Uri uri = new Uri(endpoint, string.Format("/api/Tracks?device={0}&album={1}", deviceId, albumId));
  235.             HttpResponseMessage result = (new HttpClient() {
  236.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  237.             }).GetAsync(uri).Result;
  238.  
  239.             if (!result.IsSuccessStatusCode) {
  240.                 throw new Exception("Can't connect to the server please retry");
  241.             }
  242.  
  243.             return JsonConvert.DeserializeObject<List<Track>>(result.Content.ReadAsStringAsync().Result);
  244.         }
  245.  
  246.         public Artist DevicesGetArtist(int artistId) {
  247.             Uri uri = new Uri(endpoint, string.Format("/api/Artists/{0}", artistId));
  248.             HttpResponseMessage result = (new HttpClient() {
  249.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  250.             }).GetAsync(uri).Result;
  251.  
  252.             if (!result.IsSuccessStatusCode) {
  253.                 throw new Exception("Can't connect to the server please retry");
  254.             }
  255.  
  256.             return JsonConvert.DeserializeObject<Artist>(result.Content.ReadAsStringAsync().Result);
  257.         }
  258.  
  259.         public List<Artist> DeviceGetArtists(int deviceId) {
  260.             Uri uri = new Uri(endpoint, string.Format("/api/Artists?device={0}", deviceId));
  261.             HttpResponseMessage result = (new HttpClient() {
  262.                 DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Bearer", this.bearer) }
  263.             }).GetAsync(uri).Result;
  264.  
  265.             if (!result.IsSuccessStatusCode) {
  266.                 throw new Exception("Can't connect to the server please retry");
  267.             }
  268.  
  269.             return JsonConvert.DeserializeObject<List<Artist>>(result.Content.ReadAsStringAsync().Result);
  270.         }
  271.         public async void ConnectToHub() {
  272.  
  273.             /*hubConnection = new HubConnection(SERVER_URL);
  274.             hubProxy = hubConnection.CreateHubProxy("MusicHub");
  275.             hubConnection.Headers.Add("Authorization", "Bearer " + bearer);
  276.             await hubConnection.Start();
  277.             await hubProxy.Invoke("RegisterClient", CurrentDevice.Id);*/
  278.             socket = IO.Socket(SERVER_URL);
  279.             socket.On(Socket.EVENT_CONNECT, () => {
  280.                 isConnected = true;
  281.             });
  282.             socketInitialize();
  283.             socket.On("reconnect", socketInitialize);
  284.         }
  285.         private void socketInitialize() {
  286.             socket.Emit("authentication", bearer);
  287.             socket.On("authenticated", () => {
  288.                 socket.Emit("RegisterDevice", CurrentDevice.Id);
  289.             });
  290.             socket.On("reconnect", socketInitialize);
  291.  
  292.  
  293.         }
  294.         public void LogOut() {
  295.             bearer = null;
  296.             CurrentDevice = null;
  297.             CurrentArtist = null;
  298.             CurrentAlbum = null;
  299.             CurrentTrack = null;
  300.         }
  301.         public async void PlayTrack() {
  302.  
  303.             // await hubProxy.Invoke("Queue", CurrentDevice.Id, new int[] { CurrentTrack.Id });
  304.             socket.Emit("Queue", CurrentDevice.Id, new int[] { CurrentTrack.Id });
  305.  
  306.         }
  307.         public async void PauseTrack() {
  308.  
  309.             //await hubProxy.Invoke("Pause", CurrentDevice.Id);
  310.             socket.Emit("Pause", CurrentDevice.Id);
  311.  
  312.         }
  313.         public async void NextTrack() {
  314.  
  315.             // await hubProxy.Invoke("Next", CurrentDevice.Id);
  316.             socket.Emit("Next", CurrentDevice.Id);
  317.         }
  318.         public async void SubmitVoteOptions(int[] trackIds) {
  319.  
  320.             //await hubProxy.Invoke("Next", CurrentDevice.Id, trackIds);
  321.             socket.Emit("Next", CurrentDevice.Id, trackIds);
  322.  
  323.         }
  324.         public async void submitVote(int val) {
  325.  
  326.             //await hubProxy.Invoke("Next", CurrentDevice.Id,val);
  327.             socket.Emit("Next", CurrentDevice.Id, val);
  328.  
  329.         }
  330.     }
  331. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement