Skip to content

core

Core functionality for synchronisation.

delete_done_pages(notion, database_id, gcal_event_id_notion_name, on_gcal_notion_name, delete_notion_name, delete_option, calendar_dictionary, calendar_notion_name, service)

Sync/delete Done pages.

  • If marked Done in Notion, then it will delete the GCal event (and the Notion event once Python API updates)
Source code in ncal/core.py
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
def delete_done_pages(
    notion: nc.Client,
    database_id: str,
    gcal_event_id_notion_name,
    on_gcal_notion_name,
    delete_notion_name,
    delete_option: bool,
    calendar_dictionary,
    calendar_notion_name,
    service,
):
    """Sync/delete Done pages.

    - If marked *Done* in Notion, then it will delete the GCal event
    (and the Notion event once Python API updates)
    """
    result_list = paginated_database_query(
        notion,
        database_id,
        **{
            "filter": {
                "and": [
                    {
                        "property": gcal_event_id_notion_name,
                        "text": {"is_not_empty": True},
                    },
                    {"property": on_gcal_notion_name, "checkbox": {"equals": True}},
                    {"property": delete_notion_name, "checkbox": {"equals": True}},
                ]
            },
        },
    )

    # delete gcal event (and Notion task once the Python API is updated)
    if delete_option and len(result_list) > 0:
        for i, el in enumerate(result_list):
            calendar_id = calendar_dictionary[
                el["properties"][calendar_notion_name]["select"]["name"]
            ]
            event_id = el["properties"][gcal_event_id_notion_name]["rich_text"][0][
                "text"
            ]["content"]

            try:
                service.events().delete(
                    calendarId=calendar_id, eventId=event_id
                ).execute()
                logging.info(f"deleted: {calendar_id} {event_id}")
            except HttpError:
                continue
            time.sleep(0.1)

existing_events_gcal_to_notion(database_id, default_calendar_name, calendar_dictionary, date_notion_name, on_gcal_notion_name, need_gcal_update_notion_name, gcal_event_id_notion_name, last_updated_time_notion_name, calendar_notion_name, current_calendar_id_notion_name, delete_notion_name, service, notion, today_date, settings)

Sync GCal event updates for events already in Notion back to Notion.

Query notion tasks already in Gcal, don't have to be updated, and are today or in the future.

