Exemplo n.º 1
0
def notion_update_event(notion_event, event):
    n_date = None

    # date - x - All day event
    # date - date - Many days event`
    # datetime - x - Not impossible with google events
    # datetime - datetime - regular

    n_date = NotionDate(
        convert_datetime_timezone(event["start"], 'UTC', event['timezone']))
    n_date.end = convert_datetime_timezone(event["end"], 'UTC',
                                           event['timezone'])
    n_date.timezone = event["timezone"]

    try:
        notion_event.name = event["title"]
        setattr(notion_event, notion_date_prop, n_date)
        # setattr(notion_event, notion_cal_prop, event["calendar"])
        print(f"[{datetime.datetime.now()}] N UPDATE DONE {event['title']}")
    except Exception as e:
        print(f"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} " +
              str(e))
        return None

    return notion_event
Exemplo n.º 2
0
def update_done_card():
    """
    DONE 상태의 카드의 DURATION을 새로 기록합니다.
    DURATION의 값이 없을 경우에는 시작일과 종료일을 모두 당일로 설정합니다.
    시작일이 존재할 때에는 종료일만 당일로 설정합니다.
    """
    key = notion.CARD_STATUS
    done = notion.DONE
    duration = notion.CARD_DURATION

    today = date.today()

    for card_id in notion.get_filtered_card_ids(key, done):
        card = notion.client.get_block(card_id)
        notion_date = card.get_property(duration)

        if not notion_date:
            notion_date = NotionDate(start=today, end=today)

        if notion_date.start == None:
            notion_date = NotionDate(start=today)

        if notion_date.end == None:
            notion_date = NotionDate(start=notion_date.start, end=today)

        card.set_property(duration, notion_date)
 def __init__(self, dStart, dEnd, UID, description, lastModified, name):
     self.name = name
     if (recordEndDate):
         self.date = NotionDate(formatDate(dStart), formatDate(dEnd))
     else:
         self.date = NotionDate(formatDate(dStart))
     self.UID = UID
     self.lastModified = NotionDate(formatDate(lastModified))
     self.description = description
Exemplo n.º 4
0
def add_or_update(row, event):
    row.Name = event.name
    # Check if the event is an "All Day" these get messed up if we do a direct conversion
    if event.duration == timedelta(days=1):
        row.Do = NotionDate((event.begin))
    else:
        row.Do = NotionDate(datetime.fromisoformat(str(event.begin)),
                            datetime.fromisoformat(str(event.end)))
    row.Type = "Event"
def create_notion_dates_start_end_submitted(start, active_day,
                                            last_working_day):
    # TODO: Add weekend and holiday validation logic for last working day and date submitted
    end = start + timedelta(days=last_working_day - active_day)
    validated_end = validate_date(end)
    assignment_submitted_date = validated_end + timedelta(days=1)
    assignment_start_end = NotionDate(start, end=validated_end)
    assignment_submitted = NotionDate(assignment_submitted_date)
    all_date_objects = [assignment_start_end, assignment_submitted]
    return all_date_objects
