public static async Task <string> GetAppJwtAsync(bool online)
        {
            try
            {
                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, new Dictionary <string, object>());
                        jsonObj.TryGetValue("jwt", out object jwtObj);
                        string app_jwt = (jwtObj == null) ? null : Convert.ToString(jwtObj);
                        return(app_jwt);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("GetAppJwtAsync, error: " + ex.Message, ex);
            }

            return(null);
        }
        public async Task UpdateSessionSummaryFromServerAsync()
        {
            object jwt = FileManager.getItem("jwt");

            if (jwt != null)
            {
                string api = "/sessions/summary?refresh=true";
                HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(HttpMethod.Get, api, jwt.ToString());

                if (SoftwareHttpManager.IsOk(response))
                {
                    SessionSummary summary      = SessionSummaryManager.Instance.GetSessionSummayData();
                    string         responseBody = await response.Content.ReadAsStringAsync();

                    IDictionary <string, object> jsonObj = (IDictionary <string, object>)SimpleJson.DeserializeObject(responseBody, new Dictionary <string, object>());
                    if (jsonObj != null)
                    {
                        try
                        {
                            SessionSummary incomingSummary = summary.GetSessionSummaryFromDictionary(jsonObj);
                            summary.CloneSessionSummary(incomingSummary);
                            SessionSummaryManager.Instance.SaveSessionSummaryToDisk(summary);

                            DispatchUpdatesProcessorAsync();
                        } catch (Exception e)
                        {
                            Logger.Error("failed to read json: " + e.Message);
                        }
                    }

                    package.RebuildMenuButtonsAsync();
                }
            }
        }
        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 static async Task <bool> IsLoggedOn(bool online)
        {
            try
            {
                string jwt = FileManager.getItemAsString("jwt");
                if (online && jwt != null)
                {
                    User user = await GetUserAsync(online);

                    if (user != null && SoftwareCoUtil.IsValidEmail(user.email))
                    {
                        FileManager.setItem("name", user.email);
                        FileManager.setItem("jwt", user.plugin_jwt);
                        lastJwt = user.plugin_jwt;
                        return(true);
                    }

                    string api = "/users/plugin/state";
                    HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(HttpMethod.Get, api, jwt);

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

                        IDictionary <string, object> jsonObj = (IDictionary <string, object>)SimpleJson.DeserializeObject(responseBody, new Dictionary <string, object>());
                        if (jsonObj != null)
                        {
                            jsonObj.TryGetValue("state", out object stateObj);
                            string state = (stateObj == null) ? "NONE" : Convert.ToString(stateObj);
                            jsonObj.TryGetValue("jwt", out object pluginJwtObj);
                            string pluginJwt = (pluginJwtObj == null) ? null : Convert.ToString(pluginJwtObj);
                            if (state.Equals("OK") && pluginJwt != null)
                            {
                                jsonObj.TryGetValue("email", out object nameObj);
                                string name = (nameObj == null) ? null : Convert.ToString(nameObj);
                                if (name != null)
                                {
                                    FileManager.setItem("name", name);
                                }
                                FileManager.setItem("jwt", pluginJwt);
                                lastJwt = pluginJwt;
                            }
                            else if (state.Equals("NOT_FOUND"))
                            {
                                FileManager.setItem("jwt", null);
                                lastJwt = null;
                            }
                        }
                    }
                }
                FileManager.setItem("name", null);
            }
            catch (Exception ex)
            {
                //
            }

            return(false);
        }
        public static async Task <string> CreateAnonymousUserAsync(bool online)
        {
            // get the app jwt
            try
            {
                string app_jwt = await GetAppJwtAsync(online);

                if (app_jwt != null && online)
                {
                    string creation_annotation = "NO_SESSION_FILE";
                    string osUsername          = Environment.UserName;
                    string timezone            = "";
                    if (TimeZone.CurrentTimeZone.DaylightName != null &&
                        TimeZone.CurrentTimeZone.DaylightName != TimeZone.CurrentTimeZone.StandardName)
                    {
                        timezone = TimeZone.CurrentTimeZone.DaylightName;
                    }
                    else
                    {
                        timezone = TimeZone.CurrentTimeZone.StandardName;
                    }

                    JsonObject jsonObj = new JsonObject();
                    jsonObj.Add("timezone", timezone);
                    jsonObj.Add("username", osUsername);
                    jsonObj.Add("hostname", SoftwareCoUtil.getHostname());
                    jsonObj.Add("creation_annotation", creation_annotation);

                    string api      = "/data/onboard";
                    string jsonData = jsonObj.ToString();
                    HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(HttpMethod.Post, api, jsonData, app_jwt);

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

                        IDictionary <string, object> respObj = (IDictionary <string, object>)SimpleJson.DeserializeObject(responseBody, new Dictionary <string, object>());
                        respObj.TryGetValue("jwt", out object jwtObj);
                        string jwt = (jwtObj == null) ? null : Convert.ToString(jwtObj);
                        if (jwt != null)
                        {
                            FileManager.setItem("jwt", jwt);
                            return(jwt);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("CreateAnonymousUserAsync, error: " + ex.Message, ex);
            }


            return(null);
        }
        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());
            }
        }
Esempio n. 7
0
        /**
         * Get the latest repo commit
         **/
        public async Task <RepoCommit> GetLatestCommitAsync(string projectDir)
        {
            try
            {
                if (!SoftwareCoUtil.IsGitProject(projectDir))
                {
                    return(null);
                }
                RepoResourceInfo info = GitUtilManager.GetResourceInfo(projectDir, false);

                if (info != null && info.identifier != null)
                {
                    string identifier = info.identifier;
                    if (identifier != null && !identifier.Equals(""))
                    {
                        string tag    = info.tag;
                        string branch = info.branch;

                        string qryString = "?identifier=" + identifier;
                        qryString += "&tag=" + tag;
                        qryString += "&branch=" + branch;

                        HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(
                            HttpMethod.Get, "/commits/latest?" + qryString, null);

                        if (SoftwareHttpManager.IsOk(response))
                        {
                            // get the json data
                            string responseBody = await response.Content.ReadAsStringAsync();

                            IDictionary <string, object> jsonObj = (IDictionary <string, object>)SimpleJson.DeserializeObject(responseBody, new Dictionary <string, object>());

                            jsonObj.TryGetValue("commitId", out object commitIdObj);
                            string commitId = (commitIdObj == null) ? "" : Convert.ToString(commitIdObj);

                            jsonObj.TryGetValue("message", out object messageObj);
                            string message = (messageObj == null) ? "" : Convert.ToString(messageObj);

                            jsonObj.TryGetValue("message", out object timestampObj);
                            long timestamp = (timestampObj == null) ? 0L : Convert.ToInt64(timestampObj);

                            RepoCommit repoCommit = new RepoCommit(commitId, message, timestamp);
                            return(repoCommit);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("GetLatestCommitAsync ,error: " + ex.Message, ex);
            }
            return(null);
        }
        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);
        }
Esempio n. 9
0
        /**
         * Get the latest repo commit
         **/
        public async Task <RepoCommit> GetLatestCommitAsync(string projectDir)
        {
            if (projectDir == null || projectDir.Equals(""))
            {
                return(null);
            }

            IDictionary <string, string> resourceInfo = this.GetResourceInfo(projectDir);

            if (resourceInfo != null && resourceInfo.ContainsKey("identifier"))
            {
                string identifier = "";
                resourceInfo.TryGetValue("identifier", out identifier);
                if (identifier != null && !identifier.Equals(""))
                {
                    string tag = "";
                    resourceInfo.TryGetValue("tag", out tag);
                    string branch = "";
                    resourceInfo.TryGetValue("branch", out branch);

                    string qryString = "?identifier=" + identifier;
                    qryString += "&tag=" + tag;
                    qryString += "&branch=" + branch;

                    HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(
                        HttpMethod.Get, "/commits/latest?" + qryString, null);

                    if (SoftwareHttpManager.IsOk(response))
                    {
                        // get the json data
                        string responseBody = await response.Content.ReadAsStringAsync();

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

                        jsonObj.TryGetValue("commitId", out object commitIdObj);
                        string commitId = (commitIdObj == null) ? "" : Convert.ToString(commitIdObj);

                        jsonObj.TryGetValue("message", out object messageObj);
                        string message = (messageObj == null) ? "" : Convert.ToString(messageObj);

                        jsonObj.TryGetValue("message", out object timestampObj);
                        long timestamp = (timestampObj == null) ? 0L : Convert.ToInt64(timestampObj);

                        RepoCommit repoCommit = new RepoCommit(commitId, message, timestamp);
                        return(repoCommit);
                    }
                }
            }
            return(null);
        }
        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);
        }
        private static async Task <User> GetUserAsync(bool online)
        {
            string jwt = FileManager.getItemAsString("jwt");

            try
            {
                if (jwt != null && online)
                {
                    string api = "/users/me";
                    HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(HttpMethod.Get, api, jwt);

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

                        IDictionary <string, object> jsonObj = (IDictionary <string, object>)SimpleJson.DeserializeObject(responseBody, new Dictionary <string, object>());
                        if (jsonObj != null)
                        {
                            jsonObj.TryGetValue("data", out object userObj);
                            if (userObj != null)
                            {
                                IDictionary <string, object> userData = (IDictionary <string, object>)userObj;

                                userData.TryGetValue("email", out object emailObj);
                                string email = (emailObj == null) ? null : Convert.ToString(emailObj);
                                userData.TryGetValue("plugin_jwt", out object pluginJwtObj);
                                string pluginJwt = (pluginJwtObj == null) ? null : Convert.ToString(pluginJwtObj);
                                userData.TryGetValue("id", out object idObj);
                                long userId = (idObj == null) ? 0L : Convert.ToInt64(idObj);

                                User user = new User();
                                user.email      = email;
                                user.plugin_jwt = pluginJwt;
                                user.id         = userId;
                                return(user);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("GetUserAsync, error: " + ex.Message, ex);
            }

            return(null);
        }
        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);
        }
Esempio n. 13
0
        public async Task SendOfflineEvents()
        {
            List <CodeTimeEvent> existingList = GetCodeTimeEventList();

            if (existingList.Count > 0)
            {
                JsonArray jsonArray = new JsonArray(existingList.Count);
                foreach (CodeTimeEvent existingEvent in existingList)
                {
                    jsonArray.Add(existingEvent.GetAsJson());
                }
                string eventData             = jsonArray.ToString();
                HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(HttpMethod.Post, "/data/event", eventData);

                if (SoftwareHttpManager.IsOk(response))
                {
                    ClearCodeTimeEventDataSummary();
                }
            }
        }
        public async Task SendTimeDataAsync()
        {
            string timeDataSummary = GetTimeDataFileData();

            if (timeDataSummary != null)
            {
                if (!timeDataSummary.StartsWith("["))
                {
                    // join array around the json string
                    timeDataSummary = "[" + string.Join(",", timeDataSummary) + "]";
                }
                HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(
                    HttpMethod.Post, "/data/time", timeDataSummary);

                if (SoftwareHttpManager.IsOk(response))
                {
                    ClearTimeDataSummary();
                }
            }
        }
Esempio n. 15
0
        public async Task ProcessRepoMembers(string projectDir)
        {
            if (!SoftwareCoUtil.IsGitProject(projectDir))
            {
                return;
            }
            RepoResourceInfo info = GitUtilManager.GetResourceInfo(projectDir, true);

            if (info != null && info.Members.Count > 0)
            {
                string jsonContent = SimpleJson.SerializeObject(info);
                // send the members
                HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(
                    HttpMethod.Post, "/repo/members", jsonContent);

                if (!SoftwareHttpManager.IsOk(response))
                {
                    Logger.Error(response.ToString());
                }
            }
        }
Esempio n. 16
0
        public async void GetHistoricalCommitsAsync(string projectDir)
        {
            try
            {
                if (!SoftwareCoUtil.IsGitProject(projectDir))
                {
                    return;
                }
                RepoResourceInfo info = GitUtilManager.GetResourceInfo(projectDir, false);

                if (info != null && info.identifier != null)
                {
                    string identifier = info.identifier;
                    if (identifier != null && !identifier.Equals(""))
                    {
                        string tag    = info.tag;
                        string branch = info.branch;
                        string email  = info.email;

                        RepoCommit latestCommit = null;
                        latestCommit = await this.GetLatestCommitAsync(projectDir);

                        string sinceOption = "";
                        if (latestCommit != null)
                        {
                            sinceOption = " --since=" + latestCommit.timestamp;
                        }
                        else
                        {
                            sinceOption = " --max-count=100";
                        }

                        string cmd = "git log --stat --pretty=COMMIT:%H,%ct,%cI,%s --author=" + email + "" + sinceOption;

                        string gitCommitData = SoftwareCoUtil.RunCommand(cmd, projectDir);

                        if (gitCommitData != null && !gitCommitData.Equals(""))
                        {
                            string[] lines = gitCommitData.Split(
                                new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                            RepoCommit        currentRepoCommit = null;
                            List <RepoCommit> repoCommits       = new List <RepoCommit>();
                            if (lines != null && lines.Length > 0)
                            {
                                for (int i = 0; i < lines.Length; i++)
                                {
                                    string line = lines[i].Trim();
                                    if (line.Length > 0)
                                    {
                                        bool hasPipe = line.IndexOf("|") != -1 ? true : false;
                                        bool isBin   = line.ToLower().IndexOf("bin") != -1 ? true : false;
                                        if (line.IndexOf("COMMIT:") == 0)
                                        {
                                            line = line.Substring("COMMIT:".Length);
                                            if (currentRepoCommit != null)
                                            {
                                                repoCommits.Add(currentRepoCommit);
                                            }

                                            string[] commitInfos = line.Split(',');
                                            if (commitInfos != null && commitInfos.Length > 0)
                                            {
                                                string commitId = commitInfos[0].Trim();
                                                // go to the next line if we've already processed this commitId
                                                if (latestCommit != null && commitId.Equals(latestCommit.commitId))
                                                {
                                                    currentRepoCommit = null;
                                                    continue;
                                                }

                                                // get the other attributes now
                                                long   timestamp = Convert.ToInt64(commitInfos[1].Trim());
                                                string date      = commitInfos[2].Trim();
                                                string message   = commitInfos[3].Trim();
                                                currentRepoCommit      = new RepoCommit(commitId, message, timestamp);
                                                currentRepoCommit.date = date;

                                                RepoCommitChanges changesObj = new RepoCommitChanges(0, 0);
                                                currentRepoCommit.changes.Add("__sftwTotal__", changesObj);
                                            }
                                        }
                                        else if (currentRepoCommit != null && hasPipe && !isBin)
                                        {
                                            // get the file and changes
                                            // i.e. somefile.cs                             | 20 +++++++++---------
                                            line = string.Join(" ", line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
                                            string[] lineInfos = line.Split('|');
                                            if (lineInfos != null && lineInfos.Length > 1)
                                            {
                                                string   file        = lineInfos[0].Trim();
                                                string[] metricInfos = lineInfos[1].Trim().Split(' ');
                                                if (metricInfos != null && metricInfos.Length > 1)
                                                {
                                                    string addAndDeletes = metricInfos[1].Trim();
                                                    int    len           = addAndDeletes.Length;
                                                    int    lastPlusIdx   = addAndDeletes.LastIndexOf('+');
                                                    int    insertions    = 0;
                                                    int    deletions     = 0;
                                                    if (lastPlusIdx != -1)
                                                    {
                                                        insertions = lastPlusIdx + 1;
                                                        deletions  = len - insertions;
                                                    }
                                                    else if (len > 0)
                                                    {
                                                        // all deletions
                                                        deletions = len;
                                                    }

                                                    if (!currentRepoCommit.changes.ContainsKey(file))
                                                    {
                                                        RepoCommitChanges changesObj = new RepoCommitChanges(insertions, deletions);
                                                        currentRepoCommit.changes.Add(file, changesObj);
                                                    }
                                                    else
                                                    {
                                                        RepoCommitChanges fileCommitChanges;
                                                        currentRepoCommit.changes.TryGetValue(file, out fileCommitChanges);
                                                        if (fileCommitChanges != null)
                                                        {
                                                            fileCommitChanges.deletions  += deletions;
                                                            fileCommitChanges.insertions += insertions;
                                                        }
                                                    }


                                                    RepoCommitChanges totalRepoCommit;
                                                    currentRepoCommit.changes.TryGetValue("__sftwTotal__", out totalRepoCommit);
                                                    if (totalRepoCommit != null)
                                                    {
                                                        totalRepoCommit.deletions  += deletions;
                                                        totalRepoCommit.insertions += insertions;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (currentRepoCommit != null)
                            {
                                repoCommits.Add(currentRepoCommit);
                            }

                            if (repoCommits != null && repoCommits.Count > 0)
                            {
                                // batch 10 at a time
                                int batch_size          = 10;
                                List <RepoCommit> batch = new List <RepoCommit>();
                                for (int i = 0; i < repoCommits.Count; i++)
                                {
                                    batch.Add(repoCommits[i]);
                                    if (i > 0 && i % batch_size == 0)
                                    {
                                        // send this batch.
                                        RepoCommitData commitData = new RepoCommitData(identifier, tag, branch, batch);

                                        string jsonContent = commitData.GetAsJson(); // SimpleJson.SerializeObject(commitData);
                                                                                     // send the members
                                        HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(
                                            HttpMethod.Post, "/commits", jsonContent);

                                        if (SoftwareHttpManager.IsOk(response))
                                        {
                                            Logger.Info(response.ToString());
                                        }
                                        else
                                        {
                                            Logger.Error(response.ToString());
                                        }
                                    }
                                }

                                if (batch.Count > 0)
                                {
                                    RepoCommitData commitData = new RepoCommitData(identifier, tag, branch, batch);

                                    string jsonContent = commitData.GetAsJson(); // SimpleJson.SerializeObject(commitData);
                                                                                 // send the members
                                    HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(
                                        HttpMethod.Post, "/commits", jsonContent);

                                    if (SoftwareHttpManager.IsOk(response))
                                    {
                                        Logger.Info(response.ToString());
                                    }
                                    else if (response != null)
                                    {
                                        Logger.Error("Unable to complete commit request, status: " + response.StatusCode);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("GetHistoricalCommitsAsync ,error: " + ex.Message, ex);
            }
        }
Esempio n. 17
0
        public async void GetRepoUsers(string projectDir)
        {
            if (projectDir == null || projectDir.Equals(""))
            {
                return;
            }

            IDictionary <string, string> resourceInfo = this.GetResourceInfo(projectDir);

            if (resourceInfo != null && resourceInfo.ContainsKey("identifier"))
            {
                string identifier = "";
                resourceInfo.TryGetValue("identifier", out identifier);
                if (identifier != null && !identifier.Equals(""))
                {
                    string tag = "";
                    resourceInfo.TryGetValue("tag", out tag);
                    string branch = "";
                    resourceInfo.TryGetValue("branch", out branch);

                    string gitLogData = SoftwareCoUtil.RunCommand("git log --pretty=%an,%ae | sort", projectDir);

                    IDictionary <string, string> memberMap = new Dictionary <string, string>();

                    List <RepoMember> repoMembers = new List <RepoMember>();
                    if (gitLogData != null && !gitLogData.Equals(""))
                    {
                        string[] lines = gitLogData.Split(
                            new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                        if (lines != null && lines.Length > 0)
                        {
                            for (int i = 0; i < lines.Length; i++)
                            {
                                string   line        = lines[i];
                                string[] memberInfos = line.Split(',');
                                if (memberInfos != null && memberInfos.Length > 1)
                                {
                                    string name  = memberInfos[0].Trim();
                                    string email = memberInfos[1].Trim();
                                    if (!memberMap.ContainsKey(email))
                                    {
                                        memberMap.Add(email, name);
                                        repoMembers.Add(new RepoMember(name, email));
                                    }
                                }
                            }
                        }
                    }

                    if (memberMap.Count > 0)
                    {
                        RepoData repoData    = new RepoData(identifier, tag, branch, repoMembers);
                        string   jsonContent = SimpleJson.SerializeObject(repoData);
                        // send the members
                        HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(
                            HttpMethod.Post, "/repo/members", jsonContent);

                        if (!SoftwareHttpManager.IsOk(response))
                        {
                            Logger.Error(response.ToString());
                        }
                    }
                }
            }
        }
Esempio n. 18
0
        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());
            }
        }