Source code in ncal/core.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
def existing_events_gcal_to_notion(
    database_id,
    default_calendar_name,
    calendar_dictionary,
    date_notion_name,
    on_gcal_notion_name,
    need_gcal_update_notion_name,
    gcal_event_id_notion_name,
    last_updated_time_notion_name,
    calendar_notion_name,
    current_calendar_id_notion_name,
    delete_notion_name,
    service,
    notion,
    today_date,
    settings: config.Settings,
):
    """Sync GCal event updates for events already in Notion back to Notion.

    Query notion tasks already in Gcal, don't have to be updated, and are today or
    in the future.
    """
    query = {
        "filter": {
            "and": [
                {
                    "property": need_gcal_update_notion_name,
                    "formula": {"checkbox": {"equals": False}},
                },
                {"property": on_gcal_notion_name, "checkbox": {"equals": True}},
                # {
                #     "or": [
                #         {
                #             "property": date_notion_name,
                #             "date": {"equals": todayDate},
                #         },
                #         {"property": date_notion_name, "date": {"next_week": {}}},
                #     ]
                # },
                {"property": delete_notion_name, "checkbox": {"equals": False}},
            ]
        },
    }

    result_list = paginated_database_query(notion, database_id, **query)

    # Comparison section:
    # We need to see what times between GCal and Notion are not the same, so we are
    # going to convert all of the notion date/times into datetime values and then
    # compare that against the datetime value of the GCal event.
    # If they are not the same, then we change the Notion event as appropriate.
    notion_ids_list = []
    notion_start_datetimes = []
    notion_end_datetimes = []
    notion_gcal_ids = []  # we will be comparing this against the gcal_datetimes
    gcal_start_datetimes = []
    gcal_end_datetimes = []

    notion_gcal_cal_ids = (
        []
    )  # going to fill this in from the select option, not the text option.
    notion_gcal_cal_names = []
    gcal_cal_ids = []

    for result in result_list:
        notion_ids_list.append(result["id"])
        notion_start_datetimes.append(
            result["properties"][date_notion_name]["date"]["start"]
        )
        notion_end_datetimes.append(
            result["properties"][date_notion_name]["date"]["end"]
        )
        notion_gcal_ids.append(
            result["properties"][gcal_event_id_notion_name]["rich_text"][0]["text"][
                "content"
            ]
        )
        try:
            notion_gcal_cal_ids.append(
                calendar_dictionary[
                    result["properties"][calendar_notion_name]["select"]["name"]
                ]
            )
            notion_gcal_cal_names.append(
                result["properties"][calendar_notion_name]["select"]["name"]
            )
        # keyerror occurs when there's nothing put into the calendar in the first place
        except KeyError:
            notion_gcal_cal_ids.append(calendar_dictionary[default_calendar_name])
            notion_gcal_cal_names.append(
                result["properties"][calendar_notion_name]["select"]["name"]
            )

    # the reason we take off the last 6 characters is so we can focus in on just the
    # date and time instead of any extra info
    for i in range(len(notion_start_datetimes)):
        try:
            notion_start_datetimes[i] = datetime.datetime.strptime(
                notion_start_datetimes[i], "%Y-%m-%d"
            )
        except ValueError:
            try:
                notion_start_datetimes[i] = datetime.datetime.strptime(
                    notion_start_datetimes[i][:-6], "%Y-%m-%dT%H:%M:%S.000"
                )
            except ValueError:
                notion_start_datetimes[i] = datetime.datetime.strptime(
                    notion_start_datetimes[i][:-6], "%Y-%m-%dT%H:%M:%S.%f"
                )

    for i in range(len(notion_end_datetimes)):
        if notion_end_datetimes[i] is not None:
            try:
                notion_end_datetimes[i] = datetime.datetime.strptime(
                    notion_end_datetimes[i], "%Y-%m-%d"
                )
            except ValueError:
                try:
                    notion_end_datetimes[i] = datetime.datetime.strptime(
                        notion_end_datetimes[i][:-6], "%Y-%m-%dT%H:%M:%S.000"
                    )
                except ValueError:
                    notion_end_datetimes[i] = datetime.datetime.strptime(
                        notion_end_datetimes[i][:-6], "%Y-%m-%dT%H:%M:%S.%f"
                    )
        else:
            # the reason we're doing this weird ass thing is because when we put the
            # end time into the update or make GCal event, it'll be representative of
            # the date
            notion_end_datetimes[i] = notion_start_datetimes[i]

    # We use the gcalId from the Notion dashboard to get retrieve the start Time from
    # the gcal event
    value = ""
    for gcal_id in notion_gcal_ids:
        # just check all of the calendars of interest for info about the event
        for calendar_id in calendar_dictionary.keys():
            logging.info("Trying " + calendar_id + " for " + gcal_id)
            try:
                x = (
                    service.events()
                    .get(calendarId=calendar_dictionary[calendar_id], eventId=gcal_id)
                    .execute()
                )
            except HttpError:
                logging.info("Event not found")
                x = {"status": "unconfirmed"}
            if x["status"] == "confirmed":
                gcal_cal_ids.append(calendar_id)
                value = x
            else:
                continue

        logging.info(value)
        logging.info("\n")
        try:
            gcal_start_datetimes.append(
                dateutil.parser.isoparse(value["start"]["dateTime"])  # type: ignore
            )
        except KeyError:
            date = datetime.datetime.strptime(value["start"]["date"], "%Y-%m-%d")  # type: ignore # noqa
            gcal_start_datetimes.append(date)
        try:
            gcal_end_datetimes.append(
                dateutil.parser.isoparse(value["end"]["dateTime"])  # type: ignore
            )
        except KeyError:
            date = datetime.datetime.strptime(value["end"]["date"], "%Y-%m-%d")  # type: ignore # noqa
            x = datetime.datetime(
                date.year, date.month, date.day, 0, 0, 0
            ) - datetime.timedelta(days=1)
            gcal_end_datetimes.append(x)

    # Now we iterate and compare the time on the Notion Dashboard and the start time of
    # the GCal event
    # If the datetimes don't match up,  then the Notion  Dashboard must be updated

    new_notion_start_datetimes: list[None | datetime.datetime] = []
    new_notion_end_datetimes: list[None | datetime.datetime] = []

    for i in range(len(notion_start_datetimes)):
        if notion_start_datetimes[i] != gcal_start_datetimes[i]:
            new_notion_start_datetimes.append(gcal_start_datetimes[i])
        else:
            new_notion_start_datetimes.append(None)

        if notion_end_datetimes[i] != gcal_end_datetimes[i]:
            # this means that there is no end time in notion
            new_notion_end_datetimes.append(gcal_end_datetimes[i])
        else:
            new_notion_end_datetimes.append(None)

    logging.info("test")
    logging.info(new_notion_start_datetimes)
    logging.info(new_notion_end_datetimes)
    logging.info("\n")
    for i in range(len(notion_gcal_ids)):
        logging.info(
            notion_start_datetimes[i], gcal_start_datetimes[i], notion_gcal_ids[i]
        )

    for i, (new_start, new_end) in enumerate(
        zip(new_notion_start_datetimes, new_notion_end_datetimes)
    ):
        if (
            new_start is not None and new_end is not None
        ):  # both start and end time need to be updated
            start: datetime.datetime = new_start
            end: datetime.datetime = new_end

            # you're given 12 am dateTimes so you want to enter them as dates (not
            # datetimes) into Notion
            if start.hour == 0 and start.minute == 0 and start == end:
                # update the notion dashboard with the new datetime and update the last
                # updated time
                notion.pages.update(
                    **{
                        "page_id": notion_ids_list[i],
                        "properties": {
                            date_notion_name: {
                                "date": {
                                    "start": start.strftime("%Y-%m-%d"),
                                    "end": None,
                                }
                            },
                            last_updated_time_notion_name: {
                                "date": {
                                    "start": arrow.utcnow().isoformat(),
                                    "end": None,
                                }
                            },
                        },
                    },
                )
            elif (
                start.hour == 0
                and start.minute == 0
                and end.hour == 0
                and end.minute == 0
            ):
                # you're given 12 am dateTimes so you want to enter them as dates (not
                # datetimes) into Notion
                # update the notion dashboard with the new datetime and update the last
                # updated time
                notion.pages.update(
                    **{
                        "page_id": notion_ids_list[i],
                        "properties": {
                            date_notion_name: {
                                "date": {
                                    "start": start.strftime("%Y-%m-%d"),
                                    "end": end.strftime("%Y-%m-%d"),
                                }
                            },
                            last_updated_time_notion_name: {
                                "date": {
                                    "start": arrow.utcnow().isoformat(),
                                    "end": None,
                                }
                            },
                        },
                    },
                )
            else:  # update Notion using datetime format
                notion.pages.update(
                    # update the notion dashboard with the new datetime and update the
                    # last updated time
                    **{
                        "page_id": notion_ids_list[i],
                        "properties": {
                            date_notion_name: {
                                "date": {
                                    "start": start.isoformat(),
                                    "end": end.isoformat(),
                                }
                            },
                            last_updated_time_notion_name: {
                                "date": {
                                    "start": arrow.utcnow().isoformat(),
                                    "end": None,
                                }
                            },
                        },
                    },
                )
        elif new_start is not None:  # only start time need to be updated
            start = new_start
            end = notion_end_datetimes[i]

            if start.hour == 0 and start.minute == 0 and start == end:
                # you're given 12 am dateTimes so you want to enter them as dates (not
                # datetimes) into Notion
                # update the notion dashboard with the new datetime and update the last
                # updated time
                notion.pages.update(
                    **{
                        "page_id": notion_ids_list[i],
                        "properties": {
                            date_notion_name: {
                                "date": {
                                    "start": start.strftime("%Y-%m-%d"),
                                    "end": None,
                                }
                            },
                            last_updated_time_notion_name: {
                                "date": {
                                    "start": arrow.utcnow().isoformat(),
                                    "end": None,
                                }
                            },
                        },
                    },
                )
            elif (
                start.hour == 0
                and start.minute == 0
                and end.hour == 0
                and end.minute == 0
            ):
                # you're given 12 am dateTimes so you want to enter them as dates
                # (not datetimes) into Notion
                notion.pages.update(
                    # update the notion dashboard with the new datetime and update the
                    # last updated time
                    **{
                        "page_id": notion_ids_list[i],
                        "properties": {
                            date_notion_name: {
                                "date": {
                                    "start": start.strftime("%Y-%m-%d"),
                                    "end": end.strftime("%Y-%m-%d"),
                                }
                            },
                            last_updated_time_notion_name: {
                                "date": {
                                    "start": arrow.utcnow().isoformat(),
                                    "end": None,
                                }
                            },
                        },
                    },
                )
            else:
                # update Notion using datetime format
                notion.pages.update(
                    # update the notion dashboard with the new datetime and update the
                    # last updated time
                    **{
                        "page_id": notion_ids_list[i],
                        "properties": {
                            date_notion_name: {
                                "date": {
                                    "start": start.isoformat(),
                                    "end": end.isoformat(),
                                }
                            },
                            last_updated_time_notion_name: {
                                "date": {
                                    "start": arrow.utcnow().isoformat(),
                                    "end": None,
                                }
                            },
                        },
                    },
                )
        elif new_end is not None:  # only end time needs to be updated
            start = notion_start_datetimes[i]
            end = new_end

            if start.hour == 0 and start.minute == 0 and start == end:
                # you're given 12 am dateTimes so you want to enter them as dates (not
                # datetimes) into Notion
                notion.pages.update(
                    # update the notion dashboard with the new datetime and update the
                    # last updated time
                    **{
                        "page_id": notion_ids_list[i],
                        "properties": {
                            date_notion_name: {
                                "date": {
                                    "start": start.strftime("%Y-%m-%d"),
                                    "end": None,
                                }
                            },
                            last_updated_time_notion_name: {
                                "date": {
                                    "start": arrow.utcnow().isoformat(),
                                    "end": None,
                                }
                            },
                        },
                    },
                )
            elif (
                start.hour == 0
                and start.minute == 0
                and end.hour == 0
                and end.minute == 0
            ):
                # update the notion dashboard with the new datetime and update the last
                # updated time
                notion.pages.update(
                    **{
                        "page_id": notion_ids_list[i],
                        "properties": {
                            date_notion_name: {
                                "date": {
                                    "start": start.strftime("%Y-%m-%d"),
                                    "end": end.strftime("%Y-%m-%d"),
                                }
                            },
                            last_updated_time_notion_name: {
                                "date": {
                                    "start": arrow.utcnow().isoformat(),
                                    "end": None,
                                }
                            },
                        },
                    },
                )
            else:
                # update Notion using datetime format
                notion.pages.update(
                    # update the notion dashboard with the new datetime and update the
                    # last updated time
                    **{
                        "page_id": notion_ids_list[i],
                        "properties": {
                            date_notion_name: {
                                "date": {
                                    "start": start.isoformat(),
                                    "end": end.isoformat(),
                                }
                            },
                            last_updated_time_notion_name: {
                                "date": {
                                    "start": arrow.utcnow().isoformat(),
                                    "end": None,
                                }
                            },
                        },
                    },
                )
        else:  # nothing needs to be updated here
            continue

    logging.info(notion_ids_list)
    logging.info("\n")
    logging.info(gcal_cal_ids)

    cal_names = list(calendar_dictionary.keys())
    cal_ids = list(calendar_dictionary.values())

    for i, gcal_id in enumerate(gcal_cal_ids):
        # instead of checking, just update the notion datebase with whatever calendar
        # the event is on
        logging.info("GcalId: " + gcal_id)
        notion.pages.update(
            # This puts the the GCal Id into the Notion Dashboard
            **{
                "page_id": notion_ids_list[i],
                "properties": {
                    current_calendar_id_notion_name: {  # this is the text
                        "rich_text": [
                            {"text": {"content": cal_ids[cal_names.index(gcal_id)]}}
                        ]
                    },
                    calendar_notion_name: {  # this is the select
                        "select": {"name": gcal_id},
                    },
                    last_updated_time_notion_name: {
                        "date": {
                            "start": arrow.utcnow().isoformat(),
                            "end": None,
                        }
                    },
                },
            },
        )

existing_events_notion_to_gcal(database_id, url_root, default_calendar_id, default_calendar_name, calendar_dictionary, task_notion_name, date_notion_name, initiative_notion_name, extra_info_notion_name, on_gcal_notion_name, need_gcal_update_notion_name, gcal_event_id_notion_name, last_updated_time_notion_name, calendar_notion_name, current_calendar_id_notion_name, delete_notion_name, notion, today_date, service, settings)

Update GCal Events that Need To Be Updated.

(Changed on Notion but need to be changed on GCal)

Source code in ncal/core.py
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
def existing_events_notion_to_gcal(
    database_id,
    url_root,
    default_calendar_id,
    default_calendar_name,
    calendar_dictionary,
    task_notion_name,
    date_notion_name,
    initiative_notion_name,
    extra_info_notion_name,
    on_gcal_notion_name,
    need_gcal_update_notion_name,
    gcal_event_id_notion_name,
    last_updated_time_notion_name,
    calendar_notion_name,
    current_calendar_id_notion_name,
    delete_notion_name,
    notion,
    today_date,
    service,
    settings: config.Settings,
):
    """
    Update GCal Events that Need To Be Updated.

    (Changed on Notion but need to be changed on GCal)
    """
    # In case people deleted the Calendar Variable, this queries items where
    # the Calendar select thing is empty
    query = {
        "filter": {
            "and": [
                {"property": calendar_notion_name, "select": {"is_empty": True}},
                {"property": delete_notion_name, "checkbox": {"equals": False}},
            ]
        },
    }
    result_list = paginated_database_query(
        notion_client=notion, database_id=database_id, **query
    )

    if len(result_list) > 0:
        for i, el in enumerate(result_list):
            page_id = el["id"]

            # This checks off that the event has been put on Google Calendar
            notion.pages.update(
                **{
                    "page_id": page_id,
                    "properties": {
                        calendar_notion_name: {
                            "select": {"name": default_calendar_name},
                        },
                        last_updated_time_notion_name: {
                            "date": {
                                "start": arrow.utcnow().isoformat(),
                                "end": None,
                            }
                        },
                    },
                },
            )

    # Filter events that have been updated since the GCal event has been made

    # this query will return a dictionary that we will parse for information that
    # we want
    # look for events that are today or in the next week
    query = {
        "filter": {
            "and": [
                {
                    "property": need_gcal_update_notion_name,
                    "checkbox": {"equals": True},
                },
                {"property": on_gcal_notion_name, "checkbox": {"equals": True}},
                {"property": delete_notion_name, "checkbox": {"equals": False}},
            ]
        },
    }
    result_list = paginated_database_query(notion, database_id, **query)

    updating_notion_page_ids = []
    updating_cal_event_ids = []

    for result in result_list:
        logging.info(result)
        logging.info("\n")
        page_id = result["id"]
        updating_notion_page_ids.append(page_id)
        logging.info("\n")
        logging.info(result)
        logging.info("\n")
        try:
            cal_id = result["properties"][gcal_event_id_notion_name]["rich_text"][0][
                "text"
            ]["content"]
        except IndexError:
            cal_id = default_calendar_id
        logging.info(cal_id)
        updating_cal_event_ids.append(cal_id)

    task_names = []
    start_dates = []
    end_times = []
    initiatives = []
    extra_info = []
    url_list = []
    calendar_list = []
    current_cal_list = []

    if len(result_list) > 0:
        for i, el in enumerate(result_list):
            logging.info("\n")
            logging.info(el)
            logging.info("\n")

            task_names.append(
                notion_utils.collapse_rich_text_property(
                    el["properties"][task_notion_name]["title"]
                )
            )
            start_dates.append(el["properties"][date_notion_name]["date"]["start"])

            if el["properties"][date_notion_name]["date"]["end"] is not None:
                end_times.append(el["properties"][date_notion_name]["date"]["end"])
            else:
                end_times.append(el["properties"][date_notion_name]["date"]["start"])

            try:
                initiatives.append(
                    get_property_text(
                        notion=notion,
                        notion_page=el,
                        property_name=initiative_notion_name,
                        property_type=settings.initiative_notion_type,
                    )
                )
            except ValueError:
                initiatives.append("")

            try:
                extra_info.append(
                    el["properties"][extra_info_notion_name]["rich_text"][0]["text"][
                        "content"
                    ]
                )
            except IndexError:
                extra_info.append("")
            url_list.append(make_task_url(el["id"], url_root))

            logging.info(el)
            # CalendarList.append(calendar_dictionary[el['properties'][Calendar_Notion_Name]['select']['name']])
            try:
                calendar_list.append(
                    calendar_dictionary[
                        el["properties"][calendar_notion_name]["select"]["name"]
                    ]
                )
            # keyerror occurs when there's nothing put into the calendar in the first
            # place
            except KeyError:
                calendar_list.append(calendar_dictionary[default_calendar_name])

            current_cal_list.append(
                el["properties"][current_calendar_id_notion_name]["rich_text"][0][
                    "text"
                ]["content"]
            )

            page_id = el["id"]

            # depending on the format of the dates, we'll update the gcal event as
            # necessary
            try:
                update_calendar_event(
                    task_names[i],
                    make_event_description(initiatives[i], extra_info[i]),
                    datetime.datetime.strptime(start_dates[i], "%Y-%m-%d"),
                    url_list[i],
                    updating_cal_event_ids[i],
                    datetime.datetime.strptime(end_times[i], "%Y-%m-%d"),
                    current_cal_list[i],
                    calendar_list[i],
                    service,
                    settings,
                )
            except ValueError:
                try:
                    update_calendar_event(
                        task_names[i],
                        make_event_description(initiatives[i], extra_info[i]),
                        dateutil.parser.isoparse(start_dates[i]),
                        url_list[i],
                        updating_cal_event_ids[i],
                        dateutil.parser.isoparse(end_times[i]),
                        current_cal_list[i],
                        calendar_list[i],
                        service,
                        settings,
                    )
                except ValueError:
                    update_calendar_event(
                        task_names[i],
                        make_event_description(initiatives[i], extra_info[i]),
                        dateutil.parser.isoparse(start_dates[i]),
                        url_list[i],
                        updating_cal_event_ids[i],
                        dateutil.parser.isoparse(end_times[i]),
                        current_cal_list[i],
                        calendar_list[i],
                        service,
                        settings,
                    )

            # This updates the last time that the page in Notion was updated by the code
            notion.pages.update(
                **{
                    "page_id": page_id,
                    "properties": {
                        last_updated_time_notion_name: {
                            "date": {
                                "start": arrow.utcnow().isoformat(),
                                "end": None,
                            }
                        },
                        current_calendar_id_notion_name: {
                            "rich_text": [{"text": {"content": calendar_list[i]}}]
                        },
                    },
                },
            )

    else:
        logging.info("Nothing new updated to GCal")

make_cal_event(event_name, event_description, event_start_time, source_url, event_end_time, cal_id, service, config)

Make a calendar event.

Source code in ncal/core.py
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
def make_cal_event(
    event_name,
    event_description,
    event_start_time,
    source_url,
    event_end_time,
    cal_id,
    service,
    config: config.Settings,
):
    """Make a calendar event."""
    if (
        event_start_time.hour == 0
        and event_start_time.minute == 0
        and event_end_time == event_start_time
    ):  # only startTime is given from the Notion Dashboard
        if config.all_day_event_option == 1:
            event_start_time = datetime.datetime.combine(
                event_start_time, datetime.datetime.min.time()
            ) + datetime.timedelta(
                hours=config.default_event_start
            )  # make the events pop up at 8 am instead of 12 am
            event_end_time = event_start_time + datetime.timedelta(
                minutes=config.default_event_length
            )
            event = {
                "summary": event_name,
                "description": event_description,
                "start": {
                    "dateTime": event_start_time.strftime(DATE_AND_TIME_FORMAT_STRING),
                    "timeZone": config.timezone,
                },
                "end": {
                    "dateTime": event_end_time.strftime(DATE_AND_TIME_FORMAT_STRING),
                    "timeZone": config.timezone,
                },
                "source": {
                    "title": "Notion Link",
                    "url": source_url,
                },
            }
        else:
            event_end_time = event_end_time + datetime.timedelta(
                days=1
            )  # gotta make it to 12AM the day after
            event = {
                "summary": event_name,
                "description": event_description,
                "start": {
                    "date": event_start_time.strftime("%Y-%m-%d"),
                    "timeZone": config.timezone,
                },
                "end": {
                    "date": event_end_time.strftime("%Y-%m-%d"),
                    "timeZone": config.timezone,
                },
                "source": {
                    "title": "Notion Link",
                    "url": source_url,
                },
            }
    elif (
        event_start_time.hour == 0
        and event_start_time.minute == 0
        and event_end_time.hour == 0
        and event_end_time.minute == 0
        and event_start_time != event_end_time
    ):

        event_end_time = event_end_time + datetime.timedelta(
            days=1
        )  # gotta make it to 12AM the day after

        event = {
            "summary": event_name,
            "description": event_description,
            "start": {
                "date": event_start_time.strftime("%Y-%m-%d"),
                "timeZone": config.timezone,
            },
            "end": {
                "date": event_end_time.strftime("%Y-%m-%d"),
                "timeZone": config.timezone,
            },
            "source": {
                "title": "Notion Link",
                "url": source_url,
            },
        }

    else:
        if event_start_time.hour == 0 and event_start_time.minute == 0:
            if event_end_time == event_start_time:
                # if the datetime fed into this is only a date or is at 12 AM,
                # then the event will fall under here
                event_start_time = datetime.datetime.combine(
                    event_start_time, datetime.datetime.min.time()
                ) + datetime.timedelta(
                    hours=config.default_event_start
                )  # make the events pop up at 8 am instead of 12 am
                event_end_time = event_start_time + datetime.timedelta(
                    minutes=config.default_event_length
                )
        elif event_end_time == event_start_time:
            # this would meant that only 1 datetime was actually on the notion dashboard
            event_end_time = event_start_time + datetime.timedelta(
                minutes=config.default_event_length
            )

        event = {
            "summary": event_name,
            "description": event_description,
            "start": {
                "dateTime": event_start_time.strftime(DATE_AND_TIME_FORMAT_STRING),
                "timeZone": config.timezone,
            },
            "end": {
                "dateTime": event_end_time.strftime(DATE_AND_TIME_FORMAT_STRING),
                "timeZone": config.timezone,
            },
            "source": {
                "title": "Notion Link",
                "url": source_url,
            },
        }
    logging.info(f"Adding this event to calendar: {event_name}")

    logging.info(event)
    x = service.events().insert(calendarId=cal_id, body=event).execute()
    return x["id"]

