Skip to content

Commit

Permalink
support profile select
Browse files Browse the repository at this point in the history
  • Loading branch information
xeric committed Feb 27, 2019
1 parent 4eca919 commit b548dff
Show file tree
Hide file tree
Showing 5 changed files with 145 additions and 110 deletions.
18 changes: 18 additions & 0 deletions conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ def handle(query):
if query == KEY_FOLDER:
hasOption = True
prepareFolders()
elif query == KEY_PROFILE:
hasOption = True
prepareProfile()
else:
hasOption = True
option = key + ' ' + ALL_VALS[i]
Expand Down Expand Up @@ -111,6 +114,21 @@ def prepareFolders():

cur.close()

def prepareProfile():
homePath = os.environ['HOME']

parent = homePath + OUTLOOK_DATA_PARENT
profiles = os.listdir(parent)
for profile in profiles:
if not profile.startswith('.'):
wf.add_item(
title=unicode(profile),
subtitle='Set profile as: ' + unicode(profile),
valid=True,
uid='profile ' + str(profile),
arg='profile ' + str(profile),
)

if __name__ == '__main__':
wf = Workflow()
log = wf.logger
Expand Down
15 changes: 10 additions & 5 deletions consts.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
#coding:utf-8
PAGE_SIZE = 20
OUTLOOK_DATA_PATH = r'/Library/Group Containers/UBF8T346G9.Office/Outlook/Outlook 15 Profiles/Main Profile/Data/'
# OUTLOOK_DATA_PATH = r'/Library/Group Containers/UBF8T346G9.Office/Outlook/Outlook 15 Profiles/Main Profile/Data/'
OUTLOOK_DATA_PARENT = r'/Library/Group Containers/UBF8T346G9.Office/Outlook/Outlook 15 Profiles/'
OUTLOOK_DEFAULT_PROFILE = r'Main Profile'
OUTLOOK_DATA_FOLDER = r'/Data/'
OUTLOOK_SQLITE_FILE = r'Outlook.sqlite'

KEY_PAGE_SIZE = 'pagesize'
KEY_FOLDER = 'folder'
ALL_KEYS = [KEY_PAGE_SIZE, KEY_FOLDER]
ALL_KEY_DESCS = ['one page result size', 'search folder']
ALL_VALS = ['[number]', '[folder name]']
KEY_PROFILE = 'profile'
ALL_KEYS = [KEY_PAGE_SIZE, KEY_FOLDER, KEY_PROFILE]
ALL_KEY_DESCS = ['one page result size', 'search folder', 'outlook profile']
ALL_VALS = ['[number]', '[folder name]', '[profile name]']

RULES = [r'pagesize \d+', r'folder \d+']
RULES = [r'(pagesize)\s+(\d+)', r'(folder)\s+(\d+)', r'(profile)\s+([\w\s_]+)']
4 changes: 2 additions & 2 deletions info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ python conf.py "$query"</string>
<key>scriptfile</key>
<string></string>
<key>subtext</key>
<string>pagesize, folder ...</string>
<string>pagesize, folder, profile ...</string>
<key>title</key>
<string>Configre Outlook Search</string>
<key>type</key>
Expand Down Expand Up @@ -496,7 +496,7 @@ Mail content search is based on preview content, not full text of mail, so will
</dict>
</dict>
<key>version</key>
<string>0.1.0</string>
<string>0.1.1</string>
<key>webaddress</key>
<string>https://github.com/xeric/alfred-outlook</string>
</dict>
Expand Down
200 changes: 106 additions & 94 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,112 +41,121 @@ def handle(wf, query):
subtitle='too less characters will lead huge irrelevant results',
arg='',
uid=str(random.random()),
valid=True
valid=False
)
else:
homePath = os.environ['HOME']

profile = wf.stored_data(KEY_PROFILE) or OUTLOOK_DEFAULT_PROFILE

# outlookData = homePath + '/outlook/'
outlookData = homePath + r'/Library/Group Containers/UBF8T346G9.Office/Outlook/Outlook 15 Profiles/Main Profile/Data/'
outlookData = homePath + OUTLOOK_DATA_PARENT + profile + OUTLOOK_DATA_FOLDER
log.info(outlookData)

