PageRenderTime 43ms CodeModel.GetById 20ms app.highlight 9ms RepoModel.GetById 11ms app.codeStats 0ms

/src/Server/DeviceHive.API/Controllers/NetworkController.cs

https://github.com/oryol/devicehive-.net
C# | 174 lines | 113 code | 23 blank | 38 comment | 26 complexity | 3bcbeb793f9c6eedfa53458541bfb2b8 MD5 | raw file
  1using System;
  2using System.Collections.Generic;
  3using System.Linq;
  4using System.Net;
  5using System.Web.Http;
  6using DeviceHive.API.Filters;
  7using DeviceHive.API.Mapping;
  8using DeviceHive.Data.Model;
  9using DeviceHive.Data.Repositories;
 10using Newtonsoft.Json.Linq;
 11
 12namespace DeviceHive.API.Controllers
 13{
 14    /// <resource cref="Network" />
 15    public class NetworkController : BaseController
 16    {
 17        /// <name>list</name>
 18        /// <summary>
 19        /// Gets list of device networks.
 20        /// <para>If caller belongs to the Client user role, the result list is limited to networks the user has access to.</para>
 21        /// </summary>
 22        /// <returns cref="Network">If successful, this method returns array of <see cref="Network"/> resources in the response body.</returns>
 23        [AuthorizeUser]
 24        public JArray Get()
 25        {
 26            var networks = RequestContext.CurrentUser.Role == (int)UserRole.Client ?
 27                DataContext.Network.GetByUser(RequestContext.CurrentUser.ID) :
 28                DataContext.Network.GetAll();
 29
 30            return new JArray(networks.Select(n => Mapper.Map(n)));
 31        }
 32
 33        /// <name>get</name>
 34        /// <summary>
 35        /// Gets information about device network and its devices.
 36        /// </summary>
 37        /// <param name="id">Network identifier.</param>
 38        /// <returns cref="Network">If successful, this method returns a <see cref="Network"/> resource in the response body.</returns>
 39        /// <response>
 40        ///     <parameter name="devices" type="array" cref="Device">Array of devices registered in the current network.</parameter>
 41        ///     <parameter name="devices[].network" mode="remove" />
 42        /// </response>
 43        [AuthorizeUser]
 44        public JObject Get(int id)
 45        {
 46            var network = DataContext.Network.Get(id);
 47            if (network == null || !IsNetworkAccessible(network.ID))
 48                ThrowHttpResponse(HttpStatusCode.NotFound, "Network not found!");
 49
 50            var jNetwork = Mapper.Map(network);
 51
 52            var deviceMapper = GetMapper<Device>();
 53            var devices = DataContext.Device.GetByNetwork(id);
 54            jNetwork["devices"] = new JArray(devices.Select(d => deviceMapper.Map(d)));
 55            return jNetwork;
 56        }
 57
 58        /// <name>insert</name>
 59        /// <summary>
 60        /// Creates new device network.
 61        /// </summary>
 62        /// <param name="json" cref="Network">In the request body, supply a <see cref="Network"/> resource.</param>
 63        /// <returns cref="Network">If successful, this method returns a <see cref="Network"/> resource in the response body.</returns>
 64        [HttpCreatedResponse]
 65        [AuthorizeUser(Roles = "Administrator")]
 66        public JObject Post(JObject json)
 67        {
 68            var network = Mapper.Map(json);
 69            Validate(network);
 70            
 71            if (DataContext.Network.Get(network.Name) != null)
 72                ThrowHttpResponse(HttpStatusCode.Forbidden, "Network with such name already exists!");
 73            if (network.Key != null && DataContext.Network.GetByKey(network.Key) != null)
 74                ThrowHttpResponse(HttpStatusCode.Forbidden, "Network with such key already exists!");
 75            
 76            DataContext.Network.Save(network);
 77            return Mapper.Map(network);
 78        }
 79
 80        /// <name>update</name>
 81        /// <summary>
 82        /// Updates an existing device network.
 83        /// </summary>
 84        /// <param name="id">Network identifier.</param>
 85        /// <param name="json" cref="Network">In the request body, supply a <see cref="Network"/> resource.</param>
 86        /// <returns cref="Network">If successful, this method returns a <see cref="Network"/> resource in the response body.</returns>
 87        /// <request>
 88        ///     <parameter name="name" required="false" />
 89        /// </request>
 90        [AuthorizeUser(Roles = "Administrator")]
 91        public JObject Put(int id, JObject json)
 92        {
 93            var network = DataContext.Network.Get(id);
 94            if (network == null)
 95                ThrowHttpResponse(HttpStatusCode.NotFound, "Network not found!");
 96
 97            Mapper.Apply(network, json);
 98            Validate(network);
 99
100            var existing = DataContext.Network.Get(network.Name);
101            if (existing != null && existing.ID != network.ID)
102                ThrowHttpResponse(HttpStatusCode.Forbidden, "Network with such name already exists!");
103
104            if (network.Key != null)
105            {
106                existing = DataContext.Network.GetByKey(network.Key);
107                if (existing != null && existing.ID != network.ID)
108                    ThrowHttpResponse(HttpStatusCode.Forbidden, "Network with such key already exists!");
109            }
110
111            DataContext.Network.Save(network);
112            return Mapper.Map(network);
113        }
114
115        /// <name>delete</name>
116        /// <summary>
117        /// Deletes an existing device network.
118        /// </summary>
119        /// <param name="id">Network identifier.</param>
120        [HttpNoContentResponse]
121        [AuthorizeUser(Roles = "Administrator")]
122        public void Delete(int id)
123        {
124            DataContext.Network.Delete(id);
125        }
126
127        private IJsonMapper<Network> Mapper
128        {
129            get
130            {
131                var mapper = GetMapper<Network>();
132                if (RequestContext.CurrentUser.Role == (int)UserRole.Client)
133                    return new ClientNetworkMapper(mapper);
134                return mapper;
135            }
136        }
137
138        private class ClientNetworkMapper : IJsonMapper<Network>
139        {
140            private IJsonMapper<Network> _mapper;
141
142            #region Constructor
143
144            public ClientNetworkMapper(IJsonMapper<Network> mapper)
145            {
146                if (mapper == null)
147                    throw new ArgumentNullException("mapper");
148
149                _mapper = mapper;
150            }
151            #endregion
152
153            #region IJsonMapper<Network> Members
154
155            public JObject Map(Network entity)
156            {
157                var jObject = _mapper.Map(entity);
158                jObject.Remove("key"); // do not expose network key to clients
159                return jObject;
160            }
161
162            public Network Map(JObject json)
163            {
164                return _mapper.Map(json);
165            }
166
167            public void Apply(Network entity, JObject json)
168            {
169                _mapper.Apply(entity, json);
170            }
171            #endregion
172        }
173    }
174}