private async void InitializeUserInfo()
        {
            bool online = await SoftwareUserSession.IsOnlineAsync();

            bool softwareSessionFileExists = SoftwareCoUtil.softwareSessionFileExists();
            bool jwtExists       = SoftwareCoUtil.jwtExists();
            bool initializedUser = false;

            if (!softwareSessionFileExists || !jwtExists)
            {
                string result = await SoftwareUserSession.CreateAnonymousUserAsync(online);

                if (result != null)
                {
                    initializedUser = true;
                }
            }

            SoftwareUserSession.UserStatus status = await SoftwareUserSession.GetUserStatusAsync(true);

            SoftwareLoginCommand.UpdateEnabledState(status);

            if (initializedUser)
            {
                LaunchLoginPrompt();
            }

            if (online)
            {
                fetchSessionSummaryInfoAsync();

                // send heartbeat
                SoftwareUserSession.SendHeartbeat("INITIALIZED");
            }
        }
예제 #2
0
        public static async void launchLogin()
        {
            bool isOnline = await SoftwareUserSession.IsOnlineAsync();

            string jwt = SoftwareUserSession.GetJwt();

            if (jwt == null && isOnline)
            {
                // initialize the anon flow
                await SoftwareUserSession.CreateAnonymousUserAsync(isOnline);
            }
            jwt = SoftwareUserSession.GetJwt();
            string url = Constants.url_endpoint + "/onboarding?token=" + jwt;

            if (!isOnline)
            {
                // just show the app home, which should end up showing up with a no connection message
                url = Constants.url_endpoint;
            }

            Process.Start(url);

            if (!isOnline)
            {
                return;
            }

            if (!SoftwareUserSession.checkingLoginState)
            {
                SoftwareUserSession.RefetchUserStatusLazily(12);
            }
        }