# processing query
page = 0
if isAlfredV2(wf):
m = re.search(r'\|(\d+)$', query)
page = 0 if m is None else int(m.group(1))
else:
page = os.getenv('page')
page = 0 if page is None else int(page)
if page:
query = query.replace('|' + str(page), '')
log.info("query string is: " + query)
log.info("query page is: " + str(page))

searchType = 'All'

if query.startswith('from:'):
searchType = 'From'
query = query.replace('from:', '')
elif query.startswith('title:'):
searchType = 'Title'
query = query.replace('title:', '')

if query is None or query == '':
wf.add_item(title='Type keywords to search mail ' + searchType + '...',
subtitle='too less characters will lead huge irrelevant results',
arg='',
uid=str(random.random()),
valid=True)
else:
keywords = query.split(' ')

configuredPageSize = wf.stored_data('pagesize')
calculatedPageSize = (int(configuredPageSize) if configuredPageSize else PAGE_SIZE)
offset = int(page) * calculatedPageSize
configuredFolder = wf.stored_data('folder')
folder = (int(configuredFolder) if configuredFolder else 0)

# start = time()
con = sqlite3.connect(outlookData + 'Outlook.sqlite')
cur = con.cursor()

searchMethod = getattr(sys.modules[__name__], 'query' + searchType)
searchMethod(cur, keywords, offset, calculatedPageSize + 1, folder)

resultCount = cur.rowcount
log.info("got " + str(resultCount) + " results found")

if resultCount:
count = 0

for row in cur:
count += 1
if calculatedPageSize > count:
log.info(row[0])
path = outlookData + row[3]
if row[2]:
content = wf.decode(row[2] or "")
content = re.sub('[\r\n]+', ' ', content)
else:
content = "no content preview"
wf.add_item(title=wf.decode(row[0] or ""),
subtitle=wf.decode('[' + wf.decode(row[1] or "") + '] ' + wf.decode(content or "")),
valid=True,
uid=str(row[4]),
arg=path,
type='file')
page += 1
if count > calculatedPageSize:
queryByVersion = query if not isAlfredV2(wf) else query + '|' + str(page)
it = wf.add_item(title='More Results Available...',
subtitle='click to retrieve next ' + str(calculatedPageSize) + ' results',
arg=queryByVersion,
uid='z' + str(random.random()),
valid=True)
if not isAlfredV2(wf):
it.setvar('page', page)
subtitle = ('no previous page', 'click to retrieve previous ' + str(calculatedPageSize) + ' results')[page > 1]
previousPage = 0 if page - 2 < 0 else page - 2
mod = it.add_modifier(key='ctrl',
subtitle=subtitle,
arg=queryByVersion,
valid=True)
if page > 1:
mod.setvar('page', previousPage)
else:
if page > 1:
previousPage = 0 if page - 2 < 0 else page - 2
queryByVersion = query if not isAlfredV2(wf) else query + '|' + str(previousPage)
it = wf.add_item(title='No More Results',
subtitle='click to retrieve previous ' + str(calculatedPageSize) + ' results',
if not validateProfile(outlookData):
wf.add_item(title='Profile: ' + profile + ' is not valid...',
subtitle='please use olkc profile to switch profile',
arg='olkc profile ',
uid='err' + str(random.random()),
valid=False)
else :
# processing query
page = 0
if isAlfredV2(wf):
m = re.search(r'\|(\d+)$', query)
page = 0 if m is None else int(m.group(1))
else:
page = os.getenv('page')
page = 0 if page is None else int(page)
if page:
query = query.replace('|' + str(page), '')
log.info("query string is: " + query)
log.info("query page is: " + str(page))

searchType = 'All'

if query.startswith('from:'):
searchType = 'From'
query = query.replace('from:', '')
elif query.startswith('title:'):
searchType = 'Title'
query = query.replace('title:', '')

if query is None or query == '':
wf.add_item(title='Type keywords to search mail ' + searchType + '...',
subtitle='too less characters will lead huge irrelevant results',
arg='',
uid=str(random.random()),
valid=True)
else:
keywords = query.split(' ')

configuredPageSize = wf.stored_data('pagesize')
calculatedPageSize = (int(configuredPageSize) if configuredPageSize else PAGE_SIZE)
offset = int(page) * calculatedPageSize
configuredFolder = wf.stored_data('folder')
folder = (int(configuredFolder) if configuredFolder else 0)

# start = time()
con = sqlite3.connect(outlookData + OUTLOOK_SQLITE_FILE)
cur = con.cursor()

searchMethod = getattr(sys.modules[__name__], 'query' + searchType)
searchMethod(cur, keywords, offset, calculatedPageSize + 1, folder)

resultCount = cur.rowcount
log.info("got " + str(resultCount) + " results found")

if resultCount:
count = 0

for row in cur:
count += 1
if calculatedPageSize > count:
log.info(row[0])
path = outlookData + row[3]
if row[2]:
content = wf.decode(row[2] or "")
content = re.sub('[\r\n]+', ' ', content)
else:
content = "no content preview"
wf.add_item(title=wf.decode(row[0] or ""),
subtitle=wf.decode('[' + wf.decode(row[1] or "") + '] ' + wf.decode(content or "")),
valid=True,
uid=str(row[4]),
arg=path,
type='file')
page += 1
if count > calculatedPageSize:
queryByVersion = query if not isAlfredV2(wf) else query + '|' + str(page)
it = wf.add_item(title='More Results Available...',
subtitle='click to retrieve next ' + str(calculatedPageSize) + ' results',
arg=queryByVersion,
uid='z' + str(random.random()),
valid=True)
if not isAlfredV2(wf):
it.setvar('page', previousPage)
it.setvar('page', page)
subtitle = ('no previous page', 'click to retrieve previous ' + str(calculatedPageSize) + ' results')[page > 1]
previousPage = 0 if page - 2 < 0 else page - 2
mod = it.add_modifier(key='ctrl',
subtitle=subtitle,
arg=queryByVersion,
valid=True)
if page > 1:
mod.setvar('page', previousPage)
else:
if page > 1:
previousPage = 0 if page - 2 < 0 else page - 2
queryByVersion = query if not isAlfredV2(wf) else query + '|' + str(previousPage)
it = wf.add_item(title='No More Results',
subtitle='click to retrieve previous ' + str(calculatedPageSize) + ' results',
arg=queryByVersion,
uid='z' + str(random.random()),
valid=True)
if not isAlfredV2(wf):
it.setvar('page', previousPage)

cur.close()
cur.close()
wf.send_feedback()


Expand Down Expand Up @@ -260,6 +269,9 @@ def queryAll(cur, keywords, offset, pageSize, folder):
def isAlfredV2(wf):
return wf.alfred_env['version'][0] == 2

def validateProfile(path):
return os.path.isfile(path + OUTLOOK_SQLITE_FILE)

if __name__ == '__main__':
wf = Workflow(update_settings={
'github_slug': GITHUB_SLUG,
Expand Down
18 changes: 9 additions & 9 deletions setconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,22 @@ def handle(query):
query = unicode(query, 'utf-8')

validQuery = False
key = None
val = None
for rule in RULES:
if re.match(rule, query) is not None:
m = re.match(rule, query)
if m is not None:
validQuery = True
key = m.group(1)
val = m.group(2)
break
if not validQuery:
notify('Error', query + ' is not a valid configuration!')
return

query.replace(r'\s+', ' ')
kvPair = query.split(' ')

key = kvPair[0]
val = kvPair[1]

wf.store_data(key, val)
notify('Set Configuration Successfully', 'Set ' + key + " to " + val + " complete!")
if key is not None:
wf.store_data(key, val)
notify('Set Configuration Successfully', 'Set ' + key + " to " + val + " complete!")

if __name__ == '__main__':
wf = Workflow()
Expand Down

0 comments on commit b548dff

Please sign in to comment.