Exemplo n.º 6
0
def _add_book_to_notion(title: str, author: str, highlight_count: int,
                        aggregated_text: str, last_date: str,
                        notion_token: str, notion_table_id: str,
                        enable_book_cover: bool) -> str:
    notion_client = NotionClient(token_v2=notion_token)
    notion_collection_view = notion_client.get_collection_view(notion_table_id)
    notion_collection_view_rows = notion_collection_view.collection.get_rows()

    title_exists = False
    if notion_collection_view_rows:
        for row in notion_collection_view_rows:
            if title == row.title and author == row.author:
                title_exists = True
                row = row

                if row.highlights is None:
                    row.highlights = 0  # to initialize number of highlights as 0
                elif row.highlights == highlight_count:  # if no change in highlights
                    return 'None to add'

    title_and_author = title + ' (' + str(author) + ')'
    print(title_and_author)
    print('-' * len(title_and_author))

    if not title_exists:
        row = notion_collection_view.collection.add_row()
        row.title = title
        row.author = author
        row.highlights = 0

        if enable_book_cover:
            if row.cover is None:
                result = _get_book_cover_uri(row.title, row.author)
            if result is not None:
                row.cover = result
                print('✓ Added book cover')
            else:
                row.cover = NO_COVER_IMG
                print(
                    '× Book cover couldn\'t be found. '
                    'Please replace the placeholder image with the original book cover manually.'
                )

    parent_page = notion_client.get_block(row.id)

    # For existing books with new highlights to add
    for all_blocks in parent_page.children:
        all_blocks.remove()
    parent_page.children.add_new(TextBlock, title=aggregated_text)
    diff_count = highlight_count - row.highlights
    row.highlights = highlight_count
    row.last_highlighted = NotionDate(parse(last_date))
    row.last_synced = NotionDate(datetime.now())
    message = str(diff_count) + ' notes / highlights added successfully\n'
    return message
Exemplo n.º 7
0
def notion_add_event(notion_client, google_client, event):

    n_date = NotionDate(
        convert_datetime_timezone(event["start"], 'UTC', event['timezone']))
    n_date.end = convert_datetime_timezone(event["end"], 'UTC',
                                           event['timezone'])
    n_date.timezone = event["timezone"]

    try:
        notion_event = notion_client.collection.add_row()
        notion_event.name = event["title"]
        setattr(notion_event, notion_date_prop, n_date)
        # setattr(notion_event, notion_cal_prop, event["calendar"])

        print(f"[{datetime.datetime.now()}] N ADD DONE {event['title']}")

    except Exception as e:
        print(f"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} " +
              str(e))
        return None

    try:
        nevent_id = str(notion_event.id.replace("-", "00a00"))
        event_body = google_client.events().get(
            calendarId=google_calendar_ids[event["calendar"]],
            eventId=event["id"]).execute()
    except Exception as e:
        print(f"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} " +
              str(e))
        return None

    event_body["id"] = nevent_id
    del event_body["iCalUID"]
    if 'recurringEventId' in event_body:
        del event_body['recurringEventId']

    try:
        google_client.events().delete(
            calendarId=google_calendar_ids[event["calendar"]],
            eventId=event["id"]).execute()
        event_body_new = google_client.events().insert(
            calendarId=google_calendar_ids[event["calendar"]],
            body=event_body).execute()
        print(
            f"[{datetime.datetime.now()}] N ADD (G ID) DONE {event['title']}")
    except Exception as e:
        # notion_delete_event(notion_event)
        print(f"[{datetime.datetime.now()}] | {str(inspect.stack()[0][3])} " +
              str(e))
        return None

    return notion_event
Exemplo n.º 8
0
    def addBookToNotion(self, title, author, highlightCount, aggregatedText,
                        lastNoteDate):
        titleExists = False

        if allRows != []:
            for eachRow in allRows:
                # to account for the use-case of books with the same name by different authors
                if title == eachRow.title and author == eachRow.author:
                    titleExists = True
                    row = eachRow

                    if row.highlights == None:
                        row.highlights = 0  # to initialize number of highlights as 0
                    elif row.highlights == highlightCount:  # if no change in highlights
                        return ("None to add")

        titleAndAuthor = title + " (" + str(author) + ")"
        print(titleAndAuthor)
        print("-" * len(titleAndAuthor))

        if not titleExists:
            row = cv.collection.add_row()
            row.title = title
            row.author = author
            row.highlights = 0

            if ENABLE_BOOK_COVER:
                if row.cover == None:
                    result = getBookCoverURI(row.title, row.author)
                if result != None:
                    row.cover = result
                    print("✓ Added book cover")
                else:
                    row.cover = NO_COVER_IMG
                    print(
                        "× Book cover couldn't be found. Please replace the placeholder image with the original book cover manually"
                    )

        parentPage = client.get_block(row.id)

        # For existing books with new highlights to add
        for allBlocks in parentPage.children:
            allBlocks.remove()
        parentPage.children.add_new(TextBlock, title=aggregatedText)
        diffCount = highlightCount - row.highlights
        row.highlights = highlightCount
        row.last_highlighted = NotionDate(lastNoteDate)
        row.last_synced = NotionDate(datetime.now())
        message = str(diffCount) + " notes / highlights added successfully\n"
        return (message)