예제 #3
0
        public static async void launchLogin(string loginType)
        {
            try
            {
                string jwt = FileManager.getItemAsString("jwt");
                string url = "";
                if (loginType.Equals("google"))
                {
                    url = Constants.api_endpoint + "/auth/google?token=" + jwt + "&plugin=codetime&redirect=" + Constants.url_endpoint;
                }
                else if (loginType.Equals("github"))
                {
                    url = Constants.api_endpoint + "/auth/github?token=" + jwt + "&plugin=codetime&redirect=" + Constants.url_endpoint;
                }
                else
                {
                    url = Constants.url_endpoint + "/email-signup?token=" + jwt + "&plugin=codetime&ath=software";
                }

                Process.Start(url);

                if (!SoftwareUserSession.checkingLoginState)
                {
                    SoftwareUserSession.RefetchUserStatusLazily(40);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("launchLogin, error : " + ex.Message, ex);
            }
        }
        public static async void SendOfflinePluginBatchData()
        {
            string MethodName = "SendOfflineData";

            Logger.Info(DateTime.Now.ToString());
            bool online = await SoftwareUserSession.IsOnlineAsync();

            if (!online)
            {
                return;
            }

            int batch_limit = 5;
            HttpResponseMessage response    = null;
            string        jsonData          = "";
            List <string> offlinePluginData = FileManager.GetOfflinePayloadList();
            List <string> batchList         = new List <string>();

            if (offlinePluginData != null && offlinePluginData.Count > 0)
            {
                for (int i = 0; i < offlinePluginData.Count; i++)
                {
                    string line = offlinePluginData[i];
                    if (i >= batch_limit)
                    {
                        // send this batch off
                        jsonData = "[" + string.Join(",", batchList) + "]";
                        response = await SoftwareHttpManager.SendRequestAsync(HttpMethod.Post, "/data/batch", jsonData);

                        if (!SoftwareHttpManager.IsOk(response))
                        {
                            // there was an error, don't delete the offline data
                            return;
                        }
                        batchList.Clear();
                    }
                    batchList.Add(line);
                }

                if (batchList.Count > 0)
                {
                    jsonData = "[" + string.Join(",", batchList) + "]";
                    response = await SoftwareHttpManager.SendRequestAsync(HttpMethod.Post, "/data/batch", jsonData);

                    if (!SoftwareHttpManager.IsOk(response))
                    {
                        // there was an error, don't delete the offline data
                        return;
                    }
                }

                // delete the file
                File.Delete(FileManager.getSoftwareDataStoreFile());
            }
        }
        private void ProcessHourlyJobs(Object stateInfo)
        {
            SoftwareUserSession.SendHeartbeat("HOURLY");

            string dir = getSolutionDirectory();

            if (dir != null)
            {
                _softwareRepoUtil.GetHistoricalCommitsAsync(dir);
            }
        }
        private static async Task <SessionSummaryResult> GetSessionSummaryStatusAsync(bool forceRefresh = false)
        {
            SessionSummaryResult sessionSummaryResult = new SessionSummaryResult();

            _sessionSummary = getSessionSummayData();

            //if (SoftwareCoUtil.SessionSummaryFileExists())
            //{

            if (_sessionSummary.currentDayMinutes == 0 || forceRefresh)
            {
                bool online = await SoftwareUserSession.IsOnlineAsync();

                if (!online)
                {
                    sessionSummaryResult.sessionSummary = _sessionSummary;
                    sessionSummaryResult.status         = "OK";
                    updateStatusBarWithSummaryData();
                    return(sessionSummaryResult);
                }
                HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(HttpMethod.Get, "/sessions/summary", null);

                if (SoftwareHttpManager.IsOk(response))
                {
                    string responseBody = await response.Content.ReadAsStringAsync();

                    IDictionary <string, object> jsonObj = (IDictionary <string, object>)SimpleJson.DeserializeObject(responseBody);
                    _sessionSummary = DictionaryToObject <SessionSummary>(jsonObj);

                    saveSessionSummaryToDisk(_sessionSummary);

                    updateStatusBarWithSummaryData();

                    sessionSummaryResult.sessionSummary = _sessionSummary;
                    sessionSummaryResult.status         = "OK";
                }
            }
            else
            {
                updateStatusBarWithSummaryData();
            }

            //}
            //else
            //{
            //    updateStatusBarWithSummaryData();
            //}

            sessionSummaryResult.sessionSummary = _sessionSummary;
            sessionSummaryResult.status         = "OK";
            return(sessionSummaryResult);
        }
        private async Task InitializeUserInfoAsync()
        {
            try
            {
                string MethodName = "InitializeUserInfo";
                Logger.FileLog("Initializing User", MethodName);
                bool online = await SoftwareUserSession.IsOnlineAsync();

                bool   softwareSessionFileExists = FileManager.softwareSessionFileExists();
                object jwt = FileManager.getItem("jwt");
                if (!softwareSessionFileExists || jwt == null || jwt.ToString().Equals(""))
                {
                    string result = await SoftwareUserSession.CreateAnonymousUserAsync(online);
                }

                // check if the "name" is set. if not, get the user
                string name = FileManager.getItemAsString("name");
                if (name == null || name.Equals(""))
                {
                    await SoftwareUserSession.IsLoggedOn(online);

                    SoftwareLoginCommand.UpdateEnabledState(true);
                    SoftwareLaunchCommand.UpdateEnabledState(true);
                }

                long sessionTresholdSeconds = FileManager.getItemAsLong("sessionThresholdInSec");
                if (sessionTresholdSeconds == 0)
                {
                    // update the session threshold in seconds config
                    FileManager.setNumericItem("sessionThresholdInSec", Constants.DEFAULT_SESSION_THRESHOLD_SECONDS);
                }

                if (online)
                {
                    // send heartbeat
                    SoftwareUserSession.SendHeartbeat("INITIALIZED");
                }

                // fetch the session summary
                WallclockManager.Instance.UpdateSessionSummaryFromServerAsync();
            }
            catch (Exception ex)
            {
                Logger.Error("Error Initializing UserInfo", ex);
            }
        }
        private async void SendOfflineData(object stateinfo)
        {
            Logger.Info(DateTime.Now.ToString());
            bool online = await SoftwareUserSession.IsOnlineAsync();

            if (!online)
            {
                return;
            }

            string datastoreFile = SoftwareCoUtil.getSoftwareDataStoreFile();

            if (File.Exists(datastoreFile))
            {
                // get the content
                string[] lines = File.ReadAllLines(datastoreFile);

                if (lines != null && lines.Length > 0)
                {
                    List <String> jsonLines = new List <string>();
                    foreach (string line in lines)
                    {
                        if (line != null && line.Trim().Length > 0)
                        {
                            jsonLines.Add(line);
                        }
                    }
                    string jsonContent           = "[" + string.Join(",", jsonLines) + "]";
                    HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(HttpMethod.Post, "/data/batch", jsonContent);

                    if (SoftwareHttpManager.IsOk(response))
                    {
                        // delete the file
                        File.Delete(datastoreFile);
                    }
                }
            }

            ÇlearSessionSummaryData();

            fetchSessionSummaryInfoAsync(true);
        }
        private void ProcessRepoJobs(Object stateInfo)
        {
            try
            {
                SoftwareUserSession.SendHeartbeat("HOURLY");

                string dir = DocEventManager._solutionDirectory;

                if (dir != null)
                {
                    _softwareRepoUtil.GetHistoricalCommitsAsync(dir);

                    _softwareRepoUtil.ProcessRepoMembers(dir);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ProcessHourlyJobs, error: " + ex.Message, ex);
            }
        }
        public static async Task <UserStatus> GetUserStatusAsync(bool isInitialCall)
        {
            bool online = await IsOnlineAsync();

            bool softwareSessionFileExists = SoftwareCoUtil.softwareSessionFileExists();
            bool jwtExists = SoftwareCoUtil.jwtExists();

            if (!isInitialCall && isOnline && !jwtExists)
            {
                await SoftwareUserSession.CreateAnonymousUserAsync(online);
            }

            bool loggedIn = await IsLoggedOn(online);

            UserStatus currentUserStatus = new UserStatus();

            currentUserStatus.loggedIn = loggedIn;

            if (online && loggedInCacheState != loggedIn)
            {
                // change in logged in state, send heatbeat and fetch kpm
                SendHeartbeat("STATE_CHANGE:LOGGED_IN:" + loggedIn);

                try
                {
                    Thread.Sleep(1000);
                    SoftwareCoPackage.fetchSessionSummaryInfoAsync();
                }
                catch (ThreadInterruptedException e)
                {
                    //
                }
            }

            loggedInCacheState = loggedIn;

            SoftwareLaunchCommand.UpdateEnabledState(currentUserStatus);
            SoftwareLoginCommand.UpdateEnabledState(currentUserStatus);

            return(currentUserStatus);
        }
        /*private void StorePayload(string softwareDataContent)
         * {
         *  string datastoreFile = SoftwareCoUtil.getSoftwareDataStoreFile();
         *  // append to the file
         *  File.AppendAllText(datastoreFile, softwareDataContent + Environment.NewLine);
         * }*/

        private async void LaunchLoginPrompt()
        {
            await JoinableTaskFactory.SwitchToMainThreadAsync(DisposalToken);

            bool online = await SoftwareUserSession.IsOnlineAsync();

            if (online)
            {
                string       msg     = "To see your coding data in Code Time, please log in to your account.";
                const string caption = "Code Time";
                var          result  = MessageBox.Show(msg, caption,
                                                       MessageBoxButtons.YesNo,
                                                       MessageBoxIcon.Question);

                // If the no button was pressed ...
                if (result == DialogResult.Yes)
                {
                    // launch the browser
                    SoftwareCoUtil.launchLogin();
                }
            }
        }
        public static async void RefetchUserStatusLazily(int tryCountUntilFoundUser)
        {
            try
            {
                bool loggedIn = await IsLoggedOn(true);

                if (!loggedIn && tryCountUntilFoundUser > 0)
                {
                    tryCountUntilFoundUser -= 1;

                    Task.Delay(1000 * 10).ContinueWith((task) => { RefetchUserStatusLazily(tryCountUntilFoundUser); });
                }
                else
                {
                    checkingLoginState = false;
                    if (loggedIn)
                    {
                        SoftwareLoginCommand.UpdateEnabledState(true);
                        SoftwareLaunchCommand.UpdateEnabledState(true);
                        // show they've logged on
                        string       msg     = "Successfully logged on to Code Time.";
                        const string caption = "Code Time";
                        MessageBox.Show(msg, caption, MessageBoxButtons.OK);
                        SoftwareUserSession.SendHeartbeat("STATE_CHANGE: LOGGED_IN:true");

                        // fetch the session summary to get the user's averages
                        WallclockManager.Instance.UpdateSessionSummaryFromServerAsync();

                        SoftwareCoPackage.SendOfflinePluginBatchData();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("RefetchUserStatusLazily ,error : " + ex.Message, ex);
            }
        }
예제 #13
0
        public static async Task <HttpResponseMessage> SendRequestAsync(HttpMethod httpMethod, string uri, string optionalPayload, int timeout, string jwt = null, bool isOnlineCheck = false)
        {
            if (!SoftwareCoUtil.isTelemetryOn())
            {
                return(null);
            }

            if (!isOnlineCheck && !SoftwareUserSession.isOnline)
            {
                return(null);
            }

            HttpClient client = new HttpClient
            {
                Timeout = TimeSpan.FromSeconds(timeout)
            };
            var cts = new CancellationTokenSource();
            HttpResponseMessage response = null;

            if (jwt == null)
            {
                object jwtObj = SoftwareUserSession.GetJwt();
                if (jwtObj != null)
                {
                    jwt = (string)jwtObj;
                }
            }
            if (jwt != null)
            {
                // add the authorizationn
                client.DefaultRequestHeaders.Add("Authorization", jwt);
            }
            HttpContent contentPost = null;

            try
            {
                if (optionalPayload != null)
                {
                    contentPost = new StringContent(optionalPayload, Encoding.UTF8, "application/json");
                }
            } catch (Exception e)
            {
                NotifyPostException(e);
            }
            bool isPost = (httpMethod.Equals(HttpMethod.Post));

            try
            {
                string endpoint = Constants.api_endpoint + "" + uri;
                if (isPost)
                {
                    response = await client.PostAsync(endpoint, contentPost, cts.Token);
                }
                else
                {
                    response = await client.GetAsync(endpoint, cts.Token);
                }
            }
            catch (HttpRequestException e)
            {
                if (isPost)
                {
                    NotifyPostException(e);
                }
            }
            catch (TaskCanceledException e)
            {
                if (e.CancellationToken == cts.Token)
                {
                    // triggered by the caller
                    if (isPost)
                    {
                        NotifyPostException(e);
                    }
                }
                else
                {
                    // a web request timeout (possibly other things!?)
                    Logger.Info("We are having trouble receiving a response from Software.com");
                }
            }
            catch (Exception e)
            {
                if (isPost)
                {
                    NotifyPostException(e);
                }
            }
            finally
            {
            }
            return(response);
        }
예제 #14
0
        private async Task FetchCodeTimeDashboardAsync()
        {
            string summaryContent  = "";
            string summaryInfoFile = FileManager.getSessionSummaryInfoFile();

            bool online = await SoftwareUserSession.IsOnlineAsync();


            HttpResponseMessage resp =
                await SoftwareHttpManager.SendDashboardRequestAsync(HttpMethod.Get, "/dashboard?showMusic=false&showGit=false&showRank=false&showToday=false");

            if (SoftwareHttpManager.IsOk(resp))
            {
                summaryContent += await resp.Content.ReadAsStringAsync();
            }
            else
            {
                summaryContent = NO_DATA;
            }


            if (File.Exists(summaryInfoFile))
            {
                File.SetAttributes(summaryInfoFile, FileAttributes.Normal);
            }

            try
            {
                File.WriteAllText(summaryInfoFile, summaryContent, System.Text.Encoding.UTF8);
            }
            catch (Exception e)
            {
            }

            string dashboardFile    = FileManager.getDashboardFile();
            string dashboardContent = "";
            string suffix           = SoftwareCoUtil.CreateDateSuffix(DateTime.Now);
            string formattedDate    = DateTime.Now.ToString("ddd, MMM ") + suffix + DateTime.Now.ToString(" h:mm tt");

            dashboardContent  = "CODE TIME          " + "(Last updated on " + formattedDate + " )";
            dashboardContent += "\n\n";

            string todayDate  = DateTime.Now.ToString("ddd, MMM ") + suffix;
            string today_date = "Today " + "(" + todayDate + ")";

            dashboardContent += SoftwareCoUtil.getSectionHeader(today_date);

            SessionSummary  _sessionSummary = SessionSummaryManager.Instance.GetSessionSummayData();
            CodeTimeSummary ctSummary       = TimeDataManager.Instance.GetCodeTimeSummary();

            string codeTimeMinutes = SoftwareCoUtil.HumanizeMinutes(ctSummary.codeTimeMinutes);

            dashboardContent += SoftwareCoUtil.getDashboardRow("Code time today", codeTimeMinutes);
            string activeCodeTimeMinutes = SoftwareCoUtil.HumanizeMinutes(ctSummary.activeCodeTimeMinutes);

            dashboardContent += SoftwareCoUtil.getDashboardRow("Active code time today", activeCodeTimeMinutes);
            if (_sessionSummary != null)
            {
                string averageTime = SoftwareCoUtil.HumanizeMinutes(_sessionSummary.averageDailyMinutes);

                String liveshareTime = "";
                //if (_sessionSummary.liveshareMinutes != 0)
                //{
                //    liveshareTime = SoftwareCoUtil.HumanizeMinutes(_sessionSummary.liveshareMinutes);
                //}

                dashboardContent += SoftwareCoUtil.getDashboardRow("90-day avg", averageTime);
                //if (liveshareTime != "0")
                //{
                //    dashboardContent += SoftwareCoUtil.getDashboardRow("Live Share", liveshareTime);
                //}
                dashboardContent += "\n";
            }

            if (FileManager.SessionSummaryInfoFileExists())
            {
                string SummaryData = FileManager.getSessionSummaryInfoFileData();
                dashboardContent += SummaryData;
            }


            if (File.Exists(dashboardFile))
            {
                File.SetAttributes(dashboardFile, FileAttributes.Normal);
            }
            try
            {
                File.WriteAllText(dashboardFile, dashboardContent, System.Text.Encoding.UTF8);
            }
            catch (Exception e)
            {
            }
        }
예제 #15
0
        public static bool jwtExists()
        {
            string jwt = SoftwareUserSession.GetJwt();

            return(jwt != null && !jwt.Equals(""));
        }
        private static async Task FetchCodeTimeDashboardAsync(SessionSummary _sessionSummary)
        {
            string summaryContent  = "";
            string summaryInfoFile = SoftwareCoUtil.getSessionSummaryInfoFile();

            bool online = await SoftwareUserSession.IsOnlineAsync();

            long diff = SoftwareCoUtil.getNowInSeconds() - lastDashboardFetchTime;

            if (lastDashboardFetchTime == 0 || diff >= day_in_sec || !online)
            {
                if (!online)
                {
                    lastDashboardFetchTime = 0;
                }
                else
                {
                    lastDashboardFetchTime = SoftwareCoUtil.getNowInSeconds();
                }

                HttpResponseMessage resp =
                    await SoftwareHttpManager.SendDashboardRequestAsync(HttpMethod.Get, "/dashboard?showMusic=false&showGit=false&showRank=false&showToday=false");

                if (SoftwareHttpManager.IsOk(resp))
                {
                    summaryContent += await resp.Content.ReadAsStringAsync();
                }
                else
                {
                    summaryContent = NO_DATA;
                }


                if (File.Exists(summaryInfoFile))
                {
                    File.SetAttributes(summaryInfoFile, FileAttributes.Normal);
                }

                try
                {
                    File.WriteAllText(summaryInfoFile, summaryContent);
                    File.SetAttributes(summaryInfoFile, FileAttributes.ReadOnly);
                }
                catch (Exception e)
                {
                }
            }
            string dashboardFile    = SoftwareCoUtil.getDashboardFile();
            string dashboardContent = "";
            string suffix           = SoftwareCoUtil.CreateDateSuffix(DateTime.Now);
            string formattedDate    = DateTime.Now.ToString("ddd, MMM ") + suffix + DateTime.Now.ToString(" h:mm tt");

            dashboardContent  = "CODE TIME          " + "(Last updated on " + formattedDate + " )";
            dashboardContent += "\n\n";

            string todayDate  = DateTime.Now.ToString("ddd, MMM ") + suffix;
            string today_date = "Today " + "(" + todayDate + ")";

            dashboardContent += SoftwareCoUtil.getSectionHeader(today_date);

            if (_sessionSummary != null)
            {
                string averageTime     = SoftwareCoUtil.HumanizeMinutes(_sessionSummary.averageDailyMinutes);
                string hoursCodedToday = SoftwareCoUtil.HumanizeMinutes(_sessionSummary.currentDayMinutes);
                String liveshareTime   = "";
                //if (_sessionSummary.liveshareMinutes != 0)
                //{
                //    liveshareTime = SoftwareCoUtil.HumanizeMinutes(_sessionSummary.liveshareMinutes);
                //}
                dashboardContent += SoftwareCoUtil.getDashboardRow("Hours Coded", hoursCodedToday);
                dashboardContent += SoftwareCoUtil.getDashboardRow("90-day avg", averageTime);
                //if (liveshareTime != "0")
                //{
                //    dashboardContent += SoftwareCoUtil.getDashboardRow("Live Share", liveshareTime);
                //}
                dashboardContent += "\n";
            }

            if (SoftwareCoUtil.SessionSummaryInfoFileExists())
            {
                string SummaryData = SoftwareCoUtil.getSessionSummaryInfoFileData();
                dashboardContent += SummaryData;
            }


            if (File.Exists(dashboardFile))
            {
                File.SetAttributes(dashboardFile, FileAttributes.Normal);
            }
            try
            {
                //SoftwareCoUtil.WriteToFileThreadSafe(dashboardContent, dashboardFile);
                File.WriteAllText(dashboardFile, dashboardContent);
                File.SetAttributes(dashboardFile, FileAttributes.ReadOnly);
            }
            catch (Exception e)
            {
            }
        }
 public async void UpdateUserStatus(Object stateInfo)
 {
     SoftwareUserSession.UserStatus status = await SoftwareUserSession.GetUserStatusAsync(false);
 }