Beispiel #1
0
        private static IEnumerable <TogglEntry> GetEntries(TogglEntry[] inputEntries, DateTime from, DateTime to)
        {
            Dictionary <string, string> headers = new Dictionary <string, string> {
                { "Set-Cookie", ValidFakeCookie }
            };
            MockHttpDataSource       source       = new MockHttpDataSource();
            TogglClient              client       = new TogglClient(FakeToken, source);
            ToggleClientStatusKeeper statusKeeper = new ToggleClientStatusKeeper(client);

            source.SetResponse(SessionUrl, "POST", new MockHttpResponse <TogglEntry[]>()
            {
                FakeHeaders = headers
            });

            client.LogIn();

            Assert.IsTrue(statusKeeper.IsLoggedIn);

            source.SetResponse(client.GetFormattedEntriesUrl(from, to), "GET", new MockHttpResponse <TogglEntry[]>()
            {
                FakeStatusCode     = HttpStatusCode.OK,
                FakeResponseObject = inputEntries
            });

            return(client.GetEntries(from, to));
        }
 /// <summary>
 /// Deletes the specified <paramref name="client"/>.
 /// </summary>
 /// <param name="client">The client to be deleted.</param>
 /// <returns>An instance of <see cref="IHttpResponse"/> representing the raw response from the Toggl API.</returns>
 /// <see>
 ///     <cref>https://github.com/toggl/toggl_api_docs/blob/master/chapters/clients.md#delete-a-client</cref>
 /// </see>
 public IHttpResponse DeleteClient(TogglClient client)
 {
     if (client == null)
     {
         throw new ArgumentNullException(nameof(client));
     }
     return(Client.Delete($"https://{TogglConstants.Track.HostName}/api/v8/clients/{client.Id}"));
 }
Beispiel #3
0
 private void SetToggleClientStatusChangeCallbacks(TogglClient client)
 {
     client.LogonSucceeded        += () => { AlertStatusChange("Logged in to Toggl", Logger.Info); };
     client.LogonFailed           += () => { AlertStatusChange("Failed to log in to Toggl", Logger.Warn); };
     client.LogoutSucceeded       += () => { AlertStatusChange("Logged out from Toggl", Logger.Info); };
     client.LogoutFailed          += () => { AlertStatusChange("Failed to log in to Toggl", Logger.Warn); };
     client.FetchingEntriesFailed += errorMsg => { AlertStatusChange($"Failed to get Toggl entries: {errorMsg}", Logger.Error); };
 }
Beispiel #4
0
            public ToggleClientStatusKeeper(TogglClient client)
            {
                _togglClient = client;

                client.LogonFailed           += delegate { LogonFailed = true; };
                client.LogonSucceeded        += delegate { LogonSucceeded = true; };
                client.LogoutFailed          += delegate { LogoutFailed = true; };
                client.LogoutSucceeded       += delegate { LogoutSucceeded = true; };
                client.FetchingEntriesFailed += delegate { GetEntriesFailed = true; };
            }
Beispiel #5
0
        public void Logout_LogoutWhenNotLoggedInDoesNothing()
        {
            TogglClient client = new TogglClient(FakeToken);
            ToggleClientStatusKeeper statusKeeper = new ToggleClientStatusKeeper(client);

            client.LogOut();

            Assert.IsFalse(statusKeeper.IsLoggedIn);
            Assert.IsFalse(statusKeeper.LogoutFailed);
            Assert.IsFalse(statusKeeper.LogoutSucceeded);
        }
Beispiel #6
0
        private static ToggleClientStatusKeeper LoginWithHeaders(Dictionary <string, string> headers)
        {
            IHttpResponse response = new MockHttpResponse <TogglEntry[]>()
            {
                FakeHeaders = headers
            };
            MockHttpDataSource       source       = new MockHttpDataSource();
            TogglClient              client       = new TogglClient(FakeToken, source);
            ToggleClientStatusKeeper statusKeeper = new ToggleClientStatusKeeper(client);

            source.SetResponse(SessionUrl, "POST", response);
            client.LogIn();
            return(statusKeeper);
        }
Beispiel #7
0
        private static async Task <Project?> GetProject(TogglClient client, string?project)
        {
            if (!string.IsNullOrWhiteSpace(project))
            {
                if (int.TryParse(project, out int projectId))
                {
                    return(await client.Projects.GetAsync(projectId));
                }
                else
                {
                    List <Project> allProjects = await client.Projects.ListAsync();

                    return(allProjects.FirstOrDefault(x =>
                                                      string.Equals(x.Name, project, StringComparison.OrdinalIgnoreCase)));
                }
            }

            return(null);
        }
