public SoftwareData(ProjectInfo projectInfo) { start = SoftwareCoUtil.getNowInSeconds(); project = projectInfo; version = SoftwareCoPackage.GetVersion(); os = SoftwareCoPackage.GetOs(); }
public static async void SendHeartbeat(string reason) { string jwt = GetJwt(); bool online = await IsOnlineAsync(); if (online && jwt != null) { string version = Constants.EditorVersion; JsonObject jsonObj = new JsonObject(); jsonObj.Add("version", SoftwareCoPackage.GetVersion()); jsonObj.Add("os", SoftwareCoPackage.GetOs()); jsonObj.Add("pluginId", Constants.PluginId); jsonObj.Add("start", SoftwareCoUtil.getNowInSeconds()); jsonObj.Add("trigger_annotation", reason); jsonObj.Add("hostname", SoftwareCoUtil.getHostname()); string api = "/data/heartbeat"; string jsonData = jsonObj.ToString(); HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(HttpMethod.Post, api, jsonData, jwt); if (!SoftwareHttpManager.IsOk(response)) { Logger.Warning("Code Time: Unable to send heartbeat"); } } }
public void EnsureFileInfoDataIsPresent(string fileName) { JsonObject fileInfoData = new JsonObject(); long start = SoftwareCoUtil.getNowInSeconds(); double offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMinutes; long local_start = start + ((int)offset * 60); if (!source.ContainsKey(fileName)) { fileInfoData.Add("paste", 0); fileInfoData.Add("open", 0); fileInfoData.Add("close", 0); fileInfoData.Add("delete", 0); fileInfoData.Add("add", 0); fileInfoData.Add("netkeys", 0); fileInfoData.Add("length", 0); fileInfoData.Add("lines", 0); fileInfoData.Add("linesAdded", 0); fileInfoData.Add("linesRemoved", 0); fileInfoData.Add("syntax", ""); fileInfoData.Add("start", start); fileInfoData.Add("local_start", local_start); fileInfoData.Add("end", 0); fileInfoData.Add("local_end", 0); source.Add(fileName, fileInfoData); } }
private async Task _IntialisefileMap(string fileName) { foreach (KeyValuePair <string, object> sourceFiles in _softwareData.source) { long end = 0; long local_end = 0; double offset = 0; if (fileName != sourceFiles.Key) { object outend = null; JsonObject fileInfoData = null; fileInfoData = (JsonObject)sourceFiles.Value; fileInfoData.TryGetValue("end", out outend); if (long.Parse(outend.ToString()) == 0) { end = SoftwareCoUtil.getNowInSeconds(); offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMinutes; local_end = end + ((int)offset * 60); _softwareData.addOrUpdateFileInfo(fileName, "end", end); _softwareData.addOrUpdateFileInfo(fileName, "local_end", local_end); } } else { _softwareData.addOrUpdateFileInfo(fileName, "end", 0); _softwareData.addOrUpdateFileInfo(fileName, "local_end", 0); } } }
public void ResetData() { keystrokes = 0; source = new JsonObject(); if (project != null) { project.ResetData(); } start = SoftwareCoUtil.getNowInSeconds(); local_start = 0L; initialized = false; }
public static async Task <bool> IsOnlineAsync() { long nowInSec = SoftwareCoUtil.getNowInSeconds(); long thresholdSeconds = nowInSec - lastOnlineCheck; if (thresholdSeconds > 60) { // 3 second timeout HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(HttpMethod.Get, "/ping", null, 3, null, true /*isOnlineCheck*/); isOnline = SoftwareHttpManager.IsOk(response); lastOnlineCheck = nowInSec; } return(isOnline); }
public static async Task <string> GetAppJwtAsync(bool online) { if (online) { long seconds = SoftwareCoUtil.getNowInSeconds(); HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync( HttpMethod.Get, "/data/apptoken?token=" + seconds, null); if (SoftwareHttpManager.IsOk(response)) { string responseBody = await response.Content.ReadAsStringAsync(); IDictionary <string, object> jsonObj = (IDictionary <string, object>)SimpleJson.DeserializeObject(responseBody); jsonObj.TryGetValue("jwt", out object jwtObj); string app_jwt = (jwtObj == null) ? null : Convert.ToString(jwtObj); return(app_jwt); } } return(null); }
protected static async Task HandleTrackInfoAsync(LocalSpotifyTrackInfo localTrackInfo) { try { if (!SoftwareHttpManager.HasSpotifyAccessToken()) { // initialize the token await SoftwareHttpManager.InitializeSpotifyClientGrantAsync(); } } catch (Exception e) { Logger.Error("Code Time: Unable to access spotify, error: " + e.Message); return; } if (!SoftwareHttpManager.HasSpotifyAccessToken()) { return; } bool hasLocalTrackData = (localTrackInfo.name != null && localTrackInfo.artist != null) ? true : false; bool hasCurrentTrackData = (CurrentTrackInfo != null && CurrentTrackInfo.name != null && CurrentTrackInfo.artist != null) ? true : false; bool isNewTrack = true; if (hasLocalTrackData && hasCurrentTrackData && localTrackInfo.name.Equals(CurrentTrackInfo.name) && localTrackInfo.artist.Equals(CurrentTrackInfo.artist)) { isNewTrack = false; } HttpResponseMessage response = null; try { if (isNewTrack && hasLocalTrackData) { if (hasCurrentTrackData) { // close the previous track CurrentTrackInfo.end = SoftwareCoUtil.getNowInSeconds(); // send it to the app server response = await SoftwareHttpManager.SendRequestAsync( HttpMethod.Post, "/data/music", CurrentTrackInfo.GetAsJson()); } // fill in the missing attributes from the spotify API await SoftwareHttpManager.GetSpotifyTrackInfoAsync(localTrackInfo); // send it to the app server response = await SoftwareHttpManager.SendRequestAsync( HttpMethod.Post, "/data/music", localTrackInfo.GetAsJson()); CurrentTrackInfo = localTrackInfo.Clone(); } else if (hasCurrentTrackData && !hasLocalTrackData) { // send this to close it CurrentTrackInfo.end = SoftwareCoUtil.getNowInSeconds(); // send it to the app server response = await SoftwareHttpManager.SendRequestAsync( HttpMethod.Post, "/data/music", CurrentTrackInfo.GetAsJson()); CurrentTrackInfo = null; } } catch (Exception e) { Logger.Error("Code Time: Unable to process track information, error: " + e.Message); } if (response != null && !SoftwareHttpManager.IsOk(response)) { Logger.Error(response.ToString()); } }
public static async Task GetSpotifyTrackInfoAsync(LocalSpotifyTrackInfo trackInfo) { string webResponse = string.Empty; try { HttpClient client = new HttpClient(); string searchQuery = string.Format("artist:{0} track:{1}", trackInfo.artist, trackInfo.name); searchQuery = WebUtility.UrlEncode(searchQuery); string spotifyUrl = string.Format("https://api.spotify.com/v1/search?q={0}&type=track&limit=2&offset=0", searchQuery); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(spotifyUrl); webRequest.Method = "GET"; webRequest.ContentType = "application/json"; webRequest.Accept = "application/json"; webRequest.Headers.Add("Authorization: Bearer " + token.Access_token); HttpWebResponse resp = (HttpWebResponse)await webRequest.GetResponseAsync(); string json = ""; using (Stream respStr = resp.GetResponseStream()) { using (StreamReader rdr = new StreamReader(respStr, Encoding.UTF8)) { // should get back a string we can turn into a json json = await rdr.ReadToEndAsync(); rdr.Close(); } } IDictionary <string, object> jsonObj = (IDictionary <string, object>)SimpleJson.DeserializeObject(json); jsonObj.TryGetValue("tracks", out object trackObj); IDictionary <string, object> trackDict = (trackObj == null) ? null : (IDictionary <string, object>)trackObj; JsonArray items = null; if (trackDict != null) { trackDict.TryGetValue("items", out object itemsObj); items = (itemsObj == null) ? null : (JsonArray)itemsObj; } // need: id, name (already have it), artist (already have it), state, duration // type = "spotify" // other attributes to send: genre, start, end if (items != null && items.Count > 0) { IDictionary <string, object> trackData = (IDictionary <string, object>)items[0]; trackData.TryGetValue("uri", out object spotifyIdObj); string spotifyId = (spotifyIdObj == null) ? null : Convert.ToString(spotifyIdObj); trackData.TryGetValue("duration_ms", out object durationMsObj); long durationSec = (durationMsObj == null) ? 0L : Convert.ToInt64(durationMsObj); trackInfo.duration = durationSec; trackInfo.type = "spotify"; trackInfo.state = "playing"; trackInfo.genre = ""; trackInfo.id = spotifyId; trackInfo.start = SoftwareCoUtil.getNowInSeconds(); double offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMinutes; trackInfo.local_start = trackInfo.start + ((int)offset * 60); } } catch (Exception tex) { Logger.Error("error: " + tex.Message); } }
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) { } }
// This method is called by the timer delegate. private async void ProcessSoftwareDataTimerCallbackAsync(Object stateInfo) { AutoResetEvent autoEvent = (AutoResetEvent)stateInfo; double offset = 0; long end = 0; long local_end = 0; DateTime now = DateTime.UtcNow; if (_softwareData != null && _softwareData.HasData() && (EnoughTimePassed(now) || timer == null)) { offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMinutes; _softwareData.local_start = _softwareData.start + ((int)offset * 60); _softwareData.offset = Math.Abs((int)offset); if (TimeZone.CurrentTimeZone.DaylightName != null && TimeZone.CurrentTimeZone.DaylightName != TimeZone.CurrentTimeZone.StandardName) { _softwareData.timezone = TimeZone.CurrentTimeZone.DaylightName; } else { _softwareData.timezone = TimeZone.CurrentTimeZone.StandardName; } foreach (KeyValuePair <string, object> sourceFiles in _softwareData.source) { JsonObject fileInfoData = null; fileInfoData = (JsonObject)sourceFiles.Value; object outend; fileInfoData.TryGetValue("end", out outend); if (long.Parse(outend.ToString()) == 0) { end = SoftwareCoUtil.getNowInSeconds(); offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMinutes; local_end = end + ((int)offset * 60); _softwareData.addOrUpdateFileInfo(sourceFiles.Key, "end", end); _softwareData.addOrUpdateFileInfo(sourceFiles.Key, "local_end", local_end); } } try { end = SoftwareCoUtil.getNowInSeconds(); offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMinutes; local_end = end + ((int)offset * 60); _softwareData.end = end; _softwareData.local_end = local_end; } catch (Exception) { } string softwareDataContent = _softwareData.GetAsJson(); Logger.Info("Code Time: sending: " + softwareDataContent); if (SoftwareCoUtil.isTelemetryOn()) { StorePayload(_softwareData); // call the kpm summary /* try * { * Thread.Sleep(1000 * 5); * ProcessFetchDailyKpmTimerCallbackAsync(null); * } * catch (ThreadInterruptedException e) * { * // * }*/ } else { Logger.Info("Code Time metrics are currently paused."); // this.StorePayload(softwareDataContent); } _softwareData.ResetData(); _lastPostTime = now; } }