/// <summary>
        /// API client authentication.
        /// If authentication fails, use the errorCode and errorDescription attributes on the response dictionary to get error details.
        /// If authentication succeeds, SessionId is set to the Session ID.
        /// The Session ID is reusable so it's recommended that you save this value and use it for further API calls.
        /// Once you are done using the API, call ZelloAPI.Logout() to end the session and invalidate Session ID.
        /// </summary>
        /// <param name="username">administrative username.</param>
        /// <param name="password">administrative password.</param>
        public async Task <ZelloAPIResult> Authenticate(string username, string password)
        {
            ZelloAPIResult result = await callAPI("user/gettoken", HTTPMethod.GET, null).ConfigureAwait(false);

            ZelloAPIResult returnResult;

            if (!result.Success)
            {
                returnResult = new ZelloAPIResult(false, result.Response, null);
                return(returnResult);
            }

            if (result.Response == null)
            {
                returnResult = new ZelloAPIResult(false, null, null);
                return(returnResult);
            }

            var token = (string)result.Response["token"];

            SessionId = (string)result.Response["sid"];

            if (apiKey == null)
            {
                returnResult = new ZelloAPIResult(false, result.Response, null);
                return(returnResult);
            }

            string hashedPassword = MD5Hash(MD5Hash(password) + token + apiKey);
            string parameters     = "username="******"&password="******"user/login", HTTPMethod.POST, parameters);

            return(returnResult);
        }
Exemple #2
0
        async Task authenticate(string username, string password)
        {
            ZelloAPIResult result = null;

            try
            {
                result = await api.Authenticate(username, password);
            }
            catch (System.UriFormatException)
            {
            }

            if (result != null)
            {
                Console.WriteLine("Authenticate: " + result.Success);

                if (result.Success)
                {
                    await callOtherMethods();
                }
                else
                {
                    Console.WriteLine("Input the correct credentials for your network in Program.cs");
                }
            }
            else
            {
                Console.WriteLine("Input the correct credentials for your network in Program.cs");
            }
        }
        /// <summary>
        /// Ends session identified by sessionId.
        /// Use this method to terminate the API session.
        /// See ZelloAPI.Authenticate().
        /// </summary>
        public async Task <ZelloAPIResult> Logout()
        {
            ZelloAPIResult result = await callAPI("user/logout", HTTPMethod.GET, null);

            SessionId = null;

            return(result);
        }
        async Task <ZelloAPIResult> callAPI(string command, HTTPMethod method, string parameters)
        {
            ZelloAPIResult returnResult;

            string prefix = "http://";

            if (host.Contains("http://") || host.Contains("https://"))
            {
                prefix = "";
            }
            string urlString = prefix + host + "/" + command;

            if (SessionId != null)
            {
                urlString += "?sid=" + SessionId;
            }

            LastURL = urlString;

            var request = (HttpWebRequest)WebRequest.Create(urlString);

            request.Method = convertHTTPMethodToString(method);

            if (parameters != null)
            {
                request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";

                byte[] postData = Encoding.UTF8.GetBytes(parameters);

                using (var requestStream = await Task <Stream> .Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, request))
                {
                    requestStream.Write(postData, 0, postData.Length);
                }
            }

            try
            {
                // Pick up the response:
                using (var response = (HttpWebResponse)(await Task <WebResponse> .Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
                {
                    var    reader = new StreamReader(response.GetResponseStream());
                    string result = reader.ReadToEnd();
                    var    json   = (Dictionary <string, object>) new JavaScriptSerializer().DeserializeObject(result);

                    bool success = json != null && json["code"].Equals("200");
                    returnResult = new ZelloAPIResult(success, json, null);
                }
            }
            catch (WebException exception)
            {
                returnResult = new ZelloAPIResult(false, null, exception);
            }

            return(returnResult);
        }
Exemple #5
0
        async Task callOtherMethods()
        {
            ZelloAPIResult result = await api.GetUsers(null, false, null, null, null);

            Console.WriteLine("GetUsers: " + result.Success);
            if (result.Success)
            {
                Object[] arr = (Object[])result.Response["users"];
                foreach (Object obj in arr)
                {
                    dictionaryOut((Dictionary <string, object>)obj);
                }
            }

            result = await api.GetChannels(null, null, null);

            Console.WriteLine("GetChannels: " + result.Success);
            if (result.Success)
            {
                Object[] arr = (Object[])result.Response["channels"];
                foreach (Object obj in arr)
                {
                    dictionaryOut((Dictionary <string, object>)obj);
                }
            }

            // Add or update user
            var userDictionary = new Dictionary <string, string>();

            userDictionary.Add("name", "zelloapi_test");
            userDictionary.Add("password", MD5Hash("test"));
            userDictionary.Add("email", "*****@*****.**");
            userDictionary.Add("full_name", "API Test 'На здоровье'"); // UTF-8 is fully supported
            result = await api.SaveUser(userDictionary);

            Console.WriteLine("SaveUser: "******"GetUsers: " + result.Success);
            if (result.Success)
            {
                Object[] arr = (Object[])result.Response["users"];
                foreach (Object obj in arr)
                {
                    dictionaryOut((Dictionary <string, object>)obj);
                }
            }

            // Add channel
            result = await api.AddChannel("Test channel", null, null);

            Console.WriteLine("AddChannel: " + result.Success);

            // Add user to a channel
            var users = new ArrayList();

            users.Add("zelloapi_test");
            result = await api.AddToChannel("Test channel", users);

            Console.WriteLine("AddToChannel: " + result.Success);

            // List channels again
            result = await api.GetChannels(null, null, null);

            Console.WriteLine("GetChannels: " + result.Success);
            if (result.Success)
            {
                Object[] arr = (Object[])result.Response["channels"];
                foreach (Object obj in arr)
                {
                    dictionaryOut((Dictionary <string, object>)obj);
                }
            }

            // Create channel role

            var channelRoleDictionary = new Dictionary <string, object>();

            channelRoleDictionary.Add("listen_only", false);
            channelRoleDictionary.Add("no_disconnect", true);
            channelRoleDictionary.Add("allow_alerts", false);
            var toArray = new string[0];

            channelRoleDictionary.Add("to", toArray);
            result = await api.SaveChannelRole("Test channel", "Dispatcher", channelRoleDictionary);

            Console.WriteLine("SaveChannelRole: " + result.Success);

            channelRoleDictionary = new Dictionary <string, object>();
            channelRoleDictionary.Add("listen_only", false);
            channelRoleDictionary.Add("no_disconnect", false);
            channelRoleDictionary.Add("allow_alerts", true);
            toArray = new string[] { "Dispatcher" };
            channelRoleDictionary.Add("to", toArray);
            result = await api.SaveChannelRole("Test channel", "Driver", channelRoleDictionary);

            Console.WriteLine("SaveChannelRole: " + result.Success);

            // List channel roles
            result = await api.GetChannelsRoles("Test channel");

            Console.WriteLine("GetChannelsRoles: " + result.Success);
            if (result.Success)
            {
                Object[] arr = (Object[])result.Response["roles"];
                foreach (Object obj in arr)
                {
                    dictionaryOut((Dictionary <string, object>)obj);
                }
            }

            // Remove the channel
            var channelNames = new ArrayList();

            channelNames.Add("Test channel");
            result = await api.DeleteChannels(channelNames);

            // Delete the user we just added
            users = new ArrayList();
            users.Add("zelloapi_test");
            result = await api.DeleteUsers(users);

            // List users one last time -- the new user is gone
            result = await api.GetUsers(null, false, null, null, null);

            Console.WriteLine("GetUsers: " + result.Success);
            if (result.Success)
            {
                Object[] arr = (Object[])result.Response["users"];
                foreach (Object obj in arr)
                {
                    dictionaryOut((Dictionary <string, object>)obj);
                }
            }
        }