-
Notifications
You must be signed in to change notification settings - Fork 1
/
search.py
204 lines (159 loc) · 4.71 KB
/
search.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
from kippt.kippt import Kippt
import alp
import os
import sqlite3 as lite
import utils
##
# Constants
##
SETTINGS_FILE = "settings.plist"
SETTINGS_PATH = os.path.join(alp.local(), SETTINGS_FILE)
DEFAULT_SETTINGS = dict(
username="",
sqliteDB="kippt.sqlite",
lastUpdate="",
updateClips="false",
firstRun="true",
credentialsChanged="false",
passwordSet="false"
)
# Global settings object
settings = None
def createSettingsFile():
"""
Creates the default settings file, if it doesn't exists.
"""
# Check if the settings file exists
try:
with open(SETTINGS_PATH):
pass
except IOError:
# No, settings file. Create the file and load the default settings.
file = open(SETTINGS_PATH, 'w+')
file.close()
alp.writePlist(DEFAULT_SETTINGS, SETTINGS_PATH)
def createDatabase():
"""
Creates an empty database.
"""
global settings
conn = lite.connect(settings["sqliteDB"])
with conn:
cur = conn.cursor()
cur.execute("CREATE TABLE Clips(Id INTEGER PRIMARY KEY, Title TEXT, Subtitle TEXT, Url TEXT, AppUrl TEXT, Notes TEXT)")
def udpateDatabaseFromKippt():
"""
Update the SQlite database with all clips from Kippt.
"""
global settings
# Check if database exists; if not, create it.
if not os.path.exists(os.path.join(alp.local(), settings["sqliteDB"])):
createDatabase()
clips = readAllClips()
if clips == None:
return
conn = lite.connect(settings["sqliteDB"])
with conn:
cur = conn.cursor()
# Remove old clips
cur.execute("DELETE FROM Clips")
# Add all clips
for clip in clips:
title = clip["title"]
subtitle = clip["title"]
url = clip["url"]
app_url = clip["app_url"]
notes = clip["notes"]
sql = "INSERT INTO Clips VALUES(NULL,"
sql += "\"%s\"," % title
sql += "\"%s\"," % subtitle
sql += "\"%s\"," % url
sql += "\"%s\"," % app_url
sql += "\"%s\"" % notes
sql += ")"
cur.execute(sql)
def readAllClips():
"""
Reads all clips from Kippt.
"""
global settings
k = Kippt(settings["username"], password=utils.getKeyChainPassword())
clips = k.clips().all()
# First, read the total count of clips
count = clips["meta"]["total_count"]
# Now, get all clips
clips = k.clips().all(limit=count)
return clips["objects"]
def search(keywords):
"""
Performs a search with the given keywords in the database. Returns the found clips
as Alfred Items (XML).
"""
global settings
if len(keywords) < 1:
return None
conn = lite.connect(settings["sqliteDB"])
titles = []
urls = []
notes = []
for word in keywords:
titles.append("Title LIKE \"%%%s%%\"" % word)
urls.append("Url LIKE \"%%%s%%\"" % word)
notes.append("Notes LIKE \"%%%s%%\"" % word)
titles = " AND ".join(titles)
urls = " AND ".join(urls)
notes = " AND ".join(notes)
sql = "SELECT Title, Subtitle, Url, AppUrl"
sql += " FROM Clips"
sql += " WHERE (%s) OR" % titles
sql += " (%s) OR " % urls
sql += " (%s)" % notes
alfredItems = []
with conn:
cur = conn.cursor()
cur.execute(sql)
rows = cur.fetchall()
for row in rows:
itemDict = dict(title=row[0],
subtitle=row[1],
arg=row[2],
valid=True)
item = alp.Item(**itemDict)
alfredItems.append(item)
return alfredItems
def main():
"""
Everything dispatches from this function.
"""
global settings
# Create default settings if necessary
createSettingsFile()
# Read settings
settings = alp.readPlist(SETTINGS_PATH)
# Process the settings
if settings["firstRun"] == "true":
udpateDatabaseFromKippt()
settings["firstRun"] = "false"
settings["credentialsChanged"] = "false"
alp.writePlist(settings, SETTINGS_PATH)
elif settings["credentialsChanged"] == "true":
udpateDatabaseFromKippt()
settings["credentialsChanged"] = "false"
alp.writePlist(settings, SETTINGS_PATH)
elif settings["updateClips"] == "true":
udpateDatabaseFromKippt()
settings["updateClips"] = "false"
alp.writePlist(settings, SETTINGS_PATH)
# Get the keywords
args = alp.args()
if len(args) < 1:
return
# Execute the search
items = search(args)
if items is not None:
alp.feedback(items)
else:
print "No items found"
if __name__ == '__main__':
# Let's start!
main()