export.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. #!/usr/bin/env python3
  2. import datetime
  3. import mimetypes
  4. import pathlib
  5. from typing import Dict, List, NamedTuple, Optional, Set, Tuple, Union, ValuesView, Any
  6. import click
  7. import click_config_file
  8. import frontmatter
  9. import gkeepapi
  10. from gkeepapi.node import NodeAudio, NodeDrawing, NodeImage
  11. from mdutils.mdutils import MdUtils
  12. from pathvalidate import sanitize_filename
  13. mimetypes.add_type("audio/3gpp", ".3gp")
  14. def login(
  15. user_email: str, password: Optional[str], token: Optional[str]
  16. ) -> gkeepapi.Keep:
  17. keep = gkeepapi.Keep()
  18. if token:
  19. try:
  20. click.echo("Logging in with token")
  21. keep.resume(user_email, token)
  22. print(keep.getMasterToken())
  23. return keep
  24. except gkeepapi.exception.LoginException as ex:
  25. raise click.BadParameter(f"Token login (resume) failed: {str(ex)}")
  26. if password:
  27. try:
  28. click.echo("Logging in with password")
  29. keep.login(user_email, password)
  30. print(keep.getMasterToken())
  31. return keep
  32. except gkeepapi.exception.LoginException as ex:
  33. raise click.BadParameter(f"Password login failed: {str(ex)}")
  34. raise click.BadParameter(f"Neither password nor token provided to login.")
  35. def all_note_media(
  36. note: gkeepapi._node.Note,
  37. ) -> List[Union[NodeImage, NodeDrawing, NodeAudio]]:
  38. """
  39. Returns a filtered list of only "media" blobs associate with the note.
  40. Currently NodeDrawing, NodeImage, and NodeMedia.
  41. There are other blob types, but they don't seem actionable as media.
  42. """
  43. return note.images + note.drawings + note.audio
  44. def download_media(
  45. keep: gkeepapi.Keep,
  46. note: gkeepapi._node.Note,
  47. mediapath: pathlib.Path,
  48. skip_existing: bool,
  49. ) -> Tuple[List[pathlib.Path], int]:
  50. note_media = all_note_media(note)
  51. if not note_media:
  52. return ([], 0)
  53. ret = []
  54. downloaded_media = 0
  55. for media in note_media:
  56. meta = media.blob.save()
  57. # ocr = meta["extracted_text"] # TODO save ocr as metadata? in markdown or image?
  58. if meta.get("type", "") == "DRAWING":
  59. extension = mimetypes.guess_extension(
  60. meta.get("drawingInfo", {})
  61. .get("snapshotData", {})
  62. .get("mimetype", "image/png")
  63. ) # All drawings seem to be pngs
  64. elif meta.get("type") == "IMAGE":
  65. extension = mimetypes.guess_extension(meta.get("mimetype", "image/jpeg"))
  66. # .jpe just feels weird, but it's my default in testing
  67. if extension == ".jpe":
  68. extension = ".jpg"
  69. else: # 'AUDIO'
  70. extension = mimetypes.guess_extension(meta.get("mimetype", "audio/3gpp"))
  71. # nest media files under folders named by the note's ID
  72. # this simplifies figuring out the note media files came from
  73. note_media_path = mediapath / note.id
  74. note_media_path.mkdir(exist_ok=True)
  75. media_file = (
  76. note_media_path / f"{sanitize_filename(media.id,max_len=135)}{extension}"
  77. )
  78. # checking size isn't perfect, and drawings don't have a size,
  79. # but it doesn't seem right to always re-download images that likely
  80. # haven't changed
  81. if (
  82. skip_existing
  83. and media_file.exists()
  84. and hasattr(media.blob, "byte_size")
  85. and media_file.stat().st_size == media.blob.byte_size
  86. ):
  87. click.echo(
  88. f"Media file f{media_file} exists and is same size as in Google Keep. Skipping."
  89. )
  90. else:
  91. print(f"Downloading media {meta.get('type')} {media.id} for note {note.id}")
  92. url = keep._media_api.get(media)
  93. media_data = keep._media_api._session.get(url)
  94. with media_file.open("wb") as f:
  95. f.write(media_data.content)
  96. downloaded_media += 1
  97. ret.append(media_file)
  98. return (ret, downloaded_media)
  99. def build_frontmatter(note: gkeepapi._node.Note, markdown: str) -> frontmatter.Post:
  100. metadata = {
  101. "google_keep_id": note.id,
  102. "title": note.title,
  103. "pinned": note.pinned,
  104. "trashed": note.trashed,
  105. "deleted": note.deleted,
  106. "color": note.color.name,
  107. "type": note.type.name,
  108. "parent_id": note.parent_id,
  109. "sort": note.sort,
  110. "url": note.url,
  111. "tags": [label.name for label in note.labels.all()],
  112. "timestamps": {
  113. "created": note.timestamps.created.timestamp(),
  114. "edited": note.timestamps.edited.timestamp(),
  115. "updated": note.timestamps.updated.timestamp(),
  116. },
  117. }
  118. # gkeepapi appears to be treating "0" as a timestamp rather than null. Sometimes the data structure does not have the key at all instead of 0.
  119. if note.timestamps.trashed and note.timestamps.trashed.year > 1970:
  120. metadata["timestamps"]["trashed"] = note.timestamps.trashed.timestamp()
  121. if note.timestamps.deleted and note.timestamps.deleted.year > 1970:
  122. metadata["timestamps"]["deleted"] = note.timestamps.deleted.timestamp()
  123. return frontmatter.Post(markdown, handler=None, **metadata)
  124. def build_markdown(note: gkeepapi._node.Note, images: List[pathlib.Path]) -> str:
  125. doc = MdUtils(
  126. ""
  127. ) # mdutils requires a string file name. Since we're not using it to write files, we can ignore that.
  128. doc.new_header(1, note.title)
  129. doc.new_header(2, "Note")
  130. text = note.text
  131. text = text.replace("☑ ", "- [X] ")
  132. text = text.replace("☐ ", "- [ ] ")
  133. doc.new_paragraph(text)
  134. if note.annotations.links:
  135. doc.new_line()
  136. doc.new_line()
  137. doc.new_header(2, "Links")
  138. doc.new_list(
  139. [
  140. doc.new_inline_link(link=link.url, text=link.title)
  141. for link in note.annotations.links
  142. ]
  143. )
  144. if images:
  145. doc.new_line()
  146. doc.new_header(2, "Attached Media")
  147. for image in images:
  148. doc.new_line(doc.new_inline_image("", image.name))
  149. return doc.file_data_text
  150. LocalMedia = NamedTuple(
  151. "LocalMedia",
  152. [
  153. ("path", pathlib.Path),
  154. ("google_keep_note_id", str),
  155. ("google_keep_media_id", str),
  156. ],
  157. )
  158. class LocalNote:
  159. def __init__(
  160. self,
  161. google_keep_id: str,
  162. path: Optional[pathlib.Path] = None,
  163. timestamp_updated: Optional[datetime.datetime] = None,
  164. local_media: Dict[str, LocalMedia] = None,
  165. ):
  166. self.google_keep_id = google_keep_id
  167. self.path = path
  168. self.timestamp_updated = timestamp_updated
  169. if not local_media:
  170. self.local_media: Dict[str, LocalMedia] = {}
  171. else:
  172. self.local_media = local_media
  173. def index_existing_files(directory: pathlib.Path) -> Dict[str, LocalNote]:
  174. """
  175. Scans the output folder looking for existing markdown files
  176. and media files and builds an index by google_keep_id of those files
  177. using the metadata in the markdown frontmatter and the filenames
  178. of the media files.
  179. """
  180. index: Dict[str, LocalNote] = {}
  181. keep_notes = 0
  182. unknown_notes = 0
  183. errors = 0
  184. media = 0
  185. for file in directory.rglob("*"):
  186. if not file.is_file():
  187. continue
  188. # markdown file
  189. if file.name.endswith(".md"):
  190. try:
  191. with open(file, "r") as f:
  192. fm = frontmatter.load(f)
  193. google_keep_id: str = fm.metadata.get("google_keep_id")
  194. if google_keep_id:
  195. if google_keep_id in index and index[google_keep_id].path:
  196. click.echo(
  197. f"Same Google Keep ID {google_keep_id} in multiple files:\n"
  198. f" {file}\n"
  199. f" {index[google_keep_id].path}\n"
  200. f"Only the last file will be updated."
  201. )
  202. keep_notes += 1
  203. index.setdefault(google_keep_id, LocalNote(google_keep_id))
  204. updated: datetime.datetime = datetime.datetime.fromtimestamp(
  205. fm.metadata.get("timestamps", {}).get("updated")
  206. )
  207. index[google_keep_id].timestamp_updated = updated
  208. index[google_keep_id].path = file
  209. else:
  210. unknown_notes += 1
  211. except IOError as ex:
  212. errors = 0
  213. click.echo(
  214. "Unable to open Markdown file [{os.path.join(root, file)}]. Skipping: {str(ex)}",
  215. err=True,
  216. )
  217. # media file
  218. else:
  219. media += 1
  220. google_keep_id = file.parent.name
  221. media_id = ".".join(file.name.split(".")[0:2])
  222. index.setdefault(google_keep_id, LocalNote(google_keep_id))
  223. index[google_keep_id].local_media[media_id] = LocalMedia(
  224. file, google_keep_id, media_id
  225. )
  226. click.echo(
  227. f"Indexed local files: {keep_notes} Google Keep notes, {unknown_notes} unknown markdown files, {media} media files, {errors} errors"
  228. )
  229. return index
  230. def try_rename_note(note: LocalNote, target_file: pathlib.Path) -> pathlib.Path:
  231. """
  232. Attempts to rename an existing note to the new canonical filename,
  233. but accepts failures to rename. Returns the path the note now exists
  234. in, either the old path or the new renamed path.
  235. """
  236. if not note.path:
  237. return target_file
  238. click.echo(f"Renaming [{note.path}] to [{target_file}]")
  239. try:
  240. note.path.rename(target_file)
  241. return target_file
  242. except Exception as ex:
  243. click.echo(f"Unable to rename note. Using existing name: %s" % ex, err=True)
  244. return note.path
  245. def build_note_unique_path(
  246. notepath: pathlib.Path,
  247. note: gkeepapi._node.Note,
  248. date_format: str,
  249. local_index: Dict[str, LocalNote],
  250. ) -> pathlib.Path:
  251. title = note.title.strip()
  252. if not len(title):
  253. title = "untitled"
  254. date_str = note.timestamps.created.strftime(date_format)
  255. filename = f'{sanitize_filename(f"{date_str} - " + title,max_len=135)}.md'
  256. target_path = notepath / filename
  257. local_note = local_index.get(note.id)
  258. local_path = local_note.path if local_note else None
  259. if local_path:
  260. # if the note filename matches the current filename for that note, then we're good
  261. if local_path == target_path:
  262. return local_path
  263. # if re-naming would result in having to de-dupe the target filename, keep the
  264. # exising filename - initial pass at fixing this just resulted in bouncing between
  265. # two different filenames each pass
  266. if target_path.exists():
  267. click.echo(
  268. f"Note {note.id} will not be renamed. Target file [{target_path}] exists."
  269. )
  270. return local_path
  271. # otherwise, if the file already exists avoid overwriting it
  272. # put the unique note ID and an incrementing index at the end of the filename
  273. dedupe_index = 1
  274. while target_path.exists():
  275. filename = f'{sanitize_filename(f"{date_str} - " + title,max_len=135)}.{note.id}.{dedupe_index}.md'
  276. target_path = notepath / filename
  277. dedupe_index += 1
  278. return target_path
  279. def delete_local_only_files(
  280. local_index: Dict[str, LocalNote],
  281. keep_notes: Dict[str, List[gkeepapi.node.Note]],
  282. delete_local: bool,
  283. ) -> Tuple[int, int]:
  284. """
  285. Checks the local index for any notes or media that exist only locally
  286. and were not returned in the Google Keep API call.
  287. """
  288. deleted_notes, deleted_media = 0, 0
  289. local_only_note_ids = set(local_index.keys()).difference(set(keep_notes.keys()))
  290. if local_only_note_ids:
  291. if not delete_local:
  292. click.echo(
  293. f"{len(local_only_note_ids)} notes exist locally, but not in Google Keep. Add argument [--delete-local] to delete."
  294. )
  295. else:
  296. click.echo(
  297. f"{len(local_only_note_ids)} notes exist locally, but not in Google Keep. Trashing local files."
  298. )
  299. for note_id in local_only_note_ids:
  300. note_path = local_index[note_id].path
  301. deleted_notes += 1
  302. if note_path:
  303. click.echo(
  304. f" Deleting unknown local note [{note_id}] file [{local_index[note_id].path}]"
  305. )
  306. note_path.unlink()
  307. local_only_media: Set[Tuple[str, str]] = set(
  308. [
  309. (local_media.google_keep_note_id, local_media.google_keep_media_id)
  310. for local_note in local_index.values()
  311. for local_media in local_note.local_media.values()
  312. if local_media.google_keep_note_id and local_media.google_keep_media_id
  313. ]
  314. )
  315. notes: ValuesView[gkeepapi._node.Note] = keep_notes.values()
  316. keep_media: Set[Tuple[str, str]] = set(
  317. [
  318. (keep_note.id, keep_media.id)
  319. for keep_note in notes
  320. for keep_media in all_note_media(keep_note)
  321. ]
  322. )
  323. local_only_media_ids = local_only_media.difference(keep_media)
  324. if not local_only_media_ids:
  325. return (deleted_notes, 0)
  326. if not delete_local:
  327. click.echo(
  328. f"{len(local_only_note_ids)} media files exist locally, but not in Google Keep. Add argument [--delete-local] to delete."
  329. )
  330. return (deleted_notes, 0)
  331. for (note_id, media_id) in local_only_media_ids:
  332. media = local_index[note_id].local_media[media_id]
  333. click.echo(
  334. f" Deleting media [{media_id}] for note [{note_id}] file [{media.path}]"
  335. )
  336. media.path.unlink()
  337. deleted_media += 1
  338. return (deleted_notes, deleted_media)