make_event_description(initiative, info)

Make a calendar event description.

This method can be edited as wanted. Whatever is returned from this method will be in the GCal event description Whatever you change up, be sure to return a string

Source code in ncal/core.py
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
def make_event_description(initiative, info):
    """Make a calendar event description.

    This method can be edited as wanted. Whatever is returned from this method will
    be in the GCal event description
    Whatever you change up, be sure to return a string
    """
    if initiative == "" and info == "":
        return ""
    elif info == "":
        return initiative
    elif initiative == "":
        return info
    else:
        return f"Initiative: {initiative} \n{info}"

make_task_url(ending, url_root)

Create a task's url.

Source code in ncal/core.py
1404
1405
1406
1407
1408
1409
def make_task_url(ending: str, url_root: str):
    """Create a task's url."""
    # To make a url for the notion task, we have to take the id of the task and take
    # away the hyphens from the string
    url_id = ending.replace("-", "")
    return url_root + url_id

new_events_gcal_to_notion(database_id, calendar_dictionary, task_notion_name, date_notion_name, extra_info_notion_name, on_gcal_notion_name, gcal_event_id_notion_name, last_updated_time_notion_name, calendar_notion_name, current_calendar_id_notion_name, delete_notion_name, service, notion, settings)

Bring events (not in Notion already) from GCal to Notion.

First, we get a list of all of the GCal Event Ids from the Notion Dashboard.