Exemplo n.º 9
0
def create_entry():
    token = request.args.get("token")
    content = request.get_json(silent=True)
    print(content)
    ## [{ value, slug, type }]

    client = NotionClient(token)
    url = request.args.get('url')
    cv = client.get_collection_view(url)
    row = cv.collection.add_row()

    ## Types:
    ##      date => NotionDate ✅
    ##      relation => ????
    ##      title => string ✅
    ##      select => string ✅

    for prop in content:
        val = prop['value']
        if (prop['type'] == 'date'):
            datet = datetime.fromtimestamp(prop['value'])
            val = NotionDate(datet)
        row.set_property(prop['slug'], val)

    response = app.response_class(status=200, mimetype='application/json')
    return response
    def translate_post(df):
        title_jpn = translate(title)
        abst_jpn = translate(abst)
        print("-------"+str(count)+"ページ目-------")
        print("author:{}".format(author))
        print(url)
        print("title:{}".format(title_jpn))
        print("date:{}".format(date))
        print("Abstract:{}".format(abst_jpn))
        print("Category:{}".format(cat))
        print(df.iloc[1,1])
        
#notionへの投稿
        duplicated_title_row = cv.collection.get_rows(search=url) #投稿しようとしている内容が投稿済みでないかを確認(urlで判別)
        print(len(duplicated_title_row))
        if(len(duplicated_title_row)==0): #重複しなければNotion DBへ投稿
            row = cv.collection.add_row()
            row.name = title_jpn
            row.author = author
            row.category = cat
            row.url = url
            row.abstract_jp = abst_jpn
            row.abstract = abst
            row.title = title
            row.submitted_time = NotionDate(date)
            row.children.add_new(TextBlock, title=abst_jpn)

        sleep(20)
Exemplo n.º 11
0
def describe_event(event):
    res = {}
    target_time_zone = pytz.timezone('Europe/Moscow')
    start_msk = event["DTSTART"].dt
    end_msk = event["DTEND"].dt
    if isinstance(start_msk, datetime.datetime) \
            and isinstance(end_msk, datetime.datetime):
        start_msk = start_msk.astimezone(target_time_zone)
        end_msk = end_msk.astimezone(target_time_zone)
    elif (end_msk-start_msk).days == 1:
        start_msk = pd.to_datetime(start_msk)
        end_msk = None
    else:
        start_msk = pd.to_datetime(start_msk)
        end_msk = pd.to_datetime(end_msk)
    res['title'] = str(event['SUMMARY'])
    loc = str(event['LOCATION'])
    if ' ' not in loc:
        loc = loc.capitalize()
    try:
        desc = str(event['DESCRIPTION'])
    except Exception:
        desc = None
    res['description'] = desc
    link = find_url(desc)
    res['link'] = link
    res['location'] = loc if loc else None
    reminder = None  # {'unit': 'minute', 'value': 3}
    res['date'] = NotionDate(
        start_msk, end_msk, reminder=reminder)
    return res
Exemplo n.º 12
0
def get_rtime(top, qs):
    print("Getting revised time list...")
    rtime_list = []
    for q in qs:
        time = NotionDate(start=datetime.now())
        rtime_list.append(time)
    return rtime_list
