forked from manictime/manictime-api-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
2154 lines (1764 loc) · 83 KB
/
Copy pathclient.py
File metadata and controls
2154 lines (1764 loc) · 83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
from datetime import datetime, timedelta
import requests
from requests_ntlm import HttpNtlmAuth
import json
from pathlib import Path
import backoff
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
from typing import Dict, Any, List, Optional, Union
import asyncio
import aiohttp
import pandas as pd
from io import StringIO, BytesIO
from .configuration import Config
from .exceptions import ManicTimeClientError, AuthenticationError, NotFoundError
from .models import Activity, Timeline, TagCombination
logger = logging.getLogger("manictime.client")
class ManicTimeClient:
def __init__(self, config: Config):
"""Initialize client with configuration"""
self.config = config
self.config.validate()
self.session = self._create_session()
self._setup_authentication()
logger.debug("ManicTimeClient initialized with config: %s", self.config.server_url)
def _create_session(self) -> requests.Session:
"""Create and configure requests session with retries and proper timeouts"""
session = requests.Session()
# Configure adapter with connection pooling and retries
retry = Retry(
total=3,
backoff_factor=0.5,
status_forcelist=[500, 502, 503, 504],
allowed_methods=["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"]
)
# Create adapter with connection pool settings
adapter = HTTPAdapter(
max_retries=retry,
pool_connections=10,
pool_maxsize=10,
pool_block=False # Don't block waiting for connection from pool
)
session.mount('http://', adapter)
session.mount('https://', adapter)
# Wrap the session's request method to ensure proper timeout handling
original_request = session.request
session.request = self._create_timeout_wrapper(original_request)
return session
def _create_timeout_wrapper(self, original_request):
"""Create a wrapper that ensures proper timeout for all requests"""
def request_with_timeout(*args, **kwargs):
# Ensure timeout is always set as tuple (connect_timeout, read_timeout)
if 'timeout' not in kwargs or kwargs['timeout'] is None:
# Default: 10s for connection, config timeout for read
kwargs['timeout'] = (10, self.config.timeout)
elif isinstance(kwargs['timeout'], (int, float)):
# Convert single timeout to tuple: use 10s for connection
kwargs['timeout'] = (10, kwargs['timeout'])
# Log the timeout being used
logger.debug(f"Making request with timeout: {kwargs.get('timeout')}")
return original_request(*args, **kwargs)
return request_with_timeout
def _setup_authentication(self):
"""Configure authentication based on config"""
if self.config.auth_type == 'ntlm':
domain_user = f'{self.config.domain}\\{self.config.username}' if self.config.domain else self.config.username
self.session.auth = HttpNtlmAuth(domain_user, self.config.password)
elif self.config.auth_type == 'bearer':
if self.config.token:
self.session.headers['Authorization'] = f'Bearer {self.config.token}'
elif self.config.username and self.config.password:
self._get_token()
else:
raise AuthenticationError("Bearer auth requires token or username/password")
def _get_token(self):
"""Get authentication token using username/password following OAuth 2.0 Resource Owner Password Flow"""
try:
if self.config.auth_type == 'bearer':
# Bypass token endpoint discovery and use direct URL
# Clear session cookies to ensure a clean request
self.session.cookies.clear()
logger.debug(f"Session cookies cleared before token request")
# Use the direct token endpoint URL
token_url = f"{self.config.server_url}/api/token"
logger.debug(f"Using direct token endpoint: {token_url}")
# Step 2: Get access token from token endpoint
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/vnd.manictime.v3+json"
}
# Use form-urlencoded format with proper URL encoding
data = {
"grant_type": "password",
"username": self.config.username,
"password": self.config.password
}
# Make token request with explicit connection timeout
logger.debug(f"Requesting token with timeout: (10, {self.config.timeout})")
token_response = self.session.request(
"post",
token_url,
headers=headers,
data=data, # requests will handle URL encoding automatically
timeout=(10, self.config.timeout) # (connect, read) timeouts
)
logger.debug(f"Token request response status: {token_response.status_code}")
# Even if we get a 200 OK, we need to verify the response contains a token
# First check if the response is valid JSON
try:
token_data = token_response.json()
except Exception as e:
logger.error(f"Failed to parse token response as JSON: {str(e)}")
raise AuthenticationError(f"Invalid response format from server: {str(e)}")
# Check if token_data is a dictionary
if not isinstance(token_data, dict):
logger.error(f"Unexpected token response format: {type(token_data)}")
raise AuthenticationError(f"Unexpected token response format: {type(token_data)}")
# Check if the token is in the response
if "token" not in token_data:
# Some servers might return 200 OK even for auth failures
# with different response formats
if "error" in token_data:
error_msg = token_data.get("error_description", token_data["error"])
raise AuthenticationError(f"Authentication error: {error_msg}")
else:
raise AuthenticationError("Invalid token response from server (token not found)")
# Set authorization header for future API calls
self.session.headers['Authorization'] = f'Bearer {token_data["token"]}'
# Return the token for storing in Odoo
self.token = token_data["token"]
logger.debug("Successfully obtained authentication token")
elif self.config.auth_type == 'ntlm':
# For NTLM, we already set up the session with HttpNtlmAuth,
# so nothing else to do here except verify it works
api_url = f"{self.config.server_url}/api"
logger.debug(f"Testing NTLM authentication to {api_url}")
headers = {
"Accept": "application/vnd.manictime.v3+json"
}
response = self.session.request(
"get",
api_url,
headers=headers,
timeout=(10, self.config.timeout) # (connect, read) timeouts
)
response.raise_for_status()
logger.debug("NTLM authentication successful")
else:
raise AuthenticationError(f"Unsupported authentication type: {self.config.auth_type}")
except requests.exceptions.RequestException as e:
raise AuthenticationError(f"Failed to obtain authentication token: {str(e)}")
@backoff.on_exception(backoff.expo, requests.exceptions.RequestException, max_tries=3)
def _make_request(self, url: str, method: str = 'get',
data: Any = None, params: Dict[str, Any] = None,
headers: Dict[str, str] = None) -> Any:
"""Make HTTP request with retries and error handling"""
# Prepare headers - start with session headers
request_headers = dict(self.session.headers)
# Add any custom headers
if headers:
request_headers.update(headers)
try:
response = self.session.request(
method,
url,
json=data,
params=params,
headers=request_headers,
timeout=(10, self.config.timeout) # (connect, read) timeouts
)
response.raise_for_status()
# Check if we got JSON response
content_type = response.headers.get('content-type', '')
if 'application/json' in content_type or 'application/vnd.manictime' in content_type:
return response.json() if response.text else None
else:
# If we got HTML, it's likely a login page
if 'text/html' in content_type:
logger.error(f"Got HTML response instead of JSON from {url}. This usually means authentication failed.")
raise AuthenticationError("Authentication required - received HTML instead of JSON")
else:
logger.warning(f"Unexpected content type: {content_type}")
# Try to parse as JSON anyway
try:
return response.json() if response.text else None
except:
raise ManicTimeClientError(f"Invalid response format from {url}. Expected JSON, got {content_type}")
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
raise AuthenticationError("Authentication failed")
if e.response.status_code == 404:
raise NotFoundError(f"Resource not found: {url}")
raise ManicTimeClientError(f"Request failed: {str(e)}")
except requests.exceptions.ConnectionError as e:
# Explicitly handle connection errors
raise ManicTimeClientError(f"Connection error: {str(e)}")
except requests.exceptions.Timeout as e:
# Explicitly handle timeout errors
raise ManicTimeClientError(f"Request timed out: {str(e)}")
except requests.exceptions.RequestException as e:
# Handle any other request exceptions
raise ManicTimeClientError(f"Request error: {str(e)}")
def get_activities(self, timeline_id: str,
from_time: datetime, to_time: datetime,
cache: bool = True, activities_url: str = None) -> Dict[str, Any]:
"""Get activities for timeline in time range
Args:
timeline_id: The timeline ID
from_time: Start time for the activity range
to_time: End time for the activity range
cache: Whether to use caching
activities_url: Optional direct URL to the activities endpoint
Returns:
Response data from activities API with 'activities' key containing processed activity data
"""
# Use the provided activities URL if available, otherwise construct it
if activities_url:
url = activities_url
logger.debug(f"Using provided activities URL: {url}")
else:
url = f"{self.config.server_url}/api/timelines/{timeline_id}/activities"
logger.debug(f"Using default constructed activities URL: {url}")
# Format parameters for the request
params = {
'fromTime': from_time.isoformat(),
'toTime': to_time.isoformat()
}
# Add v3 API header to ensure proper response format
headers = {"Accept": "application/vnd.manictime.v3+json"}
logger.debug(f"Requesting activities for timeline {timeline_id} from {from_time} to {to_time}")
try:
result = self._make_request(url, params=params, headers=headers)
# Handle ManicTime API response with 'entities' array
if isinstance(result, dict):
# Extract activities from 'entities' array
if 'entities' in result and isinstance(result['entities'], list):
# First, build a lookup for groups by their entityId
groups_lookup = {}
group_count = 0
for entity in result['entities']:
if isinstance(entity, dict) and entity.get('entityType') == 'group':
group_count += 1
group_id = entity.get('entityId')
if group_id and 'values' in entity:
groups_lookup[group_id] = entity['values'].get('name', '')
logger.debug(f"Found {group_count} groups in response, lookup has {len(groups_lookup)} entries")
# Filter entities for activities
activities = [
entity for entity in result['entities']
if isinstance(entity, dict) and entity.get('entityType') == 'activity'
]
# Transform entities to standard activity format
transformed_activities = []
for activity in activities:
values = activity.get('values', {})
if isinstance(values, dict) and 'timeInterval' in values:
time_interval = values.get('timeInterval', {})
start_time = time_interval.get('start', '')
duration_seconds = time_interval.get('duration', 0)
# Calculate end time from start and duration
end_time = ''
if start_time:
try:
from dateutil import parser
from datetime import timedelta
start_dt = parser.parse(start_time)
end_dt = start_dt + timedelta(seconds=duration_seconds)
end_time = end_dt.isoformat()
except Exception as e:
logger.warning(f"Error calculating end time: {str(e)}")
# Get activity name/title
name = values.get('name', '')
# Extract tags from group entities
tags = []
group_list_id = values.get('groupListId')
if group_list_id:
# Find the groupList entity
group_list = next((
entity for entity in result['entities']
if entity.get('entityType') == 'groupList' and entity.get('entityId') == group_list_id
), None)
if group_list and 'values' in group_list and 'groupIds' in group_list['values']:
group_ids = group_list['values']['groupIds']
# Find all group entities with these IDs
groups = [
entity for entity in result['entities']
if entity.get('entityType') == 'group' and entity.get('entityId') in group_ids
]
# Extract names from groups
for group in groups:
if 'values' in group and 'name' in group['values']:
tag_name = group['values']['name']
if tag_name:
tags.append(tag_name)
# Create standardized activity data - ensure ID is present and properly formatted
entity_id = activity.get('entityId')
# Convert entityId to string if it exists, otherwise use empty string
entity_id_str = str(entity_id) if entity_id is not None else ''
# Log the entityId for debugging
logger.debug(f"Processing activity with entityId: {entity_id} (type: {type(entity_id)})")
# Look up application name from groupId
group_id = values.get('groupId')
application_name = ''
if group_id and group_id in groups_lookup:
application_name = groups_lookup[group_id]
logger.debug(f"Found application '{application_name}' for groupId {group_id}")
elif group_id:
logger.debug(f"No group found for groupId {group_id} in lookup of {len(groups_lookup)} groups")
activity_data = {
'id': entity_id_str, # Use string representation as ID
'entityId': entity_id, # Keep original entityId for reference
'title': name,
'start': start_time,
'end': end_time,
'duration': duration_seconds,
'tags': tags,
'groupId': group_id,
'application': application_name, # Add resolved application name
}
transformed_activities.append(activity_data)
# Add standardized activities to result
result['activities'] = transformed_activities
logger.debug(f"Extracted {len(transformed_activities)} activities from entities")
else:
# No entities found, create empty activities list
logger.warning(f"Response doesn't contain 'entities' array. Keys: {list(result.keys())}")
result['activities'] = []
else:
# Unexpected response type, create empty result
logger.warning(f"Unexpected response type: {type(result)}")
result = {'activities': []}
return result
except Exception as e:
logger.error(f"Error fetching activities for timeline {timeline_id}: {str(e)}")
raise
def get_timelines(self) -> List[Dict[str, Any]]:
"""
Get list of timelines
"""
url = f"{self.config.server_url}/api/timelines"
response = self._make_request(url, "GET")
# Extract timelines array from response
if isinstance(response, dict) and 'timelines' in response:
timelines = response['timelines']
logger.debug(f"Retrieved {len(timelines)} timelines")
return timelines
elif isinstance(response, list):
# Response is already a list
logger.debug(f"Retrieved {len(response)} timelines")
return response
else:
logger.warning(f"Unexpected timelines response format: {type(response)}")
return []
def discover_users_from_timelines(self) -> Dict[str, Dict[str, Any]]:
"""
Discover unique users from timeline data
Returns:
Dictionary mapping username to user info including display name and timeline count
"""
timelines = self.get_timelines()
users = {}
for timeline in timelines:
# Extract owner information from timeline
owner = timeline.get('owner', {})
# ManicTime API uses 'username' field, not 'name'
username = owner.get('username') or owner.get('name')
if username:
if username not in users:
users[username] = {
'username': username,
'display_name': owner.get('displayName', username),
'email': owner.get('email', ''), # May not be present
'timeline_count': 0,
'timelines': []
}
users[username]['timeline_count'] += 1
users[username]['timelines'].append({
'key': timeline.get('timelineKey'),
'device': timeline.get('deviceDisplayName', 'Unknown Device')
})
logger.debug(f"Discovered {len(users)} unique users from {len(timelines)} timelines")
return users
def get_tag_combinations(self, include_all_users: bool = False) -> List[Dict[str, Any]]:
"""
Get list of tag combinations
Args:
include_all_users: If True, fetch tags for all users (admin only)
Returns:
List of tag combinations
"""
if include_all_users:
# Admin endpoint to get tags for all users
url = f"{self.config.server_url}/api/tagcombinationlist?getAll=true"
logger.debug("Fetching tag combinations for all users (admin endpoint)")
else:
# Standard endpoint for current user's tags
url = f"{self.config.server_url}/api/tagcombinationlist"
logger.debug("Fetching tag combinations for current user")
# Add appropriate accept header for v3 API
headers = {"Accept": "application/vnd.manictime.v3+json"}
try:
response = self._make_request(url, "GET", headers=headers)
logger.debug(f"Retrieved {len(response)} tag combinations")
return response
except ManicTimeClientError as e:
# If the admin endpoint fails, fall back to the standard endpoint
if include_all_users:
logger.warning(f"Admin tag endpoint failed: {str(e)}. Falling back to user endpoint.")
return self.get_tag_combinations(include_all_users=False)
# Re-raise the error for the standard endpoint
raise
def get_activities_for_date_range(self,
timeline_id: str,
start_date: datetime,
end_date: datetime,
batch_size: timedelta = timedelta(days=7),
activities_url: str = None) -> List[Activity]:
"""
Get all activities between two dates, handling pagination
Args:
timeline_id: The timeline to query
start_date: Start date (inclusive)
end_date: End date (inclusive)
batch_size: How much data to request at once (default 7 days)
activities_url: Optional direct URL to the activities endpoint
Returns:
List of Activity objects
"""
all_activities = []
current_start = start_date
while current_start <= end_date:
current_end = min(current_start + batch_size, end_date)
logger.debug(f"Fetching activities from {current_start} to {current_end}")
batch = self.get_activities(
timeline_id,
current_start,
current_end,
activities_url=activities_url
)
# Handle the case where batch might not be a dictionary
if not isinstance(batch, dict):
logger.warning(f"Unexpected format in activities response: {type(batch)}")
activities = []
else:
# Safely extract activities from the response
activity_data = batch.get("activities", [])
if not isinstance(activity_data, list):
logger.warning(f"Activities field is not a list: {type(activity_data)}")
activities = []
else:
activities = []
for a in activity_data:
try:
activities.append(Activity.from_dict(a))
except Exception as e:
logger.error(f"Failed to parse activity: {str(e)}")
# Continue with other activities
all_activities.extend(activities)
logger.debug(f"Retrieved {len(activities)} activities")
current_start = current_end + timedelta(seconds=1)
return all_activities
def get_all_timeline_activities(self,
start_date: datetime,
end_date: datetime) -> Dict[str, List[Activity]]:
"""
Get activities for all timelines in a date range
Args:
start_date: Start date (inclusive)
end_date: End date (inclusive)
Returns:
Dict mapping timeline IDs to lists of activities
"""
results = {}
timelines = self.get_timelines()
for timeline in timelines:
timeline_id = timeline["timelineId"]
logger.debug(f"Fetching activities for timeline {timeline_id}")
try:
activities = self.get_activities_for_date_range(
timeline_id,
start_date,
end_date
)
results[timeline_id] = activities
except NotFoundError:
logger.warning(f"Timeline {timeline_id} not found or no access")
continue
return results
def get_daily_activities(self,
start_date: datetime,
end_date: datetime) -> List[Dict[str, Any]]:
"""
Get activities for all timelines grouped by day
Args:
start_date: Start date (inclusive)
end_date: End date (inclusive)
Returns:
List of dictionaries with day and timeline activities
"""
all_activities = self.get_all_timeline_activities(start_date, end_date)
daily_data = []
# Create a dictionary for each day in the range
current_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0)
while current_date <= end_date:
next_date = current_date + timedelta(days=1)
day_data = {
"date": current_date.date().isoformat(),
"timelines": {}
}
# Filter activities for this day for each timeline
for timeline_id, activities in all_activities.items():
day_activities = [
activity for activity in activities
if current_date <= activity.start < next_date
]
if day_activities:
timeline_data = {
"activities": [
{
"start": activity.start.isoformat(),
"end": activity.end.isoformat(),
"title": activity.title,
"application": activity.application,
"duration_seconds": activity.duration.total_seconds(),
"tags": activity.tags,
"notes": activity.notes
}
for activity in day_activities
],
"total_seconds": sum(a.duration.total_seconds() for a in day_activities)
}
day_data["timelines"][timeline_id] = timeline_data
if day_data["timelines"]:
daily_data.append(day_data)
current_date = next_date
return daily_data
def create_tag_combination(self, name: str, tags: List[str], description: str = None,
color: str = None) -> Dict[str, Any]:
"""
Create a new tag combination
Args:
name: Name of the tag combination
tags: List of tag names to include
description: Optional description
color: Optional color (hex code)
Returns:
Created tag combination data
"""
url = f"{self.config.server_url}/api/tags"
data = {
"name": name,
"tags": tags
}
if description:
data["description"] = description
if color:
data["color"] = color
logger.info(f"Creating tag combination: {name}")
return self._make_request(url, method="POST", data=data)
def update_tag_combination(self, combination_id: str, name: str = None,
tags: List[str] = None, description: str = None,
color: str = None) -> Dict[str, Any]:
"""
Update an existing tag combination
Args:
combination_id: ID of the tag combination to update
name: New name (optional)
tags: New list of tags (optional)
description: New description (optional)
color: New color (optional)
Returns:
Updated tag combination data
"""
url = f"{self.config.server_url}/api/tags/{combination_id}"
data = {}
if name:
data["name"] = name
if tags:
data["tags"] = tags
if description:
data["description"] = description
if color:
data["color"] = color
logger.info(f"Updating tag combination: {combination_id}")
return self._make_request(url, method="PUT", data=data)
def delete_tag_combination(self, combination_id: str) -> None:
"""
Delete a tag combination
Args:
combination_id: ID of the tag combination to delete
"""
url = f"{self.config.server_url}/api/tags/{combination_id}"
logger.info(f"Deleting tag combination: {combination_id}")
return self._make_request(url, method="DELETE")
# Query builder for more flexible activity queries
def activity_query(self):
"""
Create a fluent query interface for activities
Returns:
ActivityQueryBuilder instance
"""
return ActivityQueryBuilder(self)
# Export methods
def export_activities_to_csv(self, activities: List[Activity],
filename: Optional[str] = None) -> Union[str, None]:
"""
Export activities to CSV format
Args:
activities: List of Activity objects
filename: Optional filename to write to
Returns:
CSV string if filename is None, otherwise None
"""
records = []
for activity in activities:
record = {
"start": activity.start,
"end": activity.end,
"duration_seconds": activity.duration.total_seconds(),
"title": activity.title,
"application": activity.application,
"notes": activity.notes or "",
"tags": ",".join(activity.tags)
}
records.append(record)
df = pd.DataFrame(records)
if filename:
df.to_csv(filename, index=False)
logger.info(f"Exported {len(activities)} activities to {filename}")
return None
else:
csv_string = StringIO()
df.to_csv(csv_string, index=False)
return csv_string.getvalue()
def export_activities_to_excel(self, activities: List[Activity],
filename: str) -> None:
"""
Export activities to Excel format
Args:
activities: List of Activity objects
filename: Filename to write to
"""
records = []
for activity in activities:
record = {
"start": activity.start,
"end": activity.end,
"duration_seconds": activity.duration.total_seconds(),
"title": activity.title,
"application": activity.application,
"notes": activity.notes or "",
"tags": ",".join(activity.tags)
}
records.append(record)
df = pd.DataFrame(records)
df.to_excel(filename, index=False)
logger.info(f"Exported {len(activities)} activities to {filename}")
def export_activities_to_json(self, activities: List[Activity],
filename: Optional[str] = None) -> Union[str, None]:
"""
Export activities to JSON format
Args:
activities: List of Activity objects
filename: Optional filename to write to
Returns:
JSON string if filename is None, otherwise None
"""
records = []
for activity in activities:
record = {
"start": activity.start.isoformat(),
"end": activity.end.isoformat(),
"duration_seconds": activity.duration.total_seconds(),
"title": activity.title,
"application": activity.application,
"notes": activity.notes or "",
"tags": activity.tags
}
records.append(record)
if filename:
with open(filename, 'w', encoding='utf-8') as f:
json.dump(records, f, ensure_ascii=False, indent=2)
logger.info(f"Exported {len(activities)} activities to {filename}")
return None
else:
return json.dumps(records, ensure_ascii=False, indent=2)
def export_activities_to_html(self, activities: List[Activity],
filename: str,
title: str = "ManicTime Activities") -> None:
"""
Export activities to HTML format
Args:
activities: List of Activity objects
filename: Filename to write to
title: Title for the HTML page
"""
records = []
for activity in activities:
records.append({
"start": activity.start.strftime("%Y-%m-%d %H:%M:%S"),
"end": activity.end.strftime("%Y-%m-%d %H:%M:%S"),
"duration": str(activity.duration).split('.')[0], # Remove microseconds
"title": activity.title,
"application": activity.application,
"notes": activity.notes or "",
"tags": ", ".join(activity.tags)
})
df = pd.DataFrame(records)
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{title}</title>
<style>
body {{
font-family: Arial, sans-serif;
margin: 20px;
line-height: 1.6;
}}
h1 {{
color: #333;
}}
table {{
border-collapse: collapse;
width: 100%;
margin-top: 20px;
}}
th, td {{
padding: 12px 15px;
border-bottom: 1px solid #ddd;
text-align: left;
}}
th {{
background-color: #f2f2f2;
color: #333;
}}
tr:hover {{
background-color: #f5f5f5;
}}
.summary {{
margin-top: 20px;
padding: 15px;
background-color: #f2f2f2;
border-radius: 5px;
}}
</style>
</head>
<body>
<h1>{title}</h1>
<div class="summary">
<p>Total activities: {len(activities)}</p>
<p>Total duration: {str(timedelta(seconds=sum(a.duration.total_seconds() for a in activities))).split('.')[0]}</p>
<p>Date range: {min(a.start for a in activities).strftime('%Y-%m-%d')} to {max(a.end for a in activities).strftime('%Y-%m-%d')}</p>
</div>
{df.to_html(index=False)}
</body>
</html>
"""
with open(filename, 'w', encoding='utf-8') as f:
f.write(html_content)
logger.info(f"Exported {len(activities)} activities to HTML file {filename}")
# Statistical Analysis Features
def get_activity_statistics(self, activities: List[Activity]) -> Dict[str, Any]:
"""
Generate statistical metrics for a list of activities
Args:
activities: List of Activity objects
Returns:
Dictionary with statistical metrics
"""
if not activities:
return {
"total_count": 0,
"total_duration_seconds": 0,
"average_duration_seconds": 0,
"min_duration_seconds": 0,
"max_duration_seconds": 0,
"total_days": 0
}
# Calculate total duration
total_duration_seconds = sum(a.duration.total_seconds() for a in activities)
# Calculate min and max duration
min_duration = min(activities, key=lambda a: a.duration).duration
max_duration = max(activities, key=lambda a: a.duration).duration
# Calculate average duration
avg_duration = timedelta(seconds=total_duration_seconds / len(activities))
# Find unique dates
unique_dates = set(a.start.date() for a in activities)
# Group activities by application
apps = {}
for activity in activities:
app = activity.application
if app not in apps:
apps[app] = []
apps[app].append(activity)
# Calculate duration per application
app_durations = {}
for app, app_activities in apps.items():
app_durations[app] = sum(a.duration.total_seconds() for a in app_activities)
# Sort applications by duration (descending)
sorted_apps = sorted(app_durations.items(), key=lambda x: x[1], reverse=True)
# Group activities by tags
tags = {}
for activity in activities:
for tag in activity.tags:
if tag not in tags:
tags[tag] = []
tags[tag].append(activity)
# Calculate duration per tag
tag_durations = {}
for tag, tag_activities in tags.items():
tag_durations[tag] = sum(a.duration.total_seconds() for a in tag_activities)
# Sort tags by duration (descending)
sorted_tags = sorted(tag_durations.items(), key=lambda x: x[1], reverse=True)
return {
"total_count": len(activities),
"total_duration_seconds": total_duration_seconds,
"average_duration_seconds": avg_duration.total_seconds(),
"min_duration_seconds": min_duration.total_seconds(),
"max_duration_seconds": max_duration.total_seconds(),
"total_days": len(unique_dates),
"applications": {
"count": len(apps),
"durations": {app: duration for app, duration in sorted_apps[:10]}
},
"tags": {
"count": len(tags),
"durations": {tag: duration for tag, duration in sorted_tags[:10]}
}
}
def get_daily_summary(self, activities: List[Activity]) -> Dict[str, Dict[str, float]]:
"""
Generate daily summary of activity durations
Args:
activities: List of Activity objects
Returns:
Dictionary mapping dates to duration summaries
"""
daily_summary = {}
for activity in activities:
date_str = activity.start.date().isoformat()
if date_str not in daily_summary:
daily_summary[date_str] = {
"total_seconds": 0,
"applications": {},