things.api
Module implementing the Things API.
The terms of the API aim to match those used in the Things app and Things URL Scheme. In some specific cases we instead choose to use terms that occur in the Things SQL database to closer reflect its underlying data structures. Whenever that happens, we define the new term here.
1""" 2Module implementing the Things API. 3 4The terms of the API aim to match those used in the Things app and 5Things URL Scheme. In some specific cases we instead choose to use terms 6that occur in the Things SQL database to closer reflect its underlying 7data structures. Whenever that happens, we define the new term here. 8""" 9 10import os # pylint: disable=C0412 11from shlex import quote 12import urllib.parse 13 14from things.database import Database 15 16 17# -------------------------------------------------- 18# Core functions 19# -------------------------------------------------- 20 21 22def tasks(uuid=None, include_items=False, **kwargs): # noqa: C901 23 """ 24 Read tasks into dicts. 25 26 Note: "task" is a technical term used in the database to refer to a 27 to-do, project, or heading. For details, check the "type"-parameter. 28 29 Per default, only tasks marked as incomplete are included. If you 30 want to include completed or canceled tasks in the result, check the 31 "status"-parameter. 32 33 Parameters 34 ---------- 35 uuid : str or None, optional 36 Any valid task uuid. If None, then return all tasks matched. 37 38 include_items : bool, default False 39 Include items contained within a task. These might include 40 checklist items, headings, and to-dos. 41 42 type : {'to-do', 'heading', 'project', None}, optional 43 Only return a specific type of task: 44 - `'to-do'`: may have a checklist; may be in an area and have tags. 45 - `'project'`: may have to-dos and headings; may be in an area and 46 have tags. 47 - `'heading'`: part of a project; groups tasks. 48 - `None` (default): return all types of tasks. 49 50 status : {'incomplete', 'completed', 'canceled', None}, optional, \ 51 default 'incomplete' 52 53 Only include tasks matching that status. If `status == None`, 54 then include tasks with any status value. 55 56 start : {'Inbox', 'Anytime', 'Someday', None}, optional 57 Only include tasks matching that start value. If the argument is 58 `None` (default), then include tasks with any start value. 59 60 area : str or bool or None, optional 61 Any valid uuid of an area. Only include tasks matching that area. 62 Special cases: 63 - `area == False`, only include tasks _without_ an area. 64 - `area == True`, only include tasks _with_ an area. 65 - `area == None` (default), then include all tasks. 66 67 project : str or bool or None, optional 68 Any valid uuid of a project. Only include tasks matching that project. 69 Special cases: 70 - `project == False`, only include tasks _without_ a project. 71 - `project == True`, only include tasks _with_ a project. 72 - `project == None` (default), then include all tasks. 73 74 heading : str or None, optional 75 Any valid uuid of a heading. Only include tasks matching that heading. 76 Special cases: 77 - `heading == False`, only include tasks _without_ a heading. 78 - `heading == True`, only include tasks _with_ a heading. 79 - `heading == None` (default), then include all tasks. 80 81 tag : str or bool or None, optional 82 Any valid title of a tag. Only include tasks matching that tag. 83 Special cases: 84 - `tag == False`, only include tasks _without_ tags. 85 - `tag == True`, only include tasks _with_ tags. 86 - `tag == None` (default), then include all tasks. 87 88 start_date : bool, str or None, optional 89 - `start_date == False`, only include tasks _without_ a start date. 90 - `start_date == True`, only include tasks with a start date. 91 - `start_date == 'future'`, only include tasks with a future start date. 92 - `start_date == 'past'`, only include tasks with a past start date. 93 Note: this includes today's date. 94 - `start_date == '[operator]YYYY-MM-DD'`; match with optional operator, 95 for example: '2023-05-22', '<=2023-05-22', or '>2023-05-22'. 96 - `start_date == None` (default), then include all tasks. 97 98 stop_date : same options as start_date, signifies the date of completion 99 100 deadline : same options as start_date, signifies the deadline 101 102 deadline_suppressed : bool or None, optional 103 "deadline suppressed" is a technical term used in the database. 104 When tasks have an overdue deadline they show up in Today. 105 Some of us "suppress" some tasks, that is, move them out of 106 Today and into Inbox, Anytime, or Someday. For those moved tasks 107 the deadline is said to be suppressed. 108 - `deadline_suppressed == True`, only include tasks with deadlines 109 and whose deadlines have been suppressed. 110 - `deadline_suppressed == False`, include any task _except_ those 111 with suppressed deadlines. 112 - `deadline_suppressed == None` (default), include any task. 113 114 trashed : bool or None, optional, default False 115 - `trashed == False` (default), only include non-trashed tasks. 116 - `trashed == True`, only include trashed tasks. 117 - `trashed == None`, include both kind of tasks. 118 119 context_trashed : bool or None, optional, default False 120 Some tasks may be within a context of a project or a heading. 121 This manages how to handle such tasks. The other tasks are not 122 affected by this setting. 123 124 - `context_trashed == False` (default), for tasks within a context, 125 only return tasks whose context has _not_ been trashed. 126 - `context_trashed == True`, for tasks within a context, 127 only return tasks whose context has been trashed. 128 - `context_trashed == None`, include both kind of tasks. 129 130 is_repeating_template : bool or None, optional, default False 131 A repeating to-do is stored as a template, from which Things 132 creates each instance. A template has no start date; instead it 133 carries `next_instance_start_date`, the date Things will create 134 the next instance. Only templates have that field. 135 - `is_repeating_template == False` (default), exclude templates. 136 - `is_repeating_template == True`, only include templates. 137 - `is_repeating_template == None`, include both kind of tasks. 138 139 next_instance_start_date : same options as start_date, signifies the date 140 Things will create the next instance of a repeating to-do (templates only) 141 142 last : str, optional 143 Limit returned tasks to tasks created within the last X days, 144 weeks, or years. For example: '3d', '5w', or '1y'. 145 146 Takes as input an offset string of the format 'X[d/w/y]' where X 147 is a non-negative integer that is followed by 'd', 'w', or 'y' 148 which stand for 'days', 'weeks', and 'years', respectively. 149 150 search_query : str, optional 151 The string value is passed to the SQL LIKE operator. It can thus 152 include placeholders such as '%' and '_'. Per default, it is 153 wrapped in '% ... %'. 154 155 Currently titles and notes of to-dos, projects, headings, and areas 156 are taken into account. 157 158 index : {'index', 'todayIndex'}, default 'index' 159 Database field to order result by. 160 161 count_only : bool, default False 162 Only output length of result. This is done by a SQL COUNT query. 163 164 print_sql : bool, default False 165 Print every SQL query performed. Some may contain '?' and ':' 166 characters, which correspond to SQLite parameter tokens. 167 See https://www.sqlite.org/lang_expr.html#varparam 168 169 filepath : str, optional 170 Any valid path of a SQLite database file generated by the Things app. 171 If the environment variable `THINGSDB` is set, then use that path. 172 Otherwise, access the default database path. 173 174 database : things.database.Database, optional 175 Any valid database object previously instantiated. 176 177 Returns 178 ------- 179 list of dict (default) 180 Representing multiple tasks. 181 dict (if `uuid` is given) 182 Representing a single task. 183 int (`count_only == True`) 184 Count of matching Tasks. 185 186 Examples 187 -------- 188 >>> things.tasks() 189 [{'uuid': '6Hf2qWBjWhq7B1xszwdo34', 'type': 'to-do', 'title':... 190 >>> things.tasks('DfYoiXcNLQssk9DkSoJV3Y') 191 {'uuid': 'DfYoiXcNLQssk9DkSoJV3Y', 'type': 'to-do', 'title': ... 192 >>> things.tasks(area='hIo1FJlAYGKt1Yj38vzKc3', include_items=True) 193 [] 194 >>> things.tasks(status='completed', count_only=True) 195 12 196 >>> things.tasks(status='completed', last='1w', count_only=True) 197 0 198 >>> things.tasks(is_repeating_template=True) 199 [{'uuid': 'N1PJHsbjct4mb1bhcs7aHa', 'type': 'to-do', 'title': 'Repeating To-Do', ... 200 201 """ 202 database = pop_database(kwargs) 203 result = database.get_tasks( 204 uuid=uuid, status=kwargs.pop("status", "incomplete"), **kwargs 205 ) 206 207 if kwargs.get("count_only"): 208 return result 209 210 # overwrite `include_items` if fetching a single task. 211 if uuid: 212 include_items = True 213 214 for task in result: 215 # TK: How costly of an operation is it to do this for every task? 216 # IF costly, then can it be made significantly more efficient 217 # by optimizing SQL calls? 218 219 if task.get("tags"): 220 task["tags"] = database.get_tags(task=task["uuid"]) 221 222 if not include_items: 223 continue 224 225 # include items 226 if task["type"] == "to-do": 227 if task.get("checklist"): 228 task["checklist"] = database.get_checklist_items(task["uuid"]) 229 elif task["type"] == "project": 230 project = task 231 project["items"] = items = tasks( 232 project=project["uuid"], 233 context_trashed=None, 234 include_items=True, 235 database=database, 236 ) 237 # to-dos without headings appear before headings in app 238 items.sort(key=lambda item: item["type"], reverse=True) 239 elif task["type"] == "heading": 240 heading = task 241 heading["items"] = tasks( 242 type="to-do", 243 heading=heading["uuid"], 244 context_trashed=None, 245 include_items=True, 246 database=database, 247 ) 248 249 if uuid: 250 result = result[0] 251 252 return result 253 254 255def areas(uuid=None, include_items=False, **kwargs): 256 """ 257 Read areas into dicts. 258 259 Parameters 260 ---------- 261 uuid : str or None, optional 262 Any valid uuid of an area. If None, then return all areas. 263 264 include_items : bool, default False 265 Include tasks and projects in each area. 266 267 tag : str or bool or None, optional 268 Any valid title of a tag. Only include areas matching that tag. 269 Special cases: 270 - `tag == False`, only include areas _without_ tags. 271 - `tag == True`, only include areas _with_ tags. 272 - `tag == None`, then ignore any tags present, that is, 273 include areas both with and without tags. 274 275 count_only : bool, default False 276 Only output length of result. This is done by a SQL COUNT query. 277 278 filepath : str, optional 279 Any valid path of a SQLite database file generated by the Things app. 280 If no path is provided, then access the default database path. 281 282 database : things.database.Database, optional 283 Any valid `things.database.Database` object previously instantiated. 284 285 Returns 286 ------- 287 list of dict (default) 288 Representing Things areas. 289 dict (if `uuid` is given) 290 Representing a single Things area. 291 int (`count_only == True`) 292 Count of matching areas. 293 294 Examples 295 -------- 296 >>> things.areas() 297 [{'uuid': 'Y3JC4XeyGWxzDocQL4aobo', 'type': 'area', 'title': 'Area 3'}, ... 298 >>> things.areas(tag='Home') 299 [] 300 >>> things.areas(uuid='DciSFacytdrNG1nRaMJPgY') 301 {'uuid': 'DciSFacytdrNG1nRaMJPgY', 'type': 'area', 'title': 'Area 1', ... 302 >>> things.areas(include_items=True, tag='Errand') 303 [{'uuid': 'DciSFacytdrNG1nRaMJPgY', 'type': 'area', 'title': 'Area 1', ... 304 """ 305 database = pop_database(kwargs) 306 result = database.get_areas(uuid=uuid, **kwargs) 307 308 if kwargs.get("count_only"): 309 return result 310 311 for area in result: 312 if area.get("tags"): 313 area["tags"] = database.get_tags(area=area["uuid"]) 314 if include_items: 315 area["items"] = tasks( 316 area=area["uuid"], include_items=True, database=database 317 ) 318 319 if uuid: 320 result = result[0] 321 322 return result 323 324 325def tags(title=None, include_items=False, **kwargs): 326 """ 327 Read tags into dicts. 328 329 Parameters 330 ---------- 331 title : str, optional 332 Any valid title of a tag. Include all items of said tag. 333 If None, then return all tags. 334 335 include_items : bool, default False 336 For each tag, include items tagged with that tag. 337 Items may include areas, tasks, and projects. 338 339 area : str, optional 340 Valid uuid of an area. Return tags of said area. 341 342 task : str, optional 343 Valid uuid of a task. Return tags of said task. 344 345 titles_only : bool, default False 346 If True, only return list of titles of tags. 347 348 filepath : str, optional 349 Any valid path of a SQLite database file generated by the Things app. 350 If no path is provided, then access the default database path. 351 352 database : things.database.Database, optional 353 Any valid database object previously instantiated. 354 355 Returns 356 ------- 357 list of dict (default) 358 Representing tags. 359 list of str (if `titles_only == True` or area / task is given) 360 Representing tag titles. 361 dict (if `title` is given) 362 Representing a single Things tag. 363 364 Examples 365 -------- 366 >>> things.tags() 367 [{'uuid': 'H96sVJwE7VJveAnv7itmux', 'type': 'tag', 'title': 'Errand', ... 368 >>> things.tags('Home') 369 {'uuid': 'CK9dARrf2ezbFvrVUUxkHE', 'type': 'tag', 'title': 'Home', ... 370 >>> things.tags(include_items=True) 371 [{'uuid': 'H96sVJwE7VJveAnv7itmux', 'type': 'tag', 'title': 'Errand', ... 372 >>> things.tags(task='2Ukg8I2nLukhyEM7wYiBeb') 373 [] 374 """ 375 database = pop_database(kwargs) 376 result = database.get_tags(title=title, **kwargs) 377 378 if include_items: 379 for tag in result: 380 tag_title = tag["title"] 381 tag["items"] = [ 382 *areas(tag=tag_title, database=database), 383 *tasks(tag=tag_title, database=database), 384 ] 385 386 if title: 387 result = result[0] 388 389 return result 390 391 392def checklist_items(todo_uuid, **kwargs): 393 """ 394 Read checklist items of to-dos into dicts. 395 396 Note: checklists are contained in the return value of 397 `things.todos(todo_uuid)` and `things.tasks(todo_uuid)`. 398 399 Parameters 400 ---------- 401 todo_uuid : str, optional 402 A valid to-do uuid. 403 404 Returns 405 ------- 406 list of dict 407 Checklist items. 408 """ 409 database = pop_database(kwargs) 410 return database.get_checklist_items(todo_uuid=todo_uuid) 411 412 413# -------------------------------------------------- 414# Utility API functions derived from above 415# -------------------------------------------------- 416 417 418def search(query: str, **kwargs) -> list[dict]: 419 """ 420 Search tasks in the database. 421 422 Currently any part of a title and note of a to-do, project, 423 heading, or area is matched. 424 425 See the `search_query` parameter of `things.api.tasks` for details. 426 427 Examples 428 -------- 429 >>> things.search('Today%yellow') 430 [{'uuid': '6Hf2qWBjWhq7B1xszwdo34', 431 'type': 'to-do', 432 'title': 'Upcoming To-Do in Today (yellow)', 433 'status': 'incomplete', 434 'notes': '', 435 ... 436 """ 437 return tasks(search_query=query, **kwargs) 438 439 440def get(uuid, default=None, **kwargs): 441 """ 442 Find an object by uuid. If not found, return `default`. 443 444 Currently supports tasks, projects, headings, areas, and tags. 445 """ 446 try: 447 return tasks(uuid=uuid, **kwargs) 448 except ValueError: 449 pass 450 451 try: 452 return areas(uuid=uuid, **kwargs) 453 except ValueError: 454 pass 455 456 for tag in tags(**kwargs): 457 if tag["uuid"] == uuid: 458 return tag 459 460 return default 461 462 463# Filter by object type 464 465 466def todos(uuid=None, **kwargs): 467 """ 468 Read to-dos into dicts. 469 470 See `things.api.tasks` for details on the optional parameters. 471 """ 472 return tasks(uuid=uuid, type="to-do", **kwargs) 473 474 475def projects(uuid=None, **kwargs): 476 """ 477 Read projects into dicts. 478 479 See `things.api.tasks` for details on the optional parameters. 480 """ 481 return tasks(uuid=uuid, type="project", **kwargs) 482 483 484# Filter by collections in the Things app sidebar. 485 486 487def inbox(**kwargs): 488 """ 489 Read Inbox into dicts. 490 491 See `things.api.tasks` for details on the optional parameters. 492 """ 493 return tasks(start="Inbox", **kwargs) 494 495 496def today(**kwargs): 497 """ 498 Read Today's tasks into dicts. 499 500 Note: The Things database reflects the state of the Things app when 501 it was last opened. For the Today tasks that means the database 502 might not be up to date anymore if you didn't open the app recently. 503 To get around this limitation, we here make a prediction of what 504 tasks would show up in Today if you were to open the app right now. 505 This prediction does not include repeating tasks at this time. 506 507 See `things.api.tasks` for details on the optional parameters. 508 """ 509 database = pop_database(kwargs) 510 kwargs["database"] = database 511 512 regular_today_tasks = tasks( 513 start_date=True, 514 start="Anytime", 515 index="todayIndex", 516 **kwargs, 517 ) 518 519 # Predictions of new to-dos indicated by a yellow dot in the app. 520 521 unconfirmed_scheduled_tasks = tasks( 522 start_date="past", 523 start="Someday", 524 index="todayIndex", 525 **kwargs, 526 ) 527 528 unconfirmed_overdue_tasks = tasks( 529 start_date=False, 530 deadline="past", 531 deadline_suppressed=False, 532 **kwargs, 533 ) 534 535 result = [ 536 *regular_today_tasks, 537 *unconfirmed_scheduled_tasks, 538 *unconfirmed_overdue_tasks, 539 ] 540 result.sort(key=lambda task: (task["today_index"], task["start_date"] or "")) 541 542 return result 543 544 545def upcoming(**kwargs): 546 """ 547 Read Upcoming tasks into dicts. 548 549 The output aims to be in the same order as Upcoming in Things.app. 550 Repeating to-dos use `next_instance_start_date` instead of `start_date`. 551 552 Note: unscheduled tasks with a deadline are not included here. 553 See the `things.api.deadlines` function instead. 554 555 For details on parameters, see `things.api.tasks`. 556 """ 557 database = pop_database(kwargs) 558 kwargs["database"] = database 559 560 scheduled = tasks(start_date="future", start="Someday", **kwargs) 561 repeating = tasks( 562 is_repeating_template=True, 563 next_instance_start_date="future", 564 start="Someday", 565 **kwargs, 566 ) 567 if kwargs.get("count_only"): 568 return scheduled + repeating 569 570 result = [*scheduled, *repeating] 571 result.sort( 572 key=lambda task: ( 573 task["start_date"] or task["next_instance_start_date"], 574 task["today_index"], 575 task["index"], 576 ) 577 ) 578 return result 579 580 581def anytime(**kwargs): 582 """ 583 Read Anytime tasks into dicts. 584 585 See `things.api.tasks` for details on the optional parameters. 586 """ 587 return tasks(start="Anytime", **kwargs) 588 589 590def someday(**kwargs): 591 """ 592 Read Someday tasks into dicts. 593 594 See `things.api.tasks` for details on the optional parameters. 595 """ 596 return tasks(start_date=False, start="Someday", **kwargs) 597 598 599def logbook(**kwargs): 600 """ 601 Read Logbook tasks into dicts. 602 603 See `things.api.tasks` for details on the optional parameters. 604 """ 605 result = [*canceled(**kwargs), *completed(**kwargs)] 606 result.sort(key=lambda task: task["stop_date"], reverse=True) 607 return result 608 609 610def trash(**kwargs): 611 """ 612 Read Trash tasks into dicts. 613 614 See `things.api.tasks` for details on the optional parameters. 615 """ 616 return tasks( 617 trashed=True, 618 context_trashed=kwargs.pop("context_trashed", None), 619 status=kwargs.pop("status", None), 620 **kwargs, 621 ) 622 623 624# Filter by various task properties 625 626 627def canceled(**kwargs): 628 """ 629 Read canceled tasks into dicts. 630 631 See `things.api.tasks` for details on the optional parameters. 632 """ 633 return tasks(status="canceled", **kwargs) 634 635 636def completed(**kwargs): 637 """ 638 Read completed tasks into dicts. 639 640 See `things.api.tasks` for details on the optional parameters. 641 642 Examples 643 -------- 644 >>> things.completed(count_only=True) 645 12 646 >>> things.completed(type='project', count_only=True) 647 0 648 >>> things.completed(type='to-do', last='1w') 649 [] 650 """ 651 return tasks(status="completed", **kwargs) 652 653 654def deadlines(**kwargs): 655 """ 656 Read tasks with deadlines into dicts. 657 658 See `things.api.tasks` for details on the optional parameters. 659 """ 660 result = tasks(deadline=True, **kwargs) 661 result.sort(key=lambda task: task["deadline"]) 662 return result 663 664 665def last(offset, **kwargs): 666 """ 667 Read tasks created within last X days, weeks, or years into dicts. 668 669 Per default, only incomplete tasks are included, but do see 670 `things.api.tasks` for details on the optional parameters. 671 672 Parameters 673 ---------- 674 offset : str 675 A valid date offset such as '3d', '5w', or '1y'. 676 For details, see the `last` parameter of `things.api.tasks`. 677 678 Returns 679 ------- 680 list of dict 681 Tasks within offset ordered by creation date. Newest first. 682 683 Examples 684 -------- 685 >>> things.last('3d') 686 [] 687 >>> things.last('1w', status='completed') 688 [] 689 >>> things.last('1y', tag='Important', status='completed', count_only=True) 690 0 691 692 """ 693 if offset is None: 694 raise ValueError(f"Invalid offset type: {offset!r}") 695 696 result = tasks(last=offset, **kwargs) 697 if result: 698 result.sort(key=lambda task: task["created"], reverse=True) 699 700 return result 701 702 703# Interact with Things app 704 705 706def token(**kwargs) -> str | None: 707 """ 708 Read the Things URL scheme authentication token. 709 710 You can make good use of this token to modify existing Things data 711 using the Things URL Scheme. For details, see 712 [here](https://culturedcode.com/things/help/url-scheme/). 713 """ 714 database = pop_database(kwargs) 715 return database.get_url_scheme_auth_token() 716 717 718def url(uuid=None, command="show", **query_parameters) -> str: 719 """ 720 Return a things:///<command>?<query> url. 721 722 For details about available commands and their parameters 723 consult the Things URL Scheme documentation 724 [here](https://culturedcode.com/things/help/url-scheme/). 725 726 Parameters 727 ---------- 728 uuid : str or None, optional 729 A valid uuid of any Things object. 730 If `None`, then 'id' is not added as a parameter unless 731 specified in `query_parameters`. 732 733 command : str, default 'show' 734 A valid command name. 735 736 **query_parameters: 737 Additional URL query parameters. 738 739 Examples 740 -------- 741 >>> things.url('6Hf2qWBjWhq7B1xszwdo34') 742 'things:///show?id=6Hf2qWBjWhq7B1xszwdo34' 743 >>> things.url(command='update', uuid='6Hf2qWBjWhq7B1xszwdo34', title='new title') 744 'things:///update?id=6Hf2qWBjWhq7B1xszwdo34&title=new%20title&auth-token=vKkylosuSuGwxrz7qcklOw' 745 >>> things.url(command='add', title='new task', when='in 3 days', deadline='in 6 days') 746 'things:///add?title=new%20task&when=in%203%20days&deadline=in%206%20days' 747 >>> query_params = {'title': 'test title', 'list-id': 'ba5d1237-1dfa-4ab8-826b-7c27b517f29d'} 748 >>> things.url(command="add", **query_params) 749 'things:///add?title=test%20title&list-id=ba5d1237-1dfa-4ab8-826b-7c27b517f29d' 750 """ 751 if uuid is not None: 752 query_parameters = {"id": uuid, **query_parameters} 753 754 # authenticate if needed 755 if command in ("update", "update-project"): 756 auth_token = query_parameters["auth-token"] = token() 757 if not auth_token: 758 raise ValueError("Things URL scheme authentication token could not be read") 759 760 query_string = urllib.parse.urlencode( 761 query_parameters, quote_via=urllib.parse.quote 762 ) 763 764 return f"things:///{command}?{query_string}" 765 766 767# Alias for backwards compatiblity 768link = url 769 770 771def show(uuid): 772 """ 773 Show a certain uuid in the Things app. 774 775 Parameters 776 ---------- 777 uuid : str 778 A valid uuid of any Things object. 779 780 Examples 781 -------- 782 >>> tag = things.tags('Home') 783 >>> things.show(tag['uuid']) # doctest: +SKIP 784 """ 785 uri = url(uuid=uuid) 786 os.system(f"open {quote(uri)}") 787 788 789def complete(uuid): 790 """ 791 Set the status of a certain uuid to complete. 792 793 Parameters 794 ---------- 795 uuid : str 796 A valid uuid of a project or to-do. 797 798 Examples 799 -------- 800 >>> task = things.todos()[0] # doctest: +SKIP 801 >>> things.complete(task['uuid']) # doctest: +SKIP 802 """ 803 uri = url(uuid=uuid, command="update", completed=True) 804 os.system(f"open {quote(uri)}") 805 806 807# Helper functions 808 809 810def pop_database(kwargs): 811 """Instantiate non-default database from `kwargs` if provided.""" 812 filepath = kwargs.pop("filepath", None) 813 database = kwargs.pop("database", None) 814 print_sql = kwargs.pop("print_sql", False) 815 816 if not database: 817 database = Database(filepath=filepath, print_sql=print_sql) 818 return database
23def tasks(uuid=None, include_items=False, **kwargs): # noqa: C901 24 """ 25 Read tasks into dicts. 26 27 Note: "task" is a technical term used in the database to refer to a 28 to-do, project, or heading. For details, check the "type"-parameter. 29 30 Per default, only tasks marked as incomplete are included. If you 31 want to include completed or canceled tasks in the result, check the 32 "status"-parameter. 33 34 Parameters 35 ---------- 36 uuid : str or None, optional 37 Any valid task uuid. If None, then return all tasks matched. 38 39 include_items : bool, default False 40 Include items contained within a task. These might include 41 checklist items, headings, and to-dos. 42 43 type : {'to-do', 'heading', 'project', None}, optional 44 Only return a specific type of task: 45 - `'to-do'`: may have a checklist; may be in an area and have tags. 46 - `'project'`: may have to-dos and headings; may be in an area and 47 have tags. 48 - `'heading'`: part of a project; groups tasks. 49 - `None` (default): return all types of tasks. 50 51 status : {'incomplete', 'completed', 'canceled', None}, optional, \ 52 default 'incomplete' 53 54 Only include tasks matching that status. If `status == None`, 55 then include tasks with any status value. 56 57 start : {'Inbox', 'Anytime', 'Someday', None}, optional 58 Only include tasks matching that start value. If the argument is 59 `None` (default), then include tasks with any start value. 60 61 area : str or bool or None, optional 62 Any valid uuid of an area. Only include tasks matching that area. 63 Special cases: 64 - `area == False`, only include tasks _without_ an area. 65 - `area == True`, only include tasks _with_ an area. 66 - `area == None` (default), then include all tasks. 67 68 project : str or bool or None, optional 69 Any valid uuid of a project. Only include tasks matching that project. 70 Special cases: 71 - `project == False`, only include tasks _without_ a project. 72 - `project == True`, only include tasks _with_ a project. 73 - `project == None` (default), then include all tasks. 74 75 heading : str or None, optional 76 Any valid uuid of a heading. Only include tasks matching that heading. 77 Special cases: 78 - `heading == False`, only include tasks _without_ a heading. 79 - `heading == True`, only include tasks _with_ a heading. 80 - `heading == None` (default), then include all tasks. 81 82 tag : str or bool or None, optional 83 Any valid title of a tag. Only include tasks matching that tag. 84 Special cases: 85 - `tag == False`, only include tasks _without_ tags. 86 - `tag == True`, only include tasks _with_ tags. 87 - `tag == None` (default), then include all tasks. 88 89 start_date : bool, str or None, optional 90 - `start_date == False`, only include tasks _without_ a start date. 91 - `start_date == True`, only include tasks with a start date. 92 - `start_date == 'future'`, only include tasks with a future start date. 93 - `start_date == 'past'`, only include tasks with a past start date. 94 Note: this includes today's date. 95 - `start_date == '[operator]YYYY-MM-DD'`; match with optional operator, 96 for example: '2023-05-22', '<=2023-05-22', or '>2023-05-22'. 97 - `start_date == None` (default), then include all tasks. 98 99 stop_date : same options as start_date, signifies the date of completion 100 101 deadline : same options as start_date, signifies the deadline 102 103 deadline_suppressed : bool or None, optional 104 "deadline suppressed" is a technical term used in the database. 105 When tasks have an overdue deadline they show up in Today. 106 Some of us "suppress" some tasks, that is, move them out of 107 Today and into Inbox, Anytime, or Someday. For those moved tasks 108 the deadline is said to be suppressed. 109 - `deadline_suppressed == True`, only include tasks with deadlines 110 and whose deadlines have been suppressed. 111 - `deadline_suppressed == False`, include any task _except_ those 112 with suppressed deadlines. 113 - `deadline_suppressed == None` (default), include any task. 114 115 trashed : bool or None, optional, default False 116 - `trashed == False` (default), only include non-trashed tasks. 117 - `trashed == True`, only include trashed tasks. 118 - `trashed == None`, include both kind of tasks. 119 120 context_trashed : bool or None, optional, default False 121 Some tasks may be within a context of a project or a heading. 122 This manages how to handle such tasks. The other tasks are not 123 affected by this setting. 124 125 - `context_trashed == False` (default), for tasks within a context, 126 only return tasks whose context has _not_ been trashed. 127 - `context_trashed == True`, for tasks within a context, 128 only return tasks whose context has been trashed. 129 - `context_trashed == None`, include both kind of tasks. 130 131 is_repeating_template : bool or None, optional, default False 132 A repeating to-do is stored as a template, from which Things 133 creates each instance. A template has no start date; instead it 134 carries `next_instance_start_date`, the date Things will create 135 the next instance. Only templates have that field. 136 - `is_repeating_template == False` (default), exclude templates. 137 - `is_repeating_template == True`, only include templates. 138 - `is_repeating_template == None`, include both kind of tasks. 139 140 next_instance_start_date : same options as start_date, signifies the date 141 Things will create the next instance of a repeating to-do (templates only) 142 143 last : str, optional 144 Limit returned tasks to tasks created within the last X days, 145 weeks, or years. For example: '3d', '5w', or '1y'. 146 147 Takes as input an offset string of the format 'X[d/w/y]' where X 148 is a non-negative integer that is followed by 'd', 'w', or 'y' 149 which stand for 'days', 'weeks', and 'years', respectively. 150 151 search_query : str, optional 152 The string value is passed to the SQL LIKE operator. It can thus 153 include placeholders such as '%' and '_'. Per default, it is 154 wrapped in '% ... %'. 155 156 Currently titles and notes of to-dos, projects, headings, and areas 157 are taken into account. 158 159 index : {'index', 'todayIndex'}, default 'index' 160 Database field to order result by. 161 162 count_only : bool, default False 163 Only output length of result. This is done by a SQL COUNT query. 164 165 print_sql : bool, default False 166 Print every SQL query performed. Some may contain '?' and ':' 167 characters, which correspond to SQLite parameter tokens. 168 See https://www.sqlite.org/lang_expr.html#varparam 169 170 filepath : str, optional 171 Any valid path of a SQLite database file generated by the Things app. 172 If the environment variable `THINGSDB` is set, then use that path. 173 Otherwise, access the default database path. 174 175 database : things.database.Database, optional 176 Any valid database object previously instantiated. 177 178 Returns 179 ------- 180 list of dict (default) 181 Representing multiple tasks. 182 dict (if `uuid` is given) 183 Representing a single task. 184 int (`count_only == True`) 185 Count of matching Tasks. 186 187 Examples 188 -------- 189 >>> things.tasks() 190 [{'uuid': '6Hf2qWBjWhq7B1xszwdo34', 'type': 'to-do', 'title':... 191 >>> things.tasks('DfYoiXcNLQssk9DkSoJV3Y') 192 {'uuid': 'DfYoiXcNLQssk9DkSoJV3Y', 'type': 'to-do', 'title': ... 193 >>> things.tasks(area='hIo1FJlAYGKt1Yj38vzKc3', include_items=True) 194 [] 195 >>> things.tasks(status='completed', count_only=True) 196 12 197 >>> things.tasks(status='completed', last='1w', count_only=True) 198 0 199 >>> things.tasks(is_repeating_template=True) 200 [{'uuid': 'N1PJHsbjct4mb1bhcs7aHa', 'type': 'to-do', 'title': 'Repeating To-Do', ... 201 202 """ 203 database = pop_database(kwargs) 204 result = database.get_tasks( 205 uuid=uuid, status=kwargs.pop("status", "incomplete"), **kwargs 206 ) 207 208 if kwargs.get("count_only"): 209 return result 210 211 # overwrite `include_items` if fetching a single task. 212 if uuid: 213 include_items = True 214 215 for task in result: 216 # TK: How costly of an operation is it to do this for every task? 217 # IF costly, then can it be made significantly more efficient 218 # by optimizing SQL calls? 219 220 if task.get("tags"): 221 task["tags"] = database.get_tags(task=task["uuid"]) 222 223 if not include_items: 224 continue 225 226 # include items 227 if task["type"] == "to-do": 228 if task.get("checklist"): 229 task["checklist"] = database.get_checklist_items(task["uuid"]) 230 elif task["type"] == "project": 231 project = task 232 project["items"] = items = tasks( 233 project=project["uuid"], 234 context_trashed=None, 235 include_items=True, 236 database=database, 237 ) 238 # to-dos without headings appear before headings in app 239 items.sort(key=lambda item: item["type"], reverse=True) 240 elif task["type"] == "heading": 241 heading = task 242 heading["items"] = tasks( 243 type="to-do", 244 heading=heading["uuid"], 245 context_trashed=None, 246 include_items=True, 247 database=database, 248 ) 249 250 if uuid: 251 result = result[0] 252 253 return result
Read tasks into dicts.
Note: "task" is a technical term used in the database to refer to a to-do, project, or heading. For details, check the "type"-parameter.
Per default, only tasks marked as incomplete are included. If you want to include completed or canceled tasks in the result, check the "status"-parameter.
Parameters
- uuid (str or None, optional): Any valid task uuid. If None, then return all tasks matched.
- include_items (bool, default False): Include items contained within a task. These might include checklist items, headings, and to-dos.
- type ({'to-do', 'heading', 'project', None}, optional):
Only return a specific type of task:
'to-do': may have a checklist; may be in an area and have tags.'project': may have to-dos and headings; may be in an area and have tags.'heading': part of a project; groups tasks.None(default): return all types of tasks.
- status ({'incomplete', 'completed', 'canceled', None}, optional, default 'incomplete'):
Only include tasks matching that status. If
status == None, then include tasks with any status value. - start ({'Inbox', 'Anytime', 'Someday', None}, optional):
Only include tasks matching that start value. If the argument is
None(default), then include tasks with any start value. - area (str or bool or None, optional):
Any valid uuid of an area. Only include tasks matching that area.
Special cases:
area == False, only include tasks _without_ an area.area == True, only include tasks _with_ an area.area == None(default), then include all tasks.
- project (str or bool or None, optional):
Any valid uuid of a project. Only include tasks matching that project.
Special cases:
project == False, only include tasks _without_ a project.project == True, only include tasks _with_ a project.project == None(default), then include all tasks.
- heading (str or None, optional):
Any valid uuid of a heading. Only include tasks matching that heading.
Special cases:
heading == False, only include tasks _without_ a heading.heading == True, only include tasks _with_ a heading.heading == None(default), then include all tasks.
- tag (str or bool or None, optional):
Any valid title of a tag. Only include tasks matching that tag.
Special cases:
tag == False, only include tasks _without_ tags.tag == True, only include tasks _with_ tags.tag == None(default), then include all tasks.
- start_date (bool, str or None, optional):
start_date == False, only include tasks _without_ a start date.start_date == True, only include tasks with a start date.start_date == 'future', only include tasks with a future start date.start_date == 'past', only include tasks with a past start date. Note: this includes today's date.start_date == '[operator]YYYY-MM-DD'; match with optional operator, for example: '2023-05-22', '<=2023-05-22', or '>2023-05-22'.start_date == None(default), then include all tasks.
stop_date (same options as start_date, signifies the date of completion):
deadline (same options as start_date, signifies the deadline):
deadline_suppressed (bool or None, optional): "deadline suppressed" is a technical term used in the database. When tasks have an overdue deadline they show up in Today. Some of us "suppress" some tasks, that is, move them out of Today and into Inbox, Anytime, or Someday. For those moved tasks the deadline is said to be suppressed.
deadline_suppressed == True, only include tasks with deadlines and whose deadlines have been suppressed.deadline_suppressed == False, include any task _except_ those with suppressed deadlines.deadline_suppressed == None(default), include any task.
- trashed (bool or None, optional, default False):
trashed == False(default), only include non-trashed tasks.trashed == True, only include trashed tasks.trashed == None, include both kind of tasks.
context_trashed (bool or None, optional, default False): Some tasks may be within a context of a project or a heading. This manages how to handle such tasks. The other tasks are not affected by this setting.
context_trashed == False(default), for tasks within a context, only return tasks whose context has _not_ been trashed.context_trashed == True, for tasks within a context, only return tasks whose context has been trashed.context_trashed == None, include both kind of tasks.
- is_repeating_template (bool or None, optional, default False):
A repeating to-do is stored as a template, from which Things
creates each instance. A template has no start date; instead it
carries
next_instance_start_date, the date Things will create the next instance. Only templates have that field.is_repeating_template == False(default), exclude templates.is_repeating_template == True, only include templates.is_repeating_template == None, include both kind of tasks.
- next_instance_start_date (same options as start_date, signifies the date): Things will create the next instance of a repeating to-do (templates only)
last (str, optional): Limit returned tasks to tasks created within the last X days, weeks, or years. For example: '3d', '5w', or '1y'.
Takes as input an offset string of the format 'X[d/w/y]' where X is a non-negative integer that is followed by 'd', 'w', or 'y' which stand for 'days', 'weeks', and 'years', respectively.
search_query (str, optional): The string value is passed to the SQL LIKE operator. It can thus include placeholders such as '%' and '_'. Per default, it is wrapped in '% ... %'.
Currently titles and notes of to-dos, projects, headings, and areas are taken into account.
- index ({'index', 'todayIndex'}, default 'index'): Database field to order result by.
- count_only (bool, default False): Only output length of result. This is done by a SQL COUNT query.
- print_sql (bool, default False): Print every SQL query performed. Some may contain '?' and ':' characters, which correspond to SQLite parameter tokens. See https://www.sqlite.org/lang_expr.html#varparam
- filepath (str, optional):
Any valid path of a SQLite database file generated by the Things app.
If the environment variable
THINGSDBis set, then use that path. Otherwise, access the default database path. - database (things.database.Database, optional): Any valid database object previously instantiated.
Returns
- list of dict (default): Representing multiple tasks.
- dict (if
uuidis given): Representing a single task. - int (
count_only == True): Count of matching Tasks.
Examples
>>> things.tasks()
[{'uuid': '6Hf2qWBjWhq7B1xszwdo34', 'type': 'to-do', 'title':...
>>> things.tasks('DfYoiXcNLQssk9DkSoJV3Y')
{'uuid': 'DfYoiXcNLQssk9DkSoJV3Y', 'type': 'to-do', 'title': ...
>>> things.tasks(area='hIo1FJlAYGKt1Yj38vzKc3', include_items=True)
[]
>>> things.tasks(status='completed', count_only=True)
12
>>> things.tasks(status='completed', last='1w', count_only=True)
0
>>> things.tasks(is_repeating_template=True)
[{'uuid': 'N1PJHsbjct4mb1bhcs7aHa', 'type': 'to-do', 'title': 'Repeating To-Do', ...
256def areas(uuid=None, include_items=False, **kwargs): 257 """ 258 Read areas into dicts. 259 260 Parameters 261 ---------- 262 uuid : str or None, optional 263 Any valid uuid of an area. If None, then return all areas. 264 265 include_items : bool, default False 266 Include tasks and projects in each area. 267 268 tag : str or bool or None, optional 269 Any valid title of a tag. Only include areas matching that tag. 270 Special cases: 271 - `tag == False`, only include areas _without_ tags. 272 - `tag == True`, only include areas _with_ tags. 273 - `tag == None`, then ignore any tags present, that is, 274 include areas both with and without tags. 275 276 count_only : bool, default False 277 Only output length of result. This is done by a SQL COUNT query. 278 279 filepath : str, optional 280 Any valid path of a SQLite database file generated by the Things app. 281 If no path is provided, then access the default database path. 282 283 database : things.database.Database, optional 284 Any valid `things.database.Database` object previously instantiated. 285 286 Returns 287 ------- 288 list of dict (default) 289 Representing Things areas. 290 dict (if `uuid` is given) 291 Representing a single Things area. 292 int (`count_only == True`) 293 Count of matching areas. 294 295 Examples 296 -------- 297 >>> things.areas() 298 [{'uuid': 'Y3JC4XeyGWxzDocQL4aobo', 'type': 'area', 'title': 'Area 3'}, ... 299 >>> things.areas(tag='Home') 300 [] 301 >>> things.areas(uuid='DciSFacytdrNG1nRaMJPgY') 302 {'uuid': 'DciSFacytdrNG1nRaMJPgY', 'type': 'area', 'title': 'Area 1', ... 303 >>> things.areas(include_items=True, tag='Errand') 304 [{'uuid': 'DciSFacytdrNG1nRaMJPgY', 'type': 'area', 'title': 'Area 1', ... 305 """ 306 database = pop_database(kwargs) 307 result = database.get_areas(uuid=uuid, **kwargs) 308 309 if kwargs.get("count_only"): 310 return result 311 312 for area in result: 313 if area.get("tags"): 314 area["tags"] = database.get_tags(area=area["uuid"]) 315 if include_items: 316 area["items"] = tasks( 317 area=area["uuid"], include_items=True, database=database 318 ) 319 320 if uuid: 321 result = result[0] 322 323 return result
Read areas into dicts.
Parameters
- uuid (str or None, optional): Any valid uuid of an area. If None, then return all areas.
- include_items (bool, default False): Include tasks and projects in each area.
- tag (str or bool or None, optional):
Any valid title of a tag. Only include areas matching that tag.
Special cases:
tag == False, only include areas _without_ tags.tag == True, only include areas _with_ tags.tag == None, then ignore any tags present, that is, include areas both with and without tags.
- count_only (bool, default False): Only output length of result. This is done by a SQL COUNT query.
- filepath (str, optional): Any valid path of a SQLite database file generated by the Things app. If no path is provided, then access the default database path.
- database (things.database.Database, optional):
Any valid
things.database.Databaseobject previously instantiated.
Returns
- list of dict (default): Representing Things areas.
- dict (if
uuidis given): Representing a single Things area. - int (
count_only == True): Count of matching areas.
Examples
>>> things.areas()
[{'uuid': 'Y3JC4XeyGWxzDocQL4aobo', 'type': 'area', 'title': 'Area 3'}, ...
>>> things.areas(tag='Home')
[]
>>> things.areas(uuid='DciSFacytdrNG1nRaMJPgY')
{'uuid': 'DciSFacytdrNG1nRaMJPgY', 'type': 'area', 'title': 'Area 1', ...
>>> things.areas(include_items=True, tag='Errand')
[{'uuid': 'DciSFacytdrNG1nRaMJPgY', 'type': 'area', 'title': 'Area 1', ...
393def checklist_items(todo_uuid, **kwargs): 394 """ 395 Read checklist items of to-dos into dicts. 396 397 Note: checklists are contained in the return value of 398 `things.todos(todo_uuid)` and `things.tasks(todo_uuid)`. 399 400 Parameters 401 ---------- 402 todo_uuid : str, optional 403 A valid to-do uuid. 404 405 Returns 406 ------- 407 list of dict 408 Checklist items. 409 """ 410 database = pop_database(kwargs) 411 return database.get_checklist_items(todo_uuid=todo_uuid)
Read checklist items of to-dos into dicts.
Note: checklists are contained in the return value of
things.todos(todo_uuid) and things.tasks(todo_uuid).
Parameters
- todo_uuid (str, optional): A valid to-do uuid.
Returns
- list of dict: Checklist items.
419def search(query: str, **kwargs) -> list[dict]: 420 """ 421 Search tasks in the database. 422 423 Currently any part of a title and note of a to-do, project, 424 heading, or area is matched. 425 426 See the `search_query` parameter of `things.api.tasks` for details. 427 428 Examples 429 -------- 430 >>> things.search('Today%yellow') 431 [{'uuid': '6Hf2qWBjWhq7B1xszwdo34', 432 'type': 'to-do', 433 'title': 'Upcoming To-Do in Today (yellow)', 434 'status': 'incomplete', 435 'notes': '', 436 ... 437 """ 438 return tasks(search_query=query, **kwargs)
Search tasks in the database.
Currently any part of a title and note of a to-do, project, heading, or area is matched.
See the search_query parameter of things.api.tasks for details.
Examples
>>> things.search('Today%yellow')
[{'uuid': '6Hf2qWBjWhq7B1xszwdo34',
'type': 'to-do',
'title': 'Upcoming To-Do in Today (yellow)',
'status': 'incomplete',
'notes': '',
...
441def get(uuid, default=None, **kwargs): 442 """ 443 Find an object by uuid. If not found, return `default`. 444 445 Currently supports tasks, projects, headings, areas, and tags. 446 """ 447 try: 448 return tasks(uuid=uuid, **kwargs) 449 except ValueError: 450 pass 451 452 try: 453 return areas(uuid=uuid, **kwargs) 454 except ValueError: 455 pass 456 457 for tag in tags(**kwargs): 458 if tag["uuid"] == uuid: 459 return tag 460 461 return default
Find an object by uuid. If not found, return default.
Currently supports tasks, projects, headings, areas, and tags.
467def todos(uuid=None, **kwargs): 468 """ 469 Read to-dos into dicts. 470 471 See `things.api.tasks` for details on the optional parameters. 472 """ 473 return tasks(uuid=uuid, type="to-do", **kwargs)
Read to-dos into dicts.
See things.api.tasks for details on the optional parameters.
476def projects(uuid=None, **kwargs): 477 """ 478 Read projects into dicts. 479 480 See `things.api.tasks` for details on the optional parameters. 481 """ 482 return tasks(uuid=uuid, type="project", **kwargs)
Read projects into dicts.
See things.api.tasks for details on the optional parameters.
488def inbox(**kwargs): 489 """ 490 Read Inbox into dicts. 491 492 See `things.api.tasks` for details on the optional parameters. 493 """ 494 return tasks(start="Inbox", **kwargs)
Read Inbox into dicts.
See things.api.tasks for details on the optional parameters.
497def today(**kwargs): 498 """ 499 Read Today's tasks into dicts. 500 501 Note: The Things database reflects the state of the Things app when 502 it was last opened. For the Today tasks that means the database 503 might not be up to date anymore if you didn't open the app recently. 504 To get around this limitation, we here make a prediction of what 505 tasks would show up in Today if you were to open the app right now. 506 This prediction does not include repeating tasks at this time. 507 508 See `things.api.tasks` for details on the optional parameters. 509 """ 510 database = pop_database(kwargs) 511 kwargs["database"] = database 512 513 regular_today_tasks = tasks( 514 start_date=True, 515 start="Anytime", 516 index="todayIndex", 517 **kwargs, 518 ) 519 520 # Predictions of new to-dos indicated by a yellow dot in the app. 521 522 unconfirmed_scheduled_tasks = tasks( 523 start_date="past", 524 start="Someday", 525 index="todayIndex", 526 **kwargs, 527 ) 528 529 unconfirmed_overdue_tasks = tasks( 530 start_date=False, 531 deadline="past", 532 deadline_suppressed=False, 533 **kwargs, 534 ) 535 536 result = [ 537 *regular_today_tasks, 538 *unconfirmed_scheduled_tasks, 539 *unconfirmed_overdue_tasks, 540 ] 541 result.sort(key=lambda task: (task["today_index"], task["start_date"] or "")) 542 543 return result
Read Today's tasks into dicts.
Note: The Things database reflects the state of the Things app when it was last opened. For the Today tasks that means the database might not be up to date anymore if you didn't open the app recently. To get around this limitation, we here make a prediction of what tasks would show up in Today if you were to open the app right now. This prediction does not include repeating tasks at this time.
See things.api.tasks for details on the optional parameters.
546def upcoming(**kwargs): 547 """ 548 Read Upcoming tasks into dicts. 549 550 The output aims to be in the same order as Upcoming in Things.app. 551 Repeating to-dos use `next_instance_start_date` instead of `start_date`. 552 553 Note: unscheduled tasks with a deadline are not included here. 554 See the `things.api.deadlines` function instead. 555 556 For details on parameters, see `things.api.tasks`. 557 """ 558 database = pop_database(kwargs) 559 kwargs["database"] = database 560 561 scheduled = tasks(start_date="future", start="Someday", **kwargs) 562 repeating = tasks( 563 is_repeating_template=True, 564 next_instance_start_date="future", 565 start="Someday", 566 **kwargs, 567 ) 568 if kwargs.get("count_only"): 569 return scheduled + repeating 570 571 result = [*scheduled, *repeating] 572 result.sort( 573 key=lambda task: ( 574 task["start_date"] or task["next_instance_start_date"], 575 task["today_index"], 576 task["index"], 577 ) 578 ) 579 return result
Read Upcoming tasks into dicts.
The output aims to be in the same order as Upcoming in Things.app.
Repeating to-dos use next_instance_start_date instead of start_date.
Note: unscheduled tasks with a deadline are not included here.
See the things.api.deadlines function instead.
For details on parameters, see things.api.tasks.
582def anytime(**kwargs): 583 """ 584 Read Anytime tasks into dicts. 585 586 See `things.api.tasks` for details on the optional parameters. 587 """ 588 return tasks(start="Anytime", **kwargs)
Read Anytime tasks into dicts.
See things.api.tasks for details on the optional parameters.
591def someday(**kwargs): 592 """ 593 Read Someday tasks into dicts. 594 595 See `things.api.tasks` for details on the optional parameters. 596 """ 597 return tasks(start_date=False, start="Someday", **kwargs)
Read Someday tasks into dicts.
See things.api.tasks for details on the optional parameters.
600def logbook(**kwargs): 601 """ 602 Read Logbook tasks into dicts. 603 604 See `things.api.tasks` for details on the optional parameters. 605 """ 606 result = [*canceled(**kwargs), *completed(**kwargs)] 607 result.sort(key=lambda task: task["stop_date"], reverse=True) 608 return result
Read Logbook tasks into dicts.
See things.api.tasks for details on the optional parameters.
611def trash(**kwargs): 612 """ 613 Read Trash tasks into dicts. 614 615 See `things.api.tasks` for details on the optional parameters. 616 """ 617 return tasks( 618 trashed=True, 619 context_trashed=kwargs.pop("context_trashed", None), 620 status=kwargs.pop("status", None), 621 **kwargs, 622 )
Read Trash tasks into dicts.
See things.api.tasks for details on the optional parameters.
628def canceled(**kwargs): 629 """ 630 Read canceled tasks into dicts. 631 632 See `things.api.tasks` for details on the optional parameters. 633 """ 634 return tasks(status="canceled", **kwargs)
Read canceled tasks into dicts.
See things.api.tasks for details on the optional parameters.
637def completed(**kwargs): 638 """ 639 Read completed tasks into dicts. 640 641 See `things.api.tasks` for details on the optional parameters. 642 643 Examples 644 -------- 645 >>> things.completed(count_only=True) 646 12 647 >>> things.completed(type='project', count_only=True) 648 0 649 >>> things.completed(type='to-do', last='1w') 650 [] 651 """ 652 return tasks(status="completed", **kwargs)
Read completed tasks into dicts.
See things.api.tasks for details on the optional parameters.
Examples
>>> things.completed(count_only=True)
12
>>> things.completed(type='project', count_only=True)
0
>>> things.completed(type='to-do', last='1w')
[]
655def deadlines(**kwargs): 656 """ 657 Read tasks with deadlines into dicts. 658 659 See `things.api.tasks` for details on the optional parameters. 660 """ 661 result = tasks(deadline=True, **kwargs) 662 result.sort(key=lambda task: task["deadline"]) 663 return result
Read tasks with deadlines into dicts.
See things.api.tasks for details on the optional parameters.
666def last(offset, **kwargs): 667 """ 668 Read tasks created within last X days, weeks, or years into dicts. 669 670 Per default, only incomplete tasks are included, but do see 671 `things.api.tasks` for details on the optional parameters. 672 673 Parameters 674 ---------- 675 offset : str 676 A valid date offset such as '3d', '5w', or '1y'. 677 For details, see the `last` parameter of `things.api.tasks`. 678 679 Returns 680 ------- 681 list of dict 682 Tasks within offset ordered by creation date. Newest first. 683 684 Examples 685 -------- 686 >>> things.last('3d') 687 [] 688 >>> things.last('1w', status='completed') 689 [] 690 >>> things.last('1y', tag='Important', status='completed', count_only=True) 691 0 692 693 """ 694 if offset is None: 695 raise ValueError(f"Invalid offset type: {offset!r}") 696 697 result = tasks(last=offset, **kwargs) 698 if result: 699 result.sort(key=lambda task: task["created"], reverse=True) 700 701 return result
Read tasks created within last X days, weeks, or years into dicts.
Per default, only incomplete tasks are included, but do see
things.api.tasks for details on the optional parameters.
Parameters
- offset (str):
A valid date offset such as '3d', '5w', or '1y'.
For details, see the
lastparameter ofthings.api.tasks.
Returns
- list of dict: Tasks within offset ordered by creation date. Newest first.
Examples
>>> things.last('3d')
[]
>>> things.last('1w', status='completed')
[]
>>> things.last('1y', tag='Important', status='completed', count_only=True)
0
707def token(**kwargs) -> str | None: 708 """ 709 Read the Things URL scheme authentication token. 710 711 You can make good use of this token to modify existing Things data 712 using the Things URL Scheme. For details, see 713 [here](https://culturedcode.com/things/help/url-scheme/). 714 """ 715 database = pop_database(kwargs) 716 return database.get_url_scheme_auth_token()
Read the Things URL scheme authentication token.
You can make good use of this token to modify existing Things data using the Things URL Scheme. For details, see here.
719def url(uuid=None, command="show", **query_parameters) -> str: 720 """ 721 Return a things:///<command>?<query> url. 722 723 For details about available commands and their parameters 724 consult the Things URL Scheme documentation 725 [here](https://culturedcode.com/things/help/url-scheme/). 726 727 Parameters 728 ---------- 729 uuid : str or None, optional 730 A valid uuid of any Things object. 731 If `None`, then 'id' is not added as a parameter unless 732 specified in `query_parameters`. 733 734 command : str, default 'show' 735 A valid command name. 736 737 **query_parameters: 738 Additional URL query parameters. 739 740 Examples 741 -------- 742 >>> things.url('6Hf2qWBjWhq7B1xszwdo34') 743 'things:///show?id=6Hf2qWBjWhq7B1xszwdo34' 744 >>> things.url(command='update', uuid='6Hf2qWBjWhq7B1xszwdo34', title='new title') 745 'things:///update?id=6Hf2qWBjWhq7B1xszwdo34&title=new%20title&auth-token=vKkylosuSuGwxrz7qcklOw' 746 >>> things.url(command='add', title='new task', when='in 3 days', deadline='in 6 days') 747 'things:///add?title=new%20task&when=in%203%20days&deadline=in%206%20days' 748 >>> query_params = {'title': 'test title', 'list-id': 'ba5d1237-1dfa-4ab8-826b-7c27b517f29d'} 749 >>> things.url(command="add", **query_params) 750 'things:///add?title=test%20title&list-id=ba5d1237-1dfa-4ab8-826b-7c27b517f29d' 751 """ 752 if uuid is not None: 753 query_parameters = {"id": uuid, **query_parameters} 754 755 # authenticate if needed 756 if command in ("update", "update-project"): 757 auth_token = query_parameters["auth-token"] = token() 758 if not auth_token: 759 raise ValueError("Things URL scheme authentication token could not be read") 760 761 query_string = urllib.parse.urlencode( 762 query_parameters, quote_via=urllib.parse.quote 763 ) 764 765 return f"things:///{command}?{query_string}"
Return a things:///
For details about available commands and their parameters consult the Things URL Scheme documentation here.
Parameters
- uuid (str or None, optional):
A valid uuid of any Things object.
If
None, then 'id' is not added as a parameter unless specified inquery_parameters. - command (str, default 'show'): A valid command name.
- **query_parameters:: Additional URL query parameters.
Examples
>>> things.url('6Hf2qWBjWhq7B1xszwdo34')
'things:///show?id=6Hf2qWBjWhq7B1xszwdo34'
>>> things.url(command='update', uuid='6Hf2qWBjWhq7B1xszwdo34', title='new title')
'things:///update?id=6Hf2qWBjWhq7B1xszwdo34&title=new%20title&auth-token=vKkylosuSuGwxrz7qcklOw'
>>> things.url(command='add', title='new task', when='in 3 days', deadline='in 6 days')
'things:///add?title=new%20task&when=in%203%20days&deadline=in%206%20days'
>>> query_params = {'title': 'test title', 'list-id': 'ba5d1237-1dfa-4ab8-826b-7c27b517f29d'}
>>> things.url(command="add", **query_params)
'things:///add?title=test%20title&list-id=ba5d1237-1dfa-4ab8-826b-7c27b517f29d'
719def url(uuid=None, command="show", **query_parameters) -> str: 720 """ 721 Return a things:///<command>?<query> url. 722 723 For details about available commands and their parameters 724 consult the Things URL Scheme documentation 725 [here](https://culturedcode.com/things/help/url-scheme/). 726 727 Parameters 728 ---------- 729 uuid : str or None, optional 730 A valid uuid of any Things object. 731 If `None`, then 'id' is not added as a parameter unless 732 specified in `query_parameters`. 733 734 command : str, default 'show' 735 A valid command name. 736 737 **query_parameters: 738 Additional URL query parameters. 739 740 Examples 741 -------- 742 >>> things.url('6Hf2qWBjWhq7B1xszwdo34') 743 'things:///show?id=6Hf2qWBjWhq7B1xszwdo34' 744 >>> things.url(command='update', uuid='6Hf2qWBjWhq7B1xszwdo34', title='new title') 745 'things:///update?id=6Hf2qWBjWhq7B1xszwdo34&title=new%20title&auth-token=vKkylosuSuGwxrz7qcklOw' 746 >>> things.url(command='add', title='new task', when='in 3 days', deadline='in 6 days') 747 'things:///add?title=new%20task&when=in%203%20days&deadline=in%206%20days' 748 >>> query_params = {'title': 'test title', 'list-id': 'ba5d1237-1dfa-4ab8-826b-7c27b517f29d'} 749 >>> things.url(command="add", **query_params) 750 'things:///add?title=test%20title&list-id=ba5d1237-1dfa-4ab8-826b-7c27b517f29d' 751 """ 752 if uuid is not None: 753 query_parameters = {"id": uuid, **query_parameters} 754 755 # authenticate if needed 756 if command in ("update", "update-project"): 757 auth_token = query_parameters["auth-token"] = token() 758 if not auth_token: 759 raise ValueError("Things URL scheme authentication token could not be read") 760 761 query_string = urllib.parse.urlencode( 762 query_parameters, quote_via=urllib.parse.quote 763 ) 764 765 return f"things:///{command}?{query_string}"
Return a things:///
For details about available commands and their parameters consult the Things URL Scheme documentation here.
Parameters
- uuid (str or None, optional):
A valid uuid of any Things object.
If
None, then 'id' is not added as a parameter unless specified inquery_parameters. - command (str, default 'show'): A valid command name.
- **query_parameters:: Additional URL query parameters.
Examples
>>> things.url('6Hf2qWBjWhq7B1xszwdo34')
'things:///show?id=6Hf2qWBjWhq7B1xszwdo34'
>>> things.url(command='update', uuid='6Hf2qWBjWhq7B1xszwdo34', title='new title')
'things:///update?id=6Hf2qWBjWhq7B1xszwdo34&title=new%20title&auth-token=vKkylosuSuGwxrz7qcklOw'
>>> things.url(command='add', title='new task', when='in 3 days', deadline='in 6 days')
'things:///add?title=new%20task&when=in%203%20days&deadline=in%206%20days'
>>> query_params = {'title': 'test title', 'list-id': 'ba5d1237-1dfa-4ab8-826b-7c27b517f29d'}
>>> things.url(command="add", **query_params)
'things:///add?title=test%20title&list-id=ba5d1237-1dfa-4ab8-826b-7c27b517f29d'
772def show(uuid): 773 """ 774 Show a certain uuid in the Things app. 775 776 Parameters 777 ---------- 778 uuid : str 779 A valid uuid of any Things object. 780 781 Examples 782 -------- 783 >>> tag = things.tags('Home') 784 >>> things.show(tag['uuid']) # doctest: +SKIP 785 """ 786 uri = url(uuid=uuid) 787 os.system(f"open {quote(uri)}")
Show a certain uuid in the Things app.
Parameters
- uuid (str): A valid uuid of any Things object.
Examples
>>> tag = things.tags('Home')
>>> things.show(tag['uuid']) # doctest: +SKIP
790def complete(uuid): 791 """ 792 Set the status of a certain uuid to complete. 793 794 Parameters 795 ---------- 796 uuid : str 797 A valid uuid of a project or to-do. 798 799 Examples 800 -------- 801 >>> task = things.todos()[0] # doctest: +SKIP 802 >>> things.complete(task['uuid']) # doctest: +SKIP 803 """ 804 uri = url(uuid=uuid, command="update", completed=True) 805 os.system(f"open {quote(uri)}")
Set the status of a certain uuid to complete.
Parameters
- uuid (str): A valid uuid of a project or to-do.
Examples
>>> task = things.todos()[0] # doctest: +SKIP
>>> things.complete(task['uuid']) # doctest: +SKIP
811def pop_database(kwargs): 812 """Instantiate non-default database from `kwargs` if provided.""" 813 filepath = kwargs.pop("filepath", None) 814 database = kwargs.pop("database", None) 815 print_sql = kwargs.pop("print_sql", False) 816 817 if not database: 818 database = Database(filepath=filepath, print_sql=print_sql) 819 return database
Instantiate non-default database from kwargs if provided.