Exemplo n.º 13
0
    def to_notion(manager: syncManager, item: task):

        manager.tasks.refresh()

        # get project info
        project = manager.projects.collection.get_rows(search=str(item.project_id))[0]

        # check if due date data available
        try:
            due = NotionDate(start=datetime.strptime(item.due, "%Y-%m-%d").date())
        except (AttributeError, TypeError):
            due = None

        # get labels
        label_dict = labelManager.give_notion_labels(manager, item)

        new_row = manager.tasks.collection.add_row()
        new_row.name = item.content
        new_row.TodoistID = item.task_id
        new_row.due = due
        new_row.project = project
        new_row.NotionID = new_row.id

        # set group if necessary
        if manager.use_groups:
            new_row.group = project.group[0]

        # set labels:
        for label_column, labels in label_dict.items():
            new_row.set_property(label_column, labels)

        print(f"Imported task {item.content} with labels {item.label_names}.")

        return new_row.id
Exemplo n.º 14
0
def get_previous_or_target_headers(page, target_date):
    prev_date = datetime.datetime.strptime(
        "1900-01-01", "%Y-%m-%d").date()  # start date for comparison
    store = page.children[0]
    for child in page.children:
        block_type = child.get("type")
        if "header" in block_type:  # check only headers block
            prop = child.get("properties")
            if prop is None:
                continue
            title = prop["title"]
            date = get_date_from_title(title)
            if date:
                d = NotionDate.from_notion([date])
                if isinstance(
                        d.start,
                        datetime.datetime):  # check only date, ignore time
                    date = d.start.date()
                else:
                    date = d.start
                if date == target_date:  # if date is same return exact date
                    return "exact", child
                else:
                    if prev_date < date < target_date:  # update last item and continue searching
                        store = child
                        prev_date = date
    return "prev", store
Exemplo n.º 15
0
def add_visit(token, clients_url, visits_url, telefon, fio, chto_budem_delat,
              stoimost, datetime_start, datetime_end):
    client = NotionClient(token)
    clients_collection = client.get_collection_view(clients_url)
    # filter_params = [{
    #     "property": "telefon",
    #     "comparator": "enum_contains",
    #     "value": telefon
    # }]
    # results = clients_collection.build_query(filter=filter_params).execute()
    # if results:
    #     customer = results[0]
    # else:
    #     customer = clients_collection.collection.add_row()
    #     customer.telefon = telefon
    #     customer.fio = fio

    visits_collection = client.get_collection_view(visits_url)
    visit = visits_collection.collection.add_row()
    # visit.klient = customer
    try:
        visit.stoimost = int(stoimost)
    except:
        pass
    visit.chto_budem_delat = chto_budem_delat
    visit.data = NotionDate(start=datetime_start, end=datetime_end)
Exemplo n.º 16
0
 def _addToNotion(self):
     row = cv.collection.add_row()
     row.title = self.title
     row.url = self.url
     self._setTag(row, 'prop', self.tags)
     row.added_on = NotionDate(datetime.fromtimestamp(self.addedOn))
     row.read = self.readStatus
Exemplo n.º 17
0
def addTodoEntry(name, dueDate=False, desc=False):
    if "TG2N_NOTION_TOKEN" not in os.environ:
        return
    client = NotionClient(token_v2=os.environ['TG2N_NOTION_TOKEN'],
                          start_monitoring=False)

    if "TG2N_NOTION_CV_LINK" not in os.environ:
        return
    cv = client.get_collection_view(os.environ['TG2N_NOTION_CV_LINK'])

    row = cv.collection.add_row()
    row.todo = name

    if dueDate:
        if " " in dueDate:
            dueDate = datetime.datetime.strptime(dueDate, '%Y%m%d %H%M')
        else:
            dueDate = datetime.datetime.strptime(dueDate, '%Y%m%d')

        tz = "Europe/Berlin"
        if "TG2N_TIMEZONE" in os.environ:
            tz = os.environ['TG2N_TIMEZONE']
        row.reminder = NotionDate(dueDate, None,
                                  timezone(os.environ['TG2N_TIMEZONE']))

    if desc:
        todoEntryPageId = row.id
        todoEntryPage = client.get_block(todoEntryPageId)
        child = todoEntryPage.children.add_new(TextBlock, title=desc)