Beispiel #8
0
        private static MockHttpDataSource GetLoggedInClient(out TogglClient client, out ToggleClientStatusKeeper statusKeeper)
        {
            Dictionary <string, string> headers = new Dictionary <string, string> {
                { "Set-Cookie", ValidFakeCookie }
            };
            MockHttpDataSource source = new MockHttpDataSource();

            client       = new TogglClient(FakeToken, source);
            statusKeeper = new ToggleClientStatusKeeper(client);

            source.SetResponse(SessionUrl, "POST", new MockHttpResponse <TogglEntry[]>()
            {
                FakeHeaders = headers
            });

            client.LogIn();

            Assert.IsTrue(statusKeeper.IsLoggedIn);
            return(source);
        }
Beispiel #9
0
        private static async Task <Workspace> GetWorkspace(TogglClient client, string?workspace)
        {
            List <Workspace> workspaces = await client.Workspaces.GetAllAsync();

            if (!string.IsNullOrWhiteSpace(workspace))
            {
                if (int.TryParse(workspace, out int workspaceId) &&
                    workspaces.FirstOrDefault(x => x.Id == workspaceId) is { } workspaceById)
                {
                    return(workspaceById);
                }

                if (workspaces.FirstOrDefault(x => string.Equals(x.Name, workspace, StringComparison.OrdinalIgnoreCase))
                    is { } workspaceByName)
                {
                    return(workspaceByName);
                }
            }

            return(workspaces.First());
        }
Beispiel #10
0
        private static ToggleClientStatusKeeper LogInLogOutWithStatus(HttpStatusCode statusCode)
        {
            Dictionary <string, string> headers = new Dictionary <string, string> {
                { "Set-Cookie", ValidFakeCookie }
            };
            MockHttpDataSource       source       = new MockHttpDataSource();
            TogglClient              client       = new TogglClient(FakeToken, source);
            ToggleClientStatusKeeper statusKeeper = new ToggleClientStatusKeeper(client);

            source.SetResponse(SessionUrl, "POST", new MockHttpResponse <TogglEntry[]>()
            {
                FakeHeaders = headers
            });
            source.SetResponse(SessionUrl, "DELETE", new MockHttpResponse <TogglEntry[]>()
            {
                FakeStatusCode = statusCode
            });
            client.LogIn();
            client.LogOut();
            return(statusKeeper);
        }
Beispiel #11
0
        public void Logout_DataSourceTimeoutFailsLogout()
        {
            Dictionary <string, string> headers = new Dictionary <string, string> {
                { "Set-Cookie", ValidFakeCookie }
            };
            MockHttpDataSource       source       = new MockHttpDataSource();
            TogglClient              client       = new TogglClient(FakeToken, source);
            ToggleClientStatusKeeper statusKeeper = new ToggleClientStatusKeeper(client);

            source.SetResponse(SessionUrl, "POST", new MockHttpResponse <TogglEntry[]>()
            {
                FakeHeaders = headers
            });
            source.SetException(SessionUrl, "DELETE", new WebException("Timeout", WebExceptionStatus.Timeout));

            client.LogIn();
            client.LogOut();

            Assert.True(statusKeeper.IsLoggedIn);
            Assert.IsFalse(statusKeeper.LogoutSucceeded);
            Assert.IsTrue(statusKeeper.LogoutFailed);
            Assert.IsTrue(statusKeeper.EncounteredError);
        }
Beispiel #12
0
 private static async Task <TimeEntry> SubmitTimeEntryAsync(
     TogglClient client,
     string?description,
     Project?targetProject,
     Workspace targetWorkspace,
     bool?isBillable,
     DateTime?start,
     DateTime?stop,
     int?duration)
 {
     if (start != null && (stop != null || duration != null))
     {
         stop ??= start + TimeSpan.FromMinutes(duration ?? 0);
         return(await client.TimeEntries.CreateAsync(new TimeEntry
         {
             Description = description,
             IsBillable = isBillable ?? targetProject?.IsBillable,
             CreatedWith = "TimeLogger Console Automation",
             ProjectId = targetProject?.Id,
             WorkspaceId = targetWorkspace.Id,
             Duration = (long)(stop.Value - start.Value).TotalSeconds,
             Start = $"{start:O}",
             Stop = $"{stop:O}"
         }));
     }
     else
     {
         return(await client.TimeEntries.StartAsync(new TimeEntry
         {
             Description = description,
             IsBillable = isBillable ?? targetProject?.IsBillable,
             CreatedWith = "TimeLogger Console Automation",
             ProjectId = targetProject?.Id,
             WorkspaceId = targetWorkspace.Id
         }));
     }
 }
 public InteractWithToggl()
 {
     TogglClient = new TogglClient(TogglApiKey);
 }
 /// <summary>
 /// Initializes a new instance from an existing <paramref name="client"/>.
 /// </summary>
 /// <param name="client">The client to be updated.</param>
 public TogglUpdateClentOptions(TogglClient client)
 {
     Id    = client.Id;
     Name  = client.Name;
     Notes = client.Notes;
 }
