-
Notifications
You must be signed in to change notification settings - Fork 4
/
cleanres.py
executable file
·161 lines (130 loc) · 5.04 KB
/
cleanres.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
import re
import os
import argparse
import sys
import errno
import optparse
import sqlite3
import uuid
import mimetypes
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, timezone
#from pytz import timezone
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 removes unused files from the resources directory.
#
global __name__, __author__, __email__, __version__, __license__
__program_name__ = 'cleanres'
__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 filelist(dir):
allfiles = []
for path, subdirs, files in os.walk(dir):
files = [os.path.join(path,x) for x in files]
# "[:]" alters the list of subdirectories walked by os.walk
# https://stackoverflow.com/questions/10620737/efficiently-removing-subdirectories-in-dirnames-from-os-walk
subdirs[:] = [os.path.join(path,x) for x in subdirs]
allfiles.extend(files)
for x in subdirs:
allfiles.extend(filelist(x))
return allfiles
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 SQLite directory")
return parser
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 directory exists
common.error("input path '%s' does not exist." % (inputPath,))
else:
common.error("input path not specified.")
inputResourcesPath = os.path.join(inputPath, 'resources')
if os.path.isdir(inputResourcesPath) == False:
# Check if input resources directory exists
common.error("input resources path '%s' does not exist." % (inputResourcesPath,))
notesdbfile = os.path.join(inputPath, 'notesdb.sqlite')
new_database = (not os.path.isfile(notesdbfile))
sqlconn = sqlite3.connect(notesdbfile,
detect_types=sqlite3.PARSE_DECLTYPES)
sqlconn.row_factory = sqlite3.Row
sqlcur = sqlconn.cursor()
if (new_database):
common.error("database not found")
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__)
files = filelist(inputResourcesPath)
# Remove unused resource files
for filepath in files:
pathname, filename = os.path.split(filepath)
resource_id, file_extension = os.path.splitext(filename)
query = "SELECT note_id FROM notes WHERE apple_attachment_path LIKE '%" + resource_id
query += "%' OR note_data LIKE '%(:/" + resource_id + ")%';"
sqlcur.execute(query)
result = sqlcur.fetchone()
if result is None:
# delete file
print("deleting '%s'..." % (filepath,))
if os.path.isfile(filepath):
os.remove(filepath)
sqlconn.commit()
if __name__ == "__main__":
main(sys.argv[1:])