Esempio n. 1
0
        public static async Task <bool> RefreshAuthorizationTokenIfRequired()
        {
            long lastSetTime = ApplicationSetting.GetLocalSetting_Long("google_token_expiresTime", 0);

            if (lastSetTime != 0)
            {
                long now = DateTime.Now.Ticks / TimeSpan.TicksPerSecond;
                if (now > lastSetTime)
                {
                    // expired
                    string FetchURL = "https://accounts.google.com/o/oauth2/token";

                    var handler = new HttpClientHandler();
                    var req     = new HttpClient(handler);


                    Tuple <string, string> keypair = APIKeys.GetRandomizedClientSecretAndIDPair();
                    string pdata = string.Format("client_id={0}&client_secret={1}&refresh_token={2}&grant_type=refresh_token",
                                                 keypair.Item1,
                                                 keypair.Item2,
                                                 await ApplicationSetting.GetEncryptedLocalStringValueOrDefault("google_refresh_token", ""));
                    StringContent strc = new StringContent(pdata, Encoding.UTF8, "application/x-www-form-urlencoded");
                    try
                    {
                        HttpResponseMessage data = await req.PostAsync(FetchURL, strc);

                        HttpContent content = data.Content;
                        data.EnsureSuccessStatusCode();

                        // {"access_token":"1/fFAGRNJru1FTz70BzhT3Zg","expires_in":3920,"token_type":"Bearer"}
                        JObject token = JObject.Parse(await content.ReadAsStringAsync());

                        /*   string access_token = (string) token["access_token"];
                         * string token_type = (string)token["token_type"];
                         * int expires_in = (int)token["expires_in"];
                         * string refresh_token = (string)token["refresh_token"];
                         *
                         * Debug.WriteLine(ReturnData);*/
                        await ApplicationSetting.SetUpdateLocalValueEncrypted("google_access_token", (string)token["access_token"]);

                        ApplicationSetting.SetLocalSetting("google_token_expiresTime", (long)now + (((long)token["expires_in"] - 5L) * 60L));

                        return(true);
                    }
                    catch (Exception eex)
                    {
                        Debug.WriteLine(eex.ToString());
                    }
                    return(false);
                }
                else
                {
                    // not expired, do nothing.
                }
            }
            return(true);
        }