Exemplo n.º 18
0
 def update_topic_date(self, topic):
     print("Updating topic date...")
     time_now = self.config.nowGMT8()
     topic.Revised = NotionDate(start=time_now,
                                end=None,
                                timezone=self.config.localTZ())
     return
Exemplo n.º 19
0
 def _task_to_row(task: TaskModel, row):
     row.title = task.title
     row.description = task.description
     row.priority = None if task.priority is None else task.priority.value
     row.due_date = NotionDate(task.due_date)
     row.done = task.isDone
     task.id = row.id
     row.refresh()
Exemplo n.º 20
0
 def addToNotion(self, lastClip):
     titleExists = False
     clipExists = False
     global cv
     allRows = cv.collection.get_rows()
     if allRows != []:
         for eachRow in allRows:
             if lastClip['Title'] == eachRow.title:
                 titleExists = True
                 row = eachRow
     if not titleExists:
         row = cv.collection.add_row()
         row.title = lastClip['Title']
         row.author = lastClip['Author']
         row.highlights = 0
     parentPage = client.get_block(row.id)
     allClippings = parentPage.children.filter(QuoteBlock)
     for eachClip in allClippings:
         if lastClip['Clipping'].strip() == eachClip.title:
             clipExists = True
     if clipExists == False:
         if lastClip['Location'] != None:
             if lastClip['Page'] != None:
                 parentPage.children.add_new(
                     TextBlock,
                     title="Page: " + lastClip['Page'] + "\tLocation: " +
                     lastClip['Location'] + "\tDate Added: " +
                     str(lastClip['Date Added'].strftime(
                         "%A, %d %B %Y %I:%M:%S %p")))
             else:
                 parentPage.children.add_new(
                     TextBlock,
                     title="Location: " + lastClip['Location'] +
                     "\tDate Added: " + str(lastClip['Date Added'].strftime(
                         "%A, %d %B %Y %I:%M:%S %p")))
         else:
             parentPage.children.add_new(
                 TextBlock,
                 title="Page: " + lastClip['Page'] + "\tDate Added: " +
                 str(lastClip['Date Added'].strftime(
                     "%A, %d %B %Y %I:%M:%S %p")))
         parentPage.children.add_new(QuoteBlock, title=lastClip['Clipping'])
         row.highlights += 1
         row.last_highlighted = NotionDate(lastClip['Date Added'])
         row.last_synced = NotionDate(datetime.now())
Exemplo n.º 21
0
    def __update_next_due(row):
        interval = int(row.Interval)
        last_start = row.Scheduled.start
        today = datetime.today().date()
        start_to_now_days = (today - last_start).days
        next_day = last_start + timedelta(days=ceil(start_to_now_days / interval) * interval)

        row.Scheduled = NotionDate(start=next_day)
        row.Done = False
Exemplo n.º 22
0
 def get_rtime(self, top, qs):
     print("Getting revised time list...")
     rtime_list = []
     for q in qs:
         timeNow = self.config.nowGMT8()
         time = NotionDate(start=timeNow,
                           end=None,
                           timezone=self.config.localTZ())
         rtime_list.append(time)
     return rtime_list
Exemplo n.º 23
0
 def set_page_info(page=None):
     if page is None:
         self.npage.set("format.page_icon", self.author.avatar)
         self.npage.title = self.author.name
         self.npage.nedelia = NotionDate(
             start=self.author.first_tweet.date.date(),
             end=self.author.last_tweet.date.date(),
         )
     else:
         page.set("format.page_icon", "🔥")
         page.title = f"{LOCALE.thread} ({self.author.name})"
def create_cohort_date(course_type):
    # applies a start and end date to new row in Cohort database
    start = create_date()
    days = None
    if course_type == 'Full Time':
        days = 91
    elif course_type == 'Part Time':
        days = 98
    end = start + timedelta(days=days)
    date = NotionDate(start, end=end)
    return date
Exemplo n.º 25
0
def log_result(cv, rows, traceback, start_datetime, finish_datetime, timezone):
    title = gethostname()
    finded_row = None
    for row in rows:
        if row.traceback is None or row.traceback == '':
            row.remove()
        if row.title == title:
            finded_row = row
    if finded_row is None:
        finded_row = cv.collection.add_row(title=title)
    finded_row.date = NotionDate(start_datetime, finish_datetime, timezone)
    finded_row.traceback = traceback
Exemplo n.º 26
0
def addToNotion():
    index = 0
    for index, eachItem in enumerate(allPocketListItems):
        if itemAlreadyExists(eachItem):
            continue
        index += 1
        row = cv.collection.add_row()
        row.title = eachItem.title
        row.url = eachItem.url
        setTag(row, cv, 'prop', eachItem.tags)
        row.added_on = NotionDate(datetime.fromtimestamp(eachItem.addedOn))
        row.read = eachItem.readStatus
    print(f"{index}/{len(allPocketListItems)} added")
Exemplo n.º 27
0
def updateLastSeen(reference, row=None):
    if row is None:
        row = getRowByReference(reference)

    if row:
        tz = pytz.timezone('America/New_York')
        east_now = datetime.now(tz)
        dd = NotionDate(east_now, None, "America/New_York")
        row.last_seen = dd
        return row
    else:
        print("Failed to find reference " + reference)
        return None
 def create_task(self, task):
     title = task['title']
     due_date = task['due_date'] if 'due_date' in task else None
     logging.info("Creating task in notion. Summary: %s - Due date: %s",
                  title, due_date)
     self.page.collection.parent.views
     newrow = self.page.collection.add_row()
     newrow.title = title
     if due_date:
         start_date = due_date.strftime("%Y-%m-%d")
         notionDate = NotionDate.from_notion({"start_date": start_date})
         newrow.due_date = notionDate
     return newrow
Exemplo n.º 29
0
    def _addMissingClippingsToRow(self, clippings):
        global allRows

        for row in allRows:
            if row.title in self.clippings.keys():
                partialAddClip = functools.partial(self._addClipToRow, row)
                with concurrent.futures.ThreadPoolExecutor() as executor:
                    updated = list(
                        executor.map(partialAddClip,
                                     self.clippings[row.title]))
                    if True in updated:
                        row.last_synced = NotionDate(datetime.now())
                    print('Finished updating', row.title)
Exemplo n.º 30
0
    def update_notion_item(manager: syncManager, item: task, updates: list):

        notion_item = manager.tasks.collection.get_rows(
            search=item.notion_task_id)[0]

        if "content" in updates:
            notion_item.title = item.content
        if "due" in updates:
            # get due date
            if item.due is not None:
                due = NotionDate(
                    start=datetime.strptime(item.due, "%Y-%m-%d").date())
            else:
                due = None
            notion_item.due = due
        if "label_ids" in updates:

            # loop through each label column and add which labels apply
            for relevant_column, column_type in manager.config[
                    "Label column name"].items():

                if column_type == "select":
                    labels = ""
                else:
                    labels = []

                for label_id in item.label_ids:
                    label_row = manager.labels.collection.get_rows(
                        search=str(label_id))[0]
                    label_column = label_row.relevant_column
                    label_name = label_row.notion_label
                    if label_column == relevant_column:
                        if column_type == "select":
                            labels = label_name
                        else:
                            labels.append(label_name)

                notion_item.set_property(relevant_column, labels)

        if "project_id" in updates:
            project = [
                manager.projects.collection.get_rows(
                    search=str(item.project_id))[0]
            ]
            notion_item.project = project
            # set group if necessary
            if manager.use_groups:
                notion_item.group = list(project.group)

        if "done" in updates:
            labelManager.set_notion_done_label(manager, item)