Source code in ncal/core.py
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
def new_events_gcal_to_notion(
    database_id,
    calendar_dictionary,
    task_notion_name,
    date_notion_name,
    extra_info_notion_name,
    on_gcal_notion_name,
    gcal_event_id_notion_name,
    last_updated_time_notion_name,
    calendar_notion_name,
    current_calendar_id_notion_name,
    delete_notion_name,
    service,
    notion,
    settings: config.Settings,
):
    """
    Bring events (not in Notion already) from GCal to Notion.

    First, we get a list of all of the GCal Event Ids from the Notion Dashboard.
    """
    my_page = paginated_database_query(
        notion,
        database_id,
        **{
            "filter": {
                "and": [
                    {
                        "property": gcal_event_id_notion_name,
                        "text": {"is_not_empty": True},
                    },
                    {"property": delete_notion_name, "checkbox": {"equals": False}},
                ]
            },
        },
    )

    my_page = paginated_database_query(
        notion,
        database_id,
        **{
            "filter": {
                "property": gcal_event_id_notion_name,
                "text": {"is_not_empty": True},
            },
        },
    )

    result_list = my_page

    all_notion_gcal_ids = []

    for result in result_list:
        all_notion_gcal_ids.append(
            result["properties"][gcal_event_id_notion_name]["rich_text"][0]["text"][
                "content"
            ]
        )

    # Get the GCal Ids and other Event Info from Google Calendar

    events = []
    # get all the events from all calendars of interest
    for key, value in calendar_dictionary.items():
        x = (
            service.events()
            .list(calendarId=value, maxResults=2000, timeMin=arrow.utcnow().isoformat())
            .execute()
        )
        events.extend(x["items"])
        time.sleep(0.1)

    logging.info(events)

    cal_items = events

    cal_name = [item["summary"] for item in cal_items]

    gcal_calendar_id = [
        item["organizer"]["email"] for item in cal_items
    ]  # this is to get all of the calendarIds for each event

    cal_names = list(calendar_dictionary.keys())
    cal_ids = list(calendar_dictionary.values())
    gcal_calendar_name = [cal_names[cal_ids.index(x)] for x in gcal_calendar_id]

    cal_start_dates = []
    cal_end_dates = []
    for el in cal_items:
        try:
            cal_start_dates.append(dateutil.parser.isoparse(el["start"]["dateTime"]))
        except KeyError:
            date = datetime.datetime.strptime(el["start"]["date"], "%Y-%m-%d")
            x = datetime.datetime(date.year, date.month, date.day, 0, 0, 0)
            cal_start_dates.append(x)
        try:
            cal_end_dates.append(dateutil.parser.isoparse(el["end"]["dateTime"]))
        except KeyError:
            date = datetime.datetime.strptime(el["end"]["date"], "%Y-%m-%d")
            x = datetime.datetime(date.year, date.month, date.day, 0, 0, 0)
            cal_end_dates.append(x)

    cal_ids = [item["id"] for item in cal_items]
    cal_descriptions = []
    for item in cal_items:
        try:
            cal_descriptions.append(item["description"])
        except KeyError:
            cal_descriptions.append(" ")

    # Now, we compare the Ids from Notion and Ids from GCal. If the Id from GCal is
    # not in the list from Notion, then we know that the event does not exist in
    # Notion yet, so we should bring that over.

    for i in range(len(cal_ids)):
        if cal_ids[i] not in all_notion_gcal_ids:
            if cal_start_dates[i] == cal_end_dates[i] - datetime.timedelta(
                days=1
            ):  # only add in the start DATE
                # Here, we create a new page for every new GCal event
                end = cal_end_dates[i] - datetime.timedelta(days=1)
                my_page = notion.pages.create(
                    **{
                        "parent": {
                            "database_id": database_id,
                        },
                        "properties": {
                            task_notion_name: {
                                "type": "title",
                                "title": [
                                    {
                                        "type": "text",
                                        "text": {
                                            "content": cal_name[i],
                                        },
                                    },
                                ],
                            },
                            date_notion_name: {
                                "type": "date",
                                "date": {
                                    "start": cal_start_dates[i].strftime("%Y-%m-%d"),
                                    "end": None,
                                },
                            },
                            last_updated_time_notion_name: {
                                "type": "date",
                                "date": {
                                    "start": arrow.utcnow().isoformat(),
                                    "end": None,
                                },
                            },
                            extra_info_notion_name: {
                                "type": "rich_text",
                                "rich_text": [
                                    {"text": {"content": cal_descriptions[i]}}
                                ],
                            },
                            gcal_event_id_notion_name: {
                                "type": "rich_text",
                                "rich_text": [{"text": {"content": cal_ids[i]}}],
                            },
                            on_gcal_notion_name: {"type": "checkbox", "checkbox": True},
                            current_calendar_id_notion_name: {
                                "rich_text": [
                                    {"text": {"content": gcal_calendar_id[i]}}
                                ]
                            },
                            calendar_notion_name: {
                                "select": {"name": gcal_calendar_name[i]},
                            },
                        },
                    },
                )

            elif (
                cal_start_dates[i].hour == 0
                and cal_start_dates[i].minute == 0
                and cal_end_dates[i].hour == 0
                and cal_end_dates[i].minute == 0
            ):  # add start and end in DATE format
                # Here, we create a new page for every new GCal event
                end = cal_end_dates[i] - datetime.timedelta(days=1)

                my_page = notion.pages.create(
                    **{
                        "parent": {
                            "database_id": database_id,
                        },
                        "properties": {
                            task_notion_name: {
                                "type": "title",
                                "title": [
                                    {
                                        "type": "text",
                                        "text": {
                                            "content": cal_name[i],
                                        },
                                    },
                                ],
                            },
                            date_notion_name: {
                                "type": "date",
                                "date": {
                                    "start": cal_start_dates[i].strftime("%Y-%m-%d"),
                                    "end": end.strftime("%Y-%m-%d"),
                                },
                            },
                            last_updated_time_notion_name: {
                                "type": "date",
                                "date": {
                                    "start": arrow.utcnow().isoformat(),
                                    "end": None,
                                },
                            },
                            extra_info_notion_name: {
                                "type": "rich_text",
                                "rich_text": [
                                    {"text": {"content": cal_descriptions[i]}}
                                ],
                            },
                            gcal_event_id_notion_name: {
                                "type": "rich_text",
                                "rich_text": [{"text": {"content": cal_ids[i]}}],
                            },
                            on_gcal_notion_name: {"type": "checkbox", "checkbox": True},
                            current_calendar_id_notion_name: {
                                "rich_text": [
                                    {"text": {"content": gcal_calendar_id[i]}}
                                ]
                            },
                            calendar_notion_name: {
                                "select": {"name": gcal_calendar_name[i]},
                            },
                        },
                    },
                )

            else:  # regular datetime stuff
                # Here, we create a new page for every new GCal event
                my_page = notion.pages.create(
                    **{
                        "parent": {
                            "database_id": database_id,
                        },
                        "properties": {
                            task_notion_name: {
                                "type": "title",
                                "title": [
                                    {
                                        "type": "text",
                                        "text": {
                                            "content": cal_name[i],
                                        },
                                    },
                                ],
                            },
                            date_notion_name: {
                                "type": "date",
                                "date": {
                                    "start": cal_start_dates[i].isoformat(),
                                    "end": cal_end_dates[i].isoformat(),
                                },
                            },
                            last_updated_time_notion_name: {
                                "type": "date",
                                "date": {
                                    "start": arrow.utcnow().isoformat(),
                                    "end": None,
                                },
                            },
                            extra_info_notion_name: {
                                "type": "rich_text",
                                "rich_text": [
                                    {"text": {"content": cal_descriptions[i]}}
                                ],
                            },
                            gcal_event_id_notion_name: {
                                "type": "rich_text",
                                "rich_text": [{"text": {"content": cal_ids[i]}}],
                            },
                            on_gcal_notion_name: {"type": "checkbox", "checkbox": True},
                            current_calendar_id_notion_name: {
                                "rich_text": [
                                    {"text": {"content": gcal_calendar_id[i]}}
                                ]
                            },
                            calendar_notion_name: {
                                "select": {"name": gcal_calendar_name[i]},
                            },
                        },
                    },
                )

            logging.info(f"Added this event to Notion: {cal_name[i]}")

new_events_notion_to_gcal(database_id, url_root, default_calendar_name, calendar_dictionary, task_notion_name, date_notion_name, initiative_notion_name, extra_info_notion_name, on_gcal_notion_name, gcal_event_id_notion_name, last_updated_time_notion_name, calendar_notion_name, current_calendar_id_notion_name, delete_notion_name, notion, service, settings)

Take Notion Events not on GCal and move them over to GCal.

If you just want all Notion events to be on GCal, then you'll have to edit the query so it is only checking the 'On GCal?' property

Source code in ncal/core.py
 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
def new_events_notion_to_gcal(
    database_id,
    url_root,
    default_calendar_name,
    calendar_dictionary,
    task_notion_name,
    date_notion_name,
    initiative_notion_name,
    extra_info_notion_name,
    on_gcal_notion_name,
    gcal_event_id_notion_name,
    last_updated_time_notion_name,
    calendar_notion_name,
    current_calendar_id_notion_name,
    delete_notion_name,
    notion,
    service,
    settings: config.Settings,
):
    """
    Take Notion Events not on GCal and move them over to GCal.

    If you just want all Notion events to be on GCal, then you'll have to edit the
    query so it is only checking the 'On GCal?' property
    """

    def get_new_notion_pages(
        database_id: str,
        on_gcal_notion_name: str,
        date_notion_name: str,
        delete_notion_name: str,
        notion: nc.Client,
    ) -> list:
        """Get new pages from notion (with pagination!)."""
        matching_pages = []

        query = {
            # "database_id": database_id,
            "filter": {
                "and": [
                    {
                        "property": on_gcal_notion_name,
                        "checkbox": {"equals": False},
                    },
                    {"property": delete_notion_name, "checkbox": {"equals": False}},
                ]
            },
        }

        matching_pages = paginated_database_query(notion, database_id, **query)
        return matching_pages

    result_list = get_new_notion_pages(
        database_id, on_gcal_notion_name, date_notion_name, delete_notion_name, notion
    )

    # logging.info(len(result_list))

    try:
        logging.info(result_list[0])
    except IndexError:
        logging.info("index error")

    task_names = []
    start_dates = []
    end_times = []
    initiatives = []
    extra_info = []
    url_list = []
    cal_event_id_list = []
    calendar_list = []

    if len(result_list) > 0:
        for i, el in enumerate(result_list):
            logging.info(el)

            task_names.append(
                notion_utils.collapse_rich_text_property(
                    el["properties"][task_notion_name]["title"]
                )
            )
            start_dates.append(el["properties"][date_notion_name]["date"]["start"])

            if el["properties"][date_notion_name]["date"]["end"] is not None:
                end_times.append(el["properties"][date_notion_name]["date"]["end"])
            else:
                end_times.append(el["properties"][date_notion_name]["date"]["start"])

            try:
                initiatives.append(
                    get_property_text(
                        notion=notion,
                        notion_page=el,
                        property_name=initiative_notion_name,
                        property_type=settings.initiative_notion_type,
                    )
                )
            except ValueError:
                initiatives.append("")

            try:
                extra_info.append(
                    el["properties"][extra_info_notion_name]["rich_text"][0]["text"][
                        "content"
                    ]
                )
            except IndexError:
                extra_info.append("")
            url_list.append(make_task_url(el["id"], url_root))

            try:
                calendar_list.append(
                    calendar_dictionary[
                        el["properties"][calendar_notion_name]["select"]["name"]
                    ]
                )
            # keyerror occurs when there's nothing put into the calendar in the first
            # place
            except (KeyError, TypeError):
                calendar_list.append(calendar_dictionary[default_calendar_name])

            page_id = el["id"]
            # This checks off that the event has been put on Google Calendar
            notion.pages.update(
                **{
                    "page_id": page_id,
                    "properties": {
                        on_gcal_notion_name: {"checkbox": True},
                        last_updated_time_notion_name: {
                            "date": {
                                "start": arrow.utcnow().isoformat(),
                                "end": None,
                            }
                        },
                    },
                },
            )
            logging.info(calendar_list)

            def create_gcal_event(
                task_name,
                initiative,
                extra_info,
                start,
                end,
                url,
                calendar,
                service,
                settings: config.Settings,
            ):
                # 2 Cases: Start and End are  both either date or date+time
                # Have restriction that the calendar events don't cross days
                try:
                    # start and end are both dates
                    cal_event_id = make_cal_event(
                        task_name,
                        make_event_description(initiative, extra_info),
                        datetime.datetime.strptime(start, "%Y-%m-%d"),
                        url,
                        datetime.datetime.strptime(end, "%Y-%m-%d"),
                        calendar,
                        service,
                        settings,
                    )
                except ValueError:
                    try:
                        # start and end are both date+time
                        cal_event_id = make_cal_event(
                            task_name,
                            make_event_description(initiative, extra_info),
                            dateutil.parser.isoparse(start),
                            url,
                            dateutil.parser.isoparse(end),
                            calendar,
                            service,
                            settings,
                        )
                    except ValueError:
                        cal_event_id = make_cal_event(
                            task_name,
                            make_event_description(initiative, extra_info),
                            dateutil.parser.isoparse(start),
                            url,
                            dateutil.parser.isoparse(end),
                            calendar,
                            service,
                            settings,
                        )
                return cal_event_id

            cal_event_id = create_gcal_event(
                task_names[i],
                initiatives[i],
                extra_info[i],
                start_dates[i],
                end_times[i],
                url_list[i],
                calendar_list[i],
                service,
                settings,
            )
            cal_event_id_list.append(cal_event_id)

            if (
                calendar_list[i] == calendar_dictionary[default_calendar_name]
            ):  # this means that there is no calendar assigned on Notion
                # This puts the the GCal Id into the Notion Dashboard
                notion.pages.update(
                    **{
                        "page_id": page_id,
                        "properties": {
                            gcal_event_id_notion_name: {
                                "rich_text": [
                                    {"text": {"content": cal_event_id_list[i]}}
                                ]
                            },
                            current_calendar_id_notion_name: {
                                "rich_text": [{"text": {"content": calendar_list[i]}}]
                            },
                            calendar_notion_name: {
                                "select": {"name": default_calendar_name},
                            },
                        },
                    },
                )
            else:  # just a regular update
                notion.pages.update(
                    **{
                        "page_id": page_id,
                        "properties": {
                            gcal_event_id_notion_name: {
                                "rich_text": [
                                    {"text": {"content": cal_event_id_list[i]}}
                                ]
                            },
                            current_calendar_id_notion_name: {
                                "rich_text": [{"text": {"content": calendar_list[i]}}]
                            },
                        },
                    },
                )

    else:
        logging.info("Nothing new added to GCal")
    return

paginated_database_query(notion_client, database_id, **query)

Similar to notion_client.database.query(**query).

Parameters:

Name Type Description Default
notion_client nc.Client required
database_id str required
**query Any

A query such as would be used for the normal notion_client query

{}

Returns:

Type Description
list

List of notion pages matching the query

Source code in ncal/core.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def paginated_database_query(
    notion_client: nc.Client, database_id: str, **query: Any
) -> list:
    """Similar to notion_client.database.query(**query).

    Args:
        notion_client:
        database_id:
        **query: A query such as would be used for the normal notion_client query
    Returns:
        List of notion pages matching the query
    """
    matching_pages = []

    while True:
        # this query will return a dictionary that we will parse
        # for information that we want
        response = notion_client.databases.query(database_id, **query)
        matching_pages.extend(response["results"])  # type: ignore
        if response["next_cursor"]:  # type: ignore
            query["start_cursor"] = response["next_cursor"]  # type: ignore
        else:
            break
    return matching_pages

setup_api_connections(default_calendar_id, credentials_location, notion_api_token, client_secret_location)

Set up the API connections to Google Calendar and notion.

Parameters:

Name Type Description Default
default_calendar_id str

gcal calendar Id

required
credentials_location

location of the credentials pickle file

required
notion_api_token str

token from the notion api

required

Returns:

Type Description
tuple[googleapiclient.discovery.Resource, Any, nc.Client]

(google api service, calendar, notion client)

Source code in ncal/core.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def setup_api_connections(
    default_calendar_id: str,
    credentials_location,
    notion_api_token: str,
    client_secret_location,
) -> tuple[googleapiclient.discovery.Resource, Any, nc.Client]:
    """Set up the API connections to Google Calendar and notion.

    Args:
        default_calendar_id: gcal calendar Id
        credentials_location: location of the credentials pickle file
        notion_api_token: token from the notion api
    Returns:
        (google api service, calendar, notion client)
    """
    # setup google api
    service, calendar = setup_google_api(
        calendar_id=default_calendar_id,
        token_file=str(credentials_location),
        client_secret_file=str(client_secret_location),
    )
    # This is where we set up the connection with the Notion API
    notion = nc.Client(auth=notion_api_token)
    return service, calendar, notion

update_calendar_event(event_name, event_description, event_start_time, source_url, event_id, event_end_time, current_cal_id, cal_id, service, config)

Update a Google Calendar event.

Parameters:

Name Type Description Default
event_name required
event_description required
event_start_time required
source_url required
event_id required
event_end_time required
current_cal_id required
cal_id required
service required
config config.Settings required

Returns:

Name Type Description
_type_

description

Source code in ncal/core.py
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
def update_calendar_event(
    event_name,
    event_description,
    event_start_time,
    source_url,
    event_id,
    event_end_time,
    current_cal_id,
    cal_id,
    service,
    config: config.Settings,
):
    """Update a Google Calendar event.

    Args:
        event_name:
        event_description:
        event_start_time:
        source_url:
        event_id:
        event_end_time:
        current_cal_id:
        cal_id:
        service:
        config (config.Settings):

    Returns:
        _type_: _description_
    """
    if (
        event_start_time.hour == 0
        and event_start_time.minute == 0
        and event_end_time == event_start_time
    ):  # you're given a single date
        if config.all_day_event_option == 1:
            event_start_time = datetime.datetime.combine(
                event_start_time, datetime.datetime.min.time()
            ) + datetime.timedelta(
                hours=config.default_event_start
            )  # make the events pop up at 8 am instead of 12 am
            event_end_time = event_start_time + datetime.timedelta(
                minutes=config.default_event_length
            )
            event = {
                "summary": event_name,
                "description": event_description,
                "start": {
                    "dateTime": event_start_time.strftime(DATE_AND_TIME_FORMAT_STRING),
                    "timeZone": config.timezone,
                },
                "end": {
                    "dateTime": event_end_time.strftime(DATE_AND_TIME_FORMAT_STRING),
                    "timeZone": config.timezone,
                },
                "source": {
                    "title": "Notion Link",
                    "url": source_url,
                },
            }
        else:
            event_end_time = event_end_time + datetime.timedelta(
                days=1
            )  # gotta make it to 12AM the day after
            event = {
                "summary": event_name,
                "description": event_description,
                "start": {
                    "date": event_start_time.strftime("%Y-%m-%d"),
                    "timeZone": config.timezone,
                },
                "end": {
                    "date": event_end_time.strftime("%Y-%m-%d"),
                    "timeZone": config.timezone,
                },
                "source": {
                    "title": "Notion Link",
                    "url": source_url,
                },
            }
    elif (
        event_start_time.hour == 0
        and event_start_time.minute == 0
        and event_end_time.hour == 0
        and event_end_time.minute == 0
        and event_start_time != event_end_time
    ):  # it's a multiple day event

        event_end_time = event_end_time + datetime.timedelta(
            days=1
        )  # gotta make it to 12AM the day after

        event = {
            "summary": event_name,
            "description": event_description,
            "start": {
                "date": event_start_time.strftime("%Y-%m-%d"),
                "timeZone": config.timezone,
            },
            "end": {
                "date": event_end_time.strftime("%Y-%m-%d"),
                "timeZone": config.timezone,
            },
            "source": {
                "title": "Notion Link",
                "url": source_url,
            },
        }

    else:  # just 2 datetimes passed in
        if event_start_time.hour == 0 and event_start_time.minute == 0:
            if event_end_time != event_start_time:
                # Start on Notion is 12 am and end is also given on Notion
                pass
            else:
                # if the datetime fed into this is only a date or is at 12 AM,
                # then the event will fall under here
                event_start_time = datetime.datetime.combine(
                    event_start_time, datetime.datetime.min.time()
                ) + datetime.timedelta(
                    hours=config.default_event_start
                )  # make the events pop up at 8 am instead of 12 am
                event_end_time = event_start_time + datetime.timedelta(
                    minutes=config.default_event_length
                )
        elif event_end_time == event_start_time:
            # this would meant that only 1 datetime was actually on the notion dashboard
            event_end_time = event_start_time + datetime.timedelta(
                minutes=config.default_event_length
            )

        event = {
            "summary": event_name,
            "description": event_description,
            "start": {
                "dateTime": event_start_time.strftime(DATE_AND_TIME_FORMAT_STRING),
                "timeZone": config.timezone,
            },
            "end": {
                "dateTime": event_end_time.strftime(DATE_AND_TIME_FORMAT_STRING),
                "timeZone": config.timezone,
            },
            "source": {
                "title": "Notion Link",
                "url": source_url,
            },
        }
    logging.info(f"Updating this event to calendar: {event_name}")

    if current_cal_id == cal_id:
        x = (
            service.events()
            .update(calendarId=cal_id, eventId=event_id, body=event)
            .execute()
        )

    else:
        # When we have to move the event to a new calendar.
        # We must move the event over to the new calendar and
        # then update the information on the event
        logging.info("Event " + event_id)
        logging.info("CurrentCal " + current_cal_id)
        logging.info("NewCal " + cal_id)
        x = (
            service.events()
            .move(calendarId=current_cal_id, eventId=event_id, destination=cal_id)
            .execute()
        )
        logging.info("New event id: " + x["id"])
        x = (
            service.events()
            .update(calendarId=cal_id, eventId=event_id, body=event)
            .execute()
        )

    return x["id"]
Back to top