Beispiel #15
0
 /// <summary>
 /// Deletes the specified <paramref name="client"/>.
 /// </summary>
 /// <param name="client">The client to be deleted.</param>
 /// <returns>An instance of <see cref="TogglResponse"/> representing the response from the Toggl API.</returns>
 /// <see>
 ///     <cref>https://github.com/toggl/toggl_api_docs/blob/master/chapters/clients.md#delete-a-client</cref>
 /// </see>
 public TogglResponse DeleteClient(TogglClient client)
 {
     return(new TogglResponse(Raw.DeleteClient(client)));
 }
Beispiel #16
0
        public async Task PushTime(AppSetting settings, DateTime startDate, DateTime endDate)
        {
            //tra-74

            if (settings == null)
            {
                throw new Exception("No Jira or Toggl credentials provided.");
            }
            this.VerifySetting(settings.JiraLogin, "JIRA login");
            this.VerifySetting(settings.JiraPassword, "JIRA password");
            this.VerifySetting(settings.JiraUrl, "JIRA URL");
            this.VerifySetting(settings.TogglApiKey, "Toggl API Key");

            var jira  = Jira.CreateRestClient(settings.JiraUrl, settings.JiraLogin, settings.JiraPassword);
            var toggl = new TogglClient(settings.TogglApiKey);

            await Task.Run(async() =>
            {
                var timeParams = new TimeEntryParams();

                timeParams.StartDate = startDate.Date;
                timeParams.EndDate   = endDate.Date;
                var entries          = await toggl.TimeEntries.GetAllAsync(timeParams);

                foreach (var te in entries.Where(w => (w.TagNames == null || !w.TagNames.Contains(POSTED_TAG)) &&
                                                 !string.IsNullOrEmpty(w.Description)))
                {
                    Debug.WriteLine(te.CreatedOn);
                    Debug.WriteLine(te.UpdatedOn);
                    Debug.WriteLine(te.Start);
                    Debug.WriteLine(te.Stop);

                    // have to manually convert DateTime to correct format for Toggl API (client library doesn't do it)
                    te.UpdatedOn = DateTime.Parse(te.UpdatedOn).ToUniversalTime().ToString("o");
                    te.Start     = DateTime.Parse(te.Start).ToUniversalTime().ToString("o");
                    te.Stop      = DateTime.Parse(te.Stop).ToUniversalTime().ToString("o");

                    Debug.WriteLine(te.CreatedOn);
                    Debug.WriteLine(te.UpdatedOn);
                    Debug.WriteLine(te.Start);
                    Debug.WriteLine(te.Stop);


                    KeyValuePair <string, string> description = this.ParseDescription(te.Description);
                    if (string.IsNullOrEmpty(description.Key))
                    {
                        continue;
                    }

                    var issue = await jira.Issues.GetIssueAsync(description.Key);
                    await issue.AddWorklogAsync(new Worklog(this.GetMinutes(te.Duration.GetValueOrDefault()), DateTime.Parse(te.Start), description.Value));

                    if (te.TagNames == null)
                    {
                        te.TagNames = new List <string>();
                    }
                    te.TagNames.Add(POSTED_TAG);
                    await toggl.TimeEntries.UpdateAsync(te);
                }
            });

            //return Task.Run(() =>
            //    {
            //        //Atlassian.Jira.Jira aa = new Atlassian.Jira.Jira("urlhere", "loginhere", "passwordhere");
            //        //var issue = aa.GetIssue("FLW6-2247");
            //        //issue.AddWorklog(new Atlassian.Jira.Worklog)

            //        //var apiKey = "apikeyhere";
            //        //var t = new Toggl.Toggl(apiKey);
            //        //var c = t.User.GetCurrent();

            //        //var timeSrv = new Toggl.Services.TimeEntryService(apiKey);
            //        //var prams = new Toggl.QueryObjects.TimeEntryParams();

            //        //// there is an issue with the date ranges have
            //        //// to step out of the range on the end.
            //        //// To capture the end of the billing range day + 1
            //        //prams.StartDate = DateTime.Now.AddMonths(-1);
            //        //prams.EndDate = DateTime.Now.AddMonths(1);

            //        //var hours = timeSrv.List(prams)
            //        //                        .Where(w => !string.IsNullOrEmpty(w.Description)).ToList();
            //    });
        }
Beispiel #17
0
 /// <summary>
 /// Creates a new <see cref="TaskService"/>
 /// </summary>
 /// <param name="client">Current <see cref="TogglClient"/></param>
 public TaskService(TogglClient client)
 {
     _client = client ?? throw new ArgumentNullException(nameof(client));
 }
Beispiel #18
0
 protected TogglTest(ITestOutputHelper iTestOutputHelper)
 {
     Logger        = iTestOutputHelper.BuildLogger();
     Configuration = LoadConfiguration("appsettings.json");
     TogglClient   = new TogglClient(Configuration.ApiKey);
 }