Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

import google takeout notes #4425

Closed
albert3595 opened this issue Feb 20, 2025 · 2 comments
Closed

import google takeout notes #4425

albert3595 opened this issue Feb 20, 2025 · 2 comments
Labels
bug Something isn't working

Comments

@albert3595
Copy link

albert3595 commented Feb 20, 2025

Describe the bug

i am trying to import a google takeout backup with a script. all notes get imported but i cant get the creation date right. its always the time i import the notes.

import os
import json
import requests
import glob
from datetime import datetime

# KONFIGURATION
MEMOS_API_URL = "http://localhost:5230/api/v1/memos"  # memo url
AUTH_TOKEN = "token"  # api token
TAKEOUT_FOLDER = "/home/Takeout/Google/"  # takeout folder


HEADERS = {
    "Authorization": f"Bearer {AUTH_TOKEN}",
    "Content-Type": "application/json"
}

def extract_data_from_json(json_file):
    """ Extracts note content and creation timestamp from a JSON file """
    try:
        with open(json_file, "r", encoding="utf-8") as f:
            data = json.load(f)

        text = data.get("textContent", "")
        timestamp_usec = data.get("createdTimestampUsec", None)
        if timestamp_usec:
            created_time = datetime.utcfromtimestamp(timestamp_usec / 1_000_000)
        else:
            created_time = None
            print(f"Warning: No 'createdTimestampUsec' in {json_file}")
        return text, created_time
    except Exception as e:
        print(f"Error processing {json_file}: {e}")
        return "", None

def upload_to_memos(text, created_time):
    """ Sends the note to Memos """
    if not text.strip():
        print("Skipping empty note.")
        return

    if created_time is None:
        print("Warning: No creation date found, using current date.")
        created_time = datetime.utcnow() # Or other fallback strategy

    payload = {
        "content": text,
        "createdTs": int(created_time.timestamp() * 1000)
    }

    print(f"Timestamp (milliseconds): {payload['createdTs']}")

    response = requests.post(MEMOS_API_URL, headers=HEADERS, json=payload)
    if response.status_code == 200:
        print(f"Note successfully uploaded: {text[:30]}...")
    else:
        print(f"Error uploading note: {response.text}")

def main():
    """ Scans the folder for notes and uploads them """
    files_processed = 0

    for json_file in glob.glob(os.path.join(TAKEOUT_FOLDER, "*.json")):
        text, created_time = extract_data_from_json(json_file)
        if text: # only if text is not empty
            upload_to_memos(text, created_time)
            files_processed += 1

    print(f"{files_processed} notes processed and uploaded!")

if __name__ == "__main__":
    main()

example of a .json from the takeout folder

{"color":"DEFAULT","isTrashed":false,"isPinned":false,"isArchived":false,"textContent":"Versand? Nur geschaeft?","title":"","userEditedTimestampUsec":1419963923783000,"createdTimestampUsec":1419963923751000,"textContentHtml":"<p dir=\"ltr\" style=\"line-height:1.38;margin-top:0.0pt;margin-bottom:0.0pt;\"><span style=\"font-size:16.0pt;font-family:'Google Sans';color:#000000;background-color:transparent;font-weight:400;font-style:normal;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;\">Versand? Nur geschaeft?<\/span><\/p>"}

Steps to reproduce

run the script, check memos, all notes uploaded but creation date is now

The version of Memos you're using

0.24.0

Screenshots or additional context

No response

@albert3595 albert3595 added the bug Something isn't working label Feb 20, 2025
@johnnyjoygh
Copy link
Collaborator

The creation time is automatically generated in the database, so it's not to specify the creation time currently. But you can modify the creation time by calling the UpdateMemo API after memo created.

@albert3595
Copy link
Author

thank you! for anyone interested, it can import text, and both the correct date and pinned status work now

import os
import requests
import json
from datetime import datetime

# Konfiguration
MEMOS_API_URL = "http://localhost:5230/api/v1/memos" #correct url to your memos
AUTH_TOKEN = "token" #memos api token
TAKEOUT_FOLDER = "/home/Takeout/Google/" #path to your backup

HEADERS = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {AUTH_TOKEN}"
}

# create notes from takeout files
def upload_takeout_notes():
    memo_ids = []
    for filename in os.listdir(TAKEOUT_FOLDER):
        if filename.endswith(".json"):
            filepath = os.path.join(TAKEOUT_FOLDER, filename)
            with open(filepath, "r", encoding="utf-8") as file:
                data = json.load(file)
                text = data.get("textContent", "").strip()
                timestamp_usec = data.get("createdTimestampUsec", 0)
                is_pinned = data.get("isPinned", False)  # Prüfe, ob die Notiz gepinnt ist
                
                if text and timestamp_usec:
                    data_payload = {"content": text, "visibility": "PRIVATE", "pinned": is_pinned}
                    response = requests.post(MEMOS_API_URL, headers=HEADERS, json=data_payload)
                    
                    if response.status_code == 200:
                        memo_id = response.json().get("name", "").replace("memos/", "")
                        memo_ids.append((memo_id, timestamp_usec, is_pinned))
                        print(f"Hochgeladen: {filename} (ID: {memo_id}, Pinned: {is_pinned})")
                    else:
                        print(f"Fehlgeschlagen: {filename}, Status: {response.status_code}, Antwort: {response.text}")
    return memo_ids

# update notes with correct date and pinned status
def update_memo_dates(memo_ids):
    for memo_id, timestamp_usec, is_pinned in memo_ids:
        iso_time = datetime.utcfromtimestamp(timestamp_usec / 1e6).isoformat() + "Z"
        update_url = f"{MEMOS_API_URL}/{memo_id}"
        data = {
            "name": f"memos/{memo_id}",
            "create_time": iso_time,
            "pinned": is_pinned
        }
        response = requests.patch(update_url, headers=HEADERS, json=data)
        print(f"Update {memo_id}: {response.status_code} - {response.text}")

# Hauptlogik
memo_ids = upload_takeout_notes()
if memo_ids:
    update_memo_dates(memo_ids)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants