-
Notifications
You must be signed in to change notification settings - Fork 4
/
joplin2sql.py
executable file
·332 lines (273 loc) · 10.9 KB
/
joplin2sql.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import re
import os
import argparse
import sys
import errno
import optparse
import sqlite3
import uuid
import email
import email.utils
from email.message import EmailMessage
from email.parser import BytesParser, Parser
from email.policy import default
from datetime import datetime
import hashlib
import shutil
import notesdb
import constants
import common
#
# MIT License
#
# https://opensource.org/licenses/MIT
#
# Copyright 2020 Rene Sugar
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Description:
#
# This program loads exported Joplin notes into a SQLite database.
#
global __name__, __author__, __email__, __version__, __license__
__program_name__ = 'joplin2sql'
__author__ = 'Rene Sugar'
__email__ = '[email protected]'
__version__ = '1.00'
__license__ = 'MIT License (https://opensource.org/licenses/MIT)'
__website__ = 'https://github.com/renesugar'
__db_schema_version__ = '1'
__db_schema_min_version__ = '1'
def _get_option_parser():
parser = optparse.OptionParser('%prog [options]',
version='%prog ' + __version__)
parser.add_option('', "--email",
action="store", dest="email_address", default=None,
help="Email address")
parser.add_option("", "--input",
action="store", dest="input_path", default=[],
help="Path to input iCloud notes archive")
parser.add_option('', "--output",
action="store", dest="output_path", default=None,
help="Path to output SQLite directory")
return parser
def process_joplin_note(sqlconn, resources_path, columns):
note_title = columns['note_title']
# note_title
if columns["note_title"] is None:
note_title = constants.NOTES_UNTITLED
else:
note_title = common.remove_line_breakers(columns["note_title"]).strip()
print("processing '%s'" % (note_title,))
# note_original_format (email, apple, icloud, joplin, bookmark)
note_original_format = "joplin"
# note_internal_date
note_internal_date = columns['note_internal_date']
# note_url
note_url = columns['note_url']
# note_data
note_data = columns['note_data']
if note_data is None:
note_data = ''
# note_data_format
note_data_format = 'text/markdown'
# note_hash (hash the markdown text)
h = hashlib.sha512()
h.update(note_data.encode('utf-8'))
note_hash = h.hexdigest()
# apple_id
apple_id = None
# apple_title
apple_title = note_title
# apple_snippet
apple_snippet = note_title
# apple_folder
apple_folder = columns['apple_folder']
if apple_folder is None:
apple_folder = constants.NOTES_FOLDER_NAME
# apple_created
apple_created = note_internal_date.strftime("%Y-%m-%d %H:%M:%S.%f")
# apple_last_modified
apple_last_modified = apple_created
# apple_data
apple_data = note_data
# apple_attachment_id
apple_attachment_id = None
# apple_attachment_path
apple_attachment_path = None
# Get resource attachments
lines = note_data.split()
links = common.getResourceLinks(lines)
first_image = False
for url, filename, resource in links:
matches = common.getResourceFileName(resources_path, resource)
if len(matches) > 0:
filename = matches[0]
mime_type, mime_subtype = common.getFileMimeType(filename)
if mime_type != "image":
# pick first non-image attachment as the Apple note attachment
apple_attachment_id = common.format_univesally_unique_identifier(resource)
apple_attachment_path = os.path.join(resources_path, filename)
break
elif first_image == False:
first_image = True
# otherwise, pick first image attachment as the Apple note attachment
apple_attachment_id = common.format_univesally_unique_identifier(resource)
apple_attachment_path = os.path.join(resources_path, filename)
# apple_account_description
apple_account_description = None
# apple_account_identifier
apple_account_identifier = None
# apple_account_username
apple_account_username = None
# apple_version
apple_version = None
# apple_user
apple_user = None
# apple_source
apple_source = None
columns["note_original_format"] = note_original_format
columns["note_internal_date"] = note_internal_date
columns["note_hash"] = note_hash
columns["note_title"] = note_title
columns["note_data"] = note_data
columns["note_data_format"] = note_data_format
columns["note_url"] = note_url
columns["apple_id"] = apple_id
columns["apple_title"] = apple_title
columns["apple_snippet"] = apple_snippet
columns["apple_folder"] = apple_folder
columns["apple_created"] = apple_created
columns["apple_last_modified"] = apple_last_modified
columns["apple_data"] = apple_data
columns["apple_attachment_id"] = apple_attachment_id
columns["apple_attachment_path"] = apple_attachment_path
columns["apple_account_description"] = apple_account_description
columns["apple_account_identifier"] = apple_account_identifier
columns["apple_account_username"] = apple_account_username
columns["apple_version"] = apple_version
columns["apple_user"] = apple_user
columns["apple_source"] = apple_source
notesdb.add_joplin_note(sqlconn, columns)
sqlconn.commit()
def parse_joplin_note(filePath):
columns = {}
if os.path.isfile(filePath) == True and common.checkExtension(filePath, ['md']):
with open(filePath, 'r') as fp:
lines = fp.readlines()
end_of_props = 0
for i in reversed(range(0, len(lines))):
if lines[i] == '\n':
end_of_props = i
break
key, val = lines[i].split(':', 1)
columns['joplin_' + key] = val.strip()
# Add missing Joplin columns
for key in notesdb.joplinColumns:
if key not in columns:
columns[key] = None
# Convert column string values to SQLite types
joplin_column_types = dict(zip(notesdb.joplinColumns, notesdb.joplinColumnTypes))
for key in columns:
if joplin_column_types[key] == "INTEGER":
if columns[key] is None:
pass
else:
columns[key] = int(columns[key])
elif joplin_column_types[key] == "FLOAT":
if columns[key] is None:
pass
else:
columns[key] = float(columns[key])
else:
pass
columns["note_type"] = common.noteTypeFromJoplinType(columns['joplin_type_'])
columns["note_uuid"] = columns["joplin_id"]
columns["note_parent_uuid"] = columns["joplin_parent_id"]
columns["note_tag_uuid"] = columns["joplin_tag_id"]
columns["note_note_uuid"] = columns["joplin_note_id"]
columns["note_original_format"] = 'joplin'
columns["note_internal_date"] = common.parse_isoformat_datetime(columns['joplin_created_time'])
columns["note_hash"] = None
columns["note_title"] = common.defaultTitleFromBody(lines[0])
columns["note_url"] = columns["joplin_source_url"]
columns["note_data"] = ''.join(lines[0:end_of_props])
columns["note_data_format"] = 'text/markdown'
columns["apple_folder"] = None
return columns
def main(args):
parser = _get_option_parser()
(options, args) = parser.parse_args(args)
email_address = ''
if hasattr(options, 'email_address') and options.email_address:
email_address = options.email_address
if common.check_email_address(email_address) == False:
# Check if email address is valid
common.error("email address '%s' is not valid." % (email_address,))
else:
common.error("email address not specified.")
inputPath = ''
if hasattr(options, 'input_path') and options.input_path:
inputPath = os.path.abspath(os.path.expanduser(options.input_path))
if os.path.isdir(inputPath) == False:
# Check if input file exists
common.error("input path '%s' does not exist." % (inputPath,))
else:
common.error("input path not specified.")
outputPath = ''
if hasattr(options, 'output_path') and options.output_path:
outputPath = os.path.abspath(os.path.expanduser(options.output_path))
if os.path.isdir(outputPath) == False:
# Check if output directory exists
common.error("output path '%s' does not exist." % (outputPath,))
else:
common.error("output path not specified.")
inputResourcesPath = os.path.join(inputPath, 'resources')
outputResourcesPath = os.path.join(outputPath, 'resources')
notesdbfile = os.path.join(outputPath, 'notesdb.sqlite')
new_database = (not os.path.isfile(notesdbfile))
sqlconn = sqlite3.connect(notesdbfile,
detect_types=sqlite3.PARSE_DECLTYPES)
sqlcur = sqlconn.cursor()
if (new_database):
notesdb.create_database(sqlconn=sqlconn, db_schema_version=__db_schema_version__, email_address=options.email_address)
db_settings = notesdb.get_db_settings(sqlcur, __db_schema_version__)
notesdb.check_db_settings(db_settings, '%prog', __version__, __db_schema_min_version__, __db_schema_version__)
# Create SQLite resources directory
if not os.path.isdir(outputResourcesPath):
os.makedirs(outputResourcesPath)
# Copy resources from Joplin resources directory to SQLite resources directory
for filename in os.listdir(inputResourcesPath):
filePath = os.path.join(inputPath, filename)
if os.path.isfile(filePath) == True:
shutil.copy2(filePath, outputResourcesPath)
# Parse Joplin notes
for filename in os.listdir(inputPath):
filePath = os.path.join(inputPath, filename)
if os.path.isfile(filePath) == True and common.checkExtension(filename, ['md']):
columns = parse_joplin_note(filePath)
if int(columns['joplin_type_']) == constants.JoplinType.JOPLIN_TYPE_NOTE:
if ('joplin_parent_id' in columns) and (columns['joplin_parent_id'] is not None):
parentPath = os.path.join(inputPath, columns['joplin_parent_id'] + '.md')
parent_columns = parse_joplin_note(parentPath)
columns["apple_folder"] = parent_columns['note_title']
process_joplin_note(sqlconn, outputResourcesPath, columns)
if __name__ == "__main__":
main(sys.argv[1:])