├── .gitignore ├── Gutenberg-Book-Search-1.4.alfredworkflow ├── README.md ├── demo.gif └── src ├── books.py ├── books.tsv ├── catalogue_to_tsv.py ├── config.py ├── icon.png ├── index.py ├── info.plist └── workflow ├── .alfredversionchecked ├── Notify.tgz ├── __init__.py ├── background.py ├── notify.py ├── update.py ├── version ├── web.py ├── workflow.py └── workflow3.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/vim,python,sublimetext 2 | 3 | ### Python ### 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | .hypothesis/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | ### SublimeText ### 107 | # cache files for sublime text 108 | *.tmlanguage.cache 109 | *.tmPreferences.cache 110 | *.stTheme.cache 111 | 112 | # workspace files are user-specific 113 | *.sublime-workspace 114 | 115 | # project files should be checked into the repository, unless a significant 116 | # proportion of contributors will probably not be using SublimeText 117 | # *.sublime-project 118 | 119 | # sftp configuration file 120 | sftp-config.json 121 | 122 | # Package control specific files 123 | Package Control.last-run 124 | Package Control.ca-list 125 | Package Control.ca-bundle 126 | Package Control.system-ca-bundle 127 | Package Control.cache/ 128 | Package Control.ca-certs/ 129 | Package Control.merged-ca-bundle 130 | Package Control.user-ca-bundle 131 | oscrypto-ca-bundle.crt 132 | bh_unicode_properties.cache 133 | 134 | # Sublime-github package stores a github token in this file 135 | # https://packagecontrol.io/packages/sublime-github 136 | GitHub.sublime-settings 137 | 138 | ### Vim ### 139 | # swap 140 | [._]*.s[a-v][a-z] 141 | [._]*.sw[a-p] 142 | [._]s[a-v][a-z] 143 | [._]sw[a-p] 144 | # session 145 | Session.vim 146 | # temporary 147 | .netrwhist 148 | *~ 149 | # auto-generated tag files 150 | tags 151 | 152 | # End of https://www.gitignore.io/api/vim,python,sublimetext 153 | -------------------------------------------------------------------------------- /Gutenberg-Book-Search-1.4.alfredworkflow: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deanishe/alfred-index-demo/c3b479fe00f4bb53e78b78c21afcaddea086adba/Gutenberg-Book-Search-1.4.alfredworkflow -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Alfred/sqlite demo workflow 2 | =========================== 3 | 4 | Search the index of Project Gutenberg ebooks from Alfred. 5 | 6 | ![](https://github.com/deanishe/alfred-index-demo/raw/master/demo.gif "") 7 | 8 | Demonstrates the usage of sqlite full-text search in a workflow and the blinding speed this offers. 9 | 10 | Download 11 | -------- 12 | 13 | Grab the workflow from [GitHub releases][latest]. 14 | 15 | 16 | Usage 17 | ----- 18 | 19 | - `books ` — Search the Gutenberg catalogue for `` 20 | 21 | You can use wildcard, boolean and field-specific queries: 22 | 23 | - `books kant AND critique` 24 | - `books author:kant` 25 | - `books criti*` 26 | - `books title:criti* AND author:kant` 27 | 28 | 29 | How fast? 30 | --------- 31 | 32 | Here's some sample log output using [a database of ~45,000 ebooks](https://raw.githubusercontent.com/deanishe/alfred-index-demo/master/src/books.tsv) from [Project Gutenberg](http://www.gutenberg.org/): 33 | 34 | ``` 35 | 11:10:53 background.py:220 DEBUG Executing task `indexer` in background... 36 | 11:10:53 index.py:43 INFO Creating index database 37 | 11:10:53 index.py:56 INFO Updating index database 38 | 11:10:53 books.py:110 INFO 0 results for `im` in 0.001 seconds 39 | 11:10:53 books.py:110 INFO 0 results for `imm` in 0.001 seconds 40 | 11:10:53 books.py:110 INFO 0 results for `imma` in 0.001 seconds 41 | 11:10:55 index.py:73 INFO 44549 items added/updated in 2.19 seconds 42 | 11:10:55 books.py:110 INFO 0 results for `imman` in 1.710 seconds 43 | 11:10:55 index.py:80 INFO Index database update finished 44 | 11:10:55 background.py:270 DEBUG Task `indexer` finished 45 | 11:10:55 books.py:110 INFO 15 results for `immanuel` in 0.002 seconds 46 | 11:10:58 books.py:110 INFO 100 results for `p` in 0.017 seconds 47 | 11:10:59 books.py:110 INFO 4 results for `ph` in 0.002 seconds 48 | 11:10:59 books.py:110 INFO 0 results for `phi` in 0.002 seconds 49 | 11:11:00 books.py:110 INFO 9 results for `phil` in 0.002 seconds 50 | 11:11:00 books.py:110 INFO 3 results for `philo` in 0.002 seconds 51 | 11:11:00 books.py:110 INFO 0 results for `philos` in 0.001 seconds 52 | 11:11:00 books.py:110 INFO 0 results for `philosp` in 0.001 seconds 53 | 11:11:01 books.py:110 INFO 0 results for `philospo` in 0.001 seconds 54 | 11:11:01 books.py:110 INFO 0 results for `philosp` in 0.001 seconds 55 | 11:11:02 books.py:110 INFO 0 results for `philos` in 0.002 seconds 56 | 11:11:02 books.py:110 INFO 0 results for `philoso` in 0.001 seconds 57 | 11:11:02 books.py:110 INFO 0 results for `philosoh` in 0.003 seconds 58 | 11:11:02 books.py:110 INFO 0 results for `philosohp` in 0.002 seconds 59 | 11:11:02 books.py:110 INFO 0 results for `philosohpy` in 0.002 seconds 60 | 11:11:03 books.py:110 INFO 0 results for `philosohp` in 0.002 seconds 61 | 11:11:03 books.py:110 INFO 0 results for `philosoh` in 0.001 seconds 62 | 11:11:03 books.py:110 INFO 0 results for `philoso` in 0.001 seconds 63 | 11:11:03 books.py:110 INFO 0 results for `philosop` in 0.001 seconds 64 | 11:11:03 books.py:110 INFO 0 results for `philosopj` in 0.001 seconds 65 | 11:11:03 books.py:110 INFO 0 results for `philosopjy` in 0.002 seconds 66 | 11:11:04 books.py:110 INFO 0 results for `philosopj` in 0.002 seconds 67 | 11:11:04 books.py:110 INFO 0 results for `philosop` in 0.002 seconds 68 | 11:11:04 books.py:110 INFO 0 results for `philosoph` in 0.002 seconds 69 | 11:11:04 books.py:110 INFO 100 results for `philosophy` in 0.012 seconds 70 | 11:11:08 books.py:110 INFO 100 results for `philosophy ` in 0.007 seconds 71 | 11:11:09 books.py:110 INFO 2 results for `philosophy t` in 0.002 seconds 72 | 11:11:09 books.py:110 INFO 0 results for `philosophy ti` in 0.002 seconds 73 | 11:11:10 books.py:110 INFO 0 results for `philosophy tit` in 0.002 seconds 74 | 11:11:11 books.py:110 INFO 0 results for `philosophy titl` in 0.002 seconds 75 | 11:11:11 books.py:110 INFO 0 results for `philosophy title` in 0.002 seconds 76 | 11:11:11 books.py:110 INFO 100 results for `philosophy title:` in 0.007 seconds 77 | 11:11:11 books.py:110 INFO 0 results for `philosophy title:t` in 0.002 seconds 78 | 11:11:11 books.py:110 INFO 0 results for `philosophy title:th` in 0.002 seconds 79 | 11:11:11 books.py:110 INFO 72 results for `philosophy title:the` in 0.010 seconds 80 | 11:11:12 books.py:110 INFO 40 results for `philosophy a` in 0.006 seconds 81 | 11:11:13 books.py:110 INFO 0 results for `philosophy au` in 0.002 seconds 82 | 11:11:13 books.py:110 INFO 0 results for `philosophy aut` in 0.002 seconds 83 | 11:11:13 books.py:110 INFO 0 results for `philosophy auth` in 0.002 seconds 84 | 11:11:13 books.py:110 INFO 0 results for `philosophy autho` in 0.002 seconds 85 | 11:11:13 books.py:110 INFO 0 results for `philosophy author` in 0.002 seconds 86 | 11:11:14 books.py:110 INFO 100 results for `philosophy author:` in 0.009 seconds 87 | 11:11:14 books.py:110 INFO 0 results for `philosophy author:k` in 0.002 seconds 88 | 11:11:14 books.py:110 INFO 0 results for `philosophy author:ka` in 0.002 seconds 89 | 11:11:14 books.py:110 INFO 0 results for `philosophy author:kan` in 0.002 seconds 90 | 11:11:15 books.py:110 INFO 0 results for `philosophy author:kant` in 0.002 seconds 91 | 11:11:18 books.py:110 INFO 3 results for `philosophy author:a` in 0.003 seconds 92 | 11:11:18 books.py:110 INFO 0 results for `philosophy author:ar` in 0.002 seconds 93 | 11:11:19 books.py:110 INFO 0 results for `philosophy author:ari` in 0.002 seconds 94 | 11:11:19 books.py:110 INFO 0 results for `philosophy author:aris` in 0.002 seconds 95 | 11:11:20 books.py:110 INFO 0 results for `philosophy author:arist` in 0.002 seconds 96 | 11:11:20 books.py:110 INFO 0 results for `philosophy author:aristo` in 0.002 seconds 97 | 11:11:20 books.py:110 INFO 0 results for `philosophy author:aristot` in 0.002 seconds 98 | 11:11:20 books.py:110 INFO 0 results for `philosophy author:aristotl` in 0.002 seconds 99 | 11:11:20 books.py:110 INFO 0 results for `philosophy author:aristotle` in 0.002 seconds 100 | 11:11:22 books.py:110 INFO 15 results for `author:aristotle` in 0.002 seconds 101 | ``` 102 | 103 | [latest]: https://github.com/deanishe/alfred-index-demo/releases/latest 104 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deanishe/alfred-index-demo/c3b479fe00f4bb53e78b78c21afcaddea086adba/demo.gif -------------------------------------------------------------------------------- /src/books.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2014 deanishe@deanishe.net 5 | # 6 | # MIT Licence. See http://opensource.org/licenses/MIT 7 | # 8 | # Created on 2014-07-03 9 | # 10 | 11 | """Workflow Script Filter to show search results in Alfred.""" 12 | 13 | from __future__ import print_function, unicode_literals 14 | 15 | import sys 16 | import os 17 | import struct 18 | from time import time 19 | 20 | import sqlite3 21 | 22 | from workflow import Workflow, ICON_INFO, ICON_WARNING 23 | from workflow.background import run_in_background, is_running 24 | 25 | from config import INDEX_DB 26 | 27 | log = None 28 | 29 | 30 | # Search ranking function 31 | # Adapted from http://goo.gl/4QXj25 and http://goo.gl/fWg25i 32 | def make_rank_func(weights): 33 | """`weights` is a list or tuple of the relative ranking per column. 34 | 35 | Use floats (1.0 not 1) for more accurate results. Use 0 to ignore a 36 | column. 37 | """ 38 | def rank(matchinfo): 39 | # matchinfo is defined as returning 32-bit unsigned integers 40 | # in machine byte order 41 | # http://www.sqlite.org/fts3.html#matchinfo 42 | # and struct defaults to machine byte order 43 | bufsize = len(matchinfo) # Length in bytes. 44 | matchinfo = [struct.unpack(b'I', matchinfo[i:i + 4])[0] 45 | for i in range(0, bufsize, 4)] 46 | it = iter(matchinfo[2:]) 47 | return sum(x[0] * w / x[1] 48 | for x, w in zip(zip(it, it, it), weights) 49 | if x[1]) 50 | return rank 51 | 52 | 53 | def main(wf): 54 | # Workflow requires a query 55 | query = wf.args[0] 56 | 57 | index_exists = True 58 | 59 | # Create index if it doesn't exist 60 | if not os.path.exists(INDEX_DB): 61 | index_exists = False 62 | run_in_background('indexer', ['/usr/bin/python', 'index.py']) 63 | 64 | # Can't search without an index. Inform user and exit 65 | if not index_exists: 66 | wf.add_item('Creating search index…', 'Please wait a moment', 67 | icon=ICON_INFO) 68 | wf.send_feedback() 69 | return 70 | 71 | # Inform user of update in case they're looking for something 72 | # recently added (and it isn't there) 73 | if is_running('indexer'): 74 | wf.add_item('Updating search index…', 75 | 'Fresher results will be available shortly', 76 | icon=ICON_INFO) 77 | 78 | # Search! 79 | start = time() 80 | db = sqlite3.connect(INDEX_DB) 81 | # Set ranking function with weightings for each column. 82 | # `make_rank_function` must be called with a tuple/list of the same 83 | # length as the number of columns "selected" from the database. 84 | # In this case, `url` is set to 0 because we don't want to search on 85 | # that column 86 | db.create_function('rank', 1, make_rank_func((1.0, 1.0, 0))) 87 | cursor = db.cursor() 88 | try: 89 | cursor.execute("""SELECT author, title, url FROM 90 | (SELECT rank(matchinfo(books)) 91 | AS r, author, title, url 92 | FROM books WHERE books MATCH ?) 93 | ORDER BY r DESC LIMIT 100""", (query,)) 94 | results = cursor.fetchall() 95 | except sqlite3.OperationalError as err: 96 | # If the query is invalid, show an appropriate warning and exit 97 | if b'malformed MATCH' in err.message: 98 | wf.add_item('Invalid query', icon=ICON_WARNING) 99 | wf.send_feedback() 100 | return 101 | # Otherwise raise error for Workflow to catch and log 102 | else: 103 | raise err 104 | 105 | if not results: 106 | wf.add_item('No matches', 'Try a different query', icon=ICON_WARNING) 107 | 108 | log.info('{} results for `{}` in {:0.3f} seconds'.format( 109 | len(results), query, time() - start)) 110 | 111 | # Output results to Alfred 112 | for (author, title, url) in results: 113 | wf.add_item(title, author, valid=True, arg=url, icon='icon.png') 114 | 115 | wf.send_feedback() 116 | 117 | 118 | if __name__ == '__main__': 119 | wf = Workflow() 120 | log = wf.logger 121 | sys.exit(wf.run(main)) 122 | -------------------------------------------------------------------------------- /src/catalogue_to_tsv.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2014 deanishe@deanishe.net 5 | # 6 | # MIT Licence. See http://opensource.org/licenses/MIT 7 | # 8 | # Created on 2014-07-03 9 | # 10 | 11 | """Convert the Gutenberg RDF data dump to a TSV file. 12 | 13 | The script expects the data dump from 14 | http://www.gutenberg.org/wiki/Gutenberg:Feeds#The_Complete_Project_Gutenberg_Catalog 15 | to be extracted into the same directory (i.e. the `epub` directory is 16 | in the same directory as this script.) 17 | 18 | Usage: 19 | 20 | python catalogue_to_tsv.py > books.tsv 21 | """ 22 | 23 | from __future__ import print_function, unicode_literals 24 | 25 | import sys 26 | import os 27 | import csv 28 | from lxml import etree 29 | 30 | 31 | NS_DC = '{http://purl.org/dc/terms/}' 32 | NS_PG = '{http://www.gutenberg.org/2009/pgterms/}' 33 | NS_RDF = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}' 34 | 35 | resource_tag = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource' 36 | title_tag = '//{}title'.format(NS_DC) 37 | author_tag = '//{}creator/{}agent/{}name'.format(NS_DC, NS_PG, NS_PG) 38 | book_id_tag = '//{}isFormatOf'.format(NS_DC) 39 | book_id_attrib = '{}resource'.format(NS_RDF) 40 | 41 | 42 | def iter_books(dirpath): 43 | for root, dirnames, filenames in os.walk(dirpath): 44 | for filename in filenames: 45 | if filename.endswith('.rdf'): 46 | yield os.path.join(root, filename) 47 | 48 | 49 | def tidy(text): 50 | text = text.replace('\r', '') 51 | text = text.replace('\n', ' - ') 52 | return text 53 | 54 | 55 | def parse_book(path): 56 | data = {} 57 | tree = etree.parse(path) 58 | title = tree.findtext(title_tag) 59 | if not title: 60 | return None 61 | author = tree.findtext(author_tag) 62 | if not author: 63 | return None 64 | data['title'] = tidy(title) 65 | data['author'] = tidy(author) 66 | elems = tree.findall(book_id_tag) 67 | if not elems: 68 | return None 69 | id_ = elems[0].attrib[book_id_attrib] 70 | data['url'] = 'http://www.gutenberg.org/{}'.format(id_) 71 | data['id'] = id_.split('/')[1] 72 | return data 73 | 74 | 75 | def main(): 76 | writer = csv.writer(sys.stdout, delimiter=b'\t', quoting=csv.QUOTE_MINIMAL) 77 | count = 0 78 | for i, path in enumerate(iter_books('epub')): 79 | count += 1 80 | print(os.path.basename(path), file=sys.stderr) 81 | book = parse_book(path) 82 | if not book: 83 | continue 84 | i += 1 85 | for k, v in book.items(): 86 | book[k] = unicode(v).encode('utf-8') 87 | writer.writerow((book['id'], book['author'], 88 | book['title'], book['url'])) 89 | 90 | 91 | if __name__ == '__main__': 92 | main() 93 | -------------------------------------------------------------------------------- /src/config.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2014 deanishe@deanishe.net 5 | # 6 | # MIT Licence. See http://opensource.org/licenses/MIT 7 | # 8 | # Created on 2014-07-03 9 | # 10 | 11 | """Common settings.""" 12 | 13 | from __future__ import unicode_literals 14 | 15 | from workflow import Workflow 16 | 17 | wf = Workflow() 18 | 19 | INDEX_DB = wf.cachefile('index.db') 20 | DATA_FILE = wf.workflowfile('books.tsv') 21 | -------------------------------------------------------------------------------- /src/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deanishe/alfred-index-demo/c3b479fe00f4bb53e78b78c21afcaddea086adba/src/icon.png -------------------------------------------------------------------------------- /src/index.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2014 deanishe@deanishe.net 5 | # 6 | # MIT Licence. See http://opensource.org/licenses/MIT 7 | # 8 | # Created on 2014-07-03 9 | # 10 | 11 | """Read in data from `books.tsv` and add it to the search index database. 12 | 13 | See `catalogue_to_tsv.py` for the generation of the `books.tsv` file. 14 | """ 15 | 16 | from __future__ import print_function, unicode_literals 17 | 18 | import sys 19 | import os 20 | import sqlite3 21 | import csv 22 | from time import time 23 | 24 | from workflow import Workflow 25 | 26 | from config import INDEX_DB, DATA_FILE 27 | 28 | log = None 29 | 30 | 31 | def create_index_db(): 32 | """Create a "virtual" table, which sqlite3 uses for its full-text search 33 | 34 | Given the size of the original data source (~45K entries, 5 MB), we'll put 35 | *all* the data in the database. 36 | 37 | Depending on the data you have, it might make more sense to only add 38 | the fields you want to search to the search DB plus an ID (included here 39 | but unused) with which you can retrieve the full data from your full 40 | dataset. 41 | """ 42 | log.info('Creating index database') 43 | con = sqlite3.connect(INDEX_DB) 44 | with con: 45 | cur = con.cursor() 46 | # cur.execute( 47 | # "CREATE TABLE books(id INT, author TEXT, title TEXT, url TEXT)") 48 | cur.execute( 49 | "CREATE VIRTUAL TABLE books USING fts3(id, author, title, url)") 50 | 51 | 52 | def update_index_db(): 53 | """Read in the data source and add it to the search index database""" 54 | start = time() 55 | log.info('Updating index database') 56 | con = sqlite3.connect(INDEX_DB) 57 | count = 0 58 | with con: 59 | cur = con.cursor() 60 | with open(DATA_FILE, 'rb') as fp: 61 | reader = csv.reader(fp, delimiter=b'\t') 62 | for row in reader: 63 | id_, author, title, url = [v.decode('utf-8') for v in row] 64 | id_ = int(id_) 65 | cur.execute("""INSERT OR IGNORE INTO 66 | books (id, author, title, url) 67 | VALUES (?, ?, ?, ?) 68 | """, (id_, author, title, url)) 69 | # log.info('Added {} by {} to database'.format(title, author)) 70 | count += 1 71 | log.info('{} items added/updated in {:0.3} seconds'.format( 72 | count, time() - start)) 73 | 74 | 75 | def main(wf): 76 | if not os.path.exists(INDEX_DB): 77 | create_index_db() 78 | update_index_db() 79 | log.info('Index database update finished') 80 | 81 | 82 | if __name__ == '__main__': 83 | wf = Workflow() 84 | log = wf.logger 85 | sys.exit(wf.run(main)) 86 | -------------------------------------------------------------------------------- /src/info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | bundleid 6 | net.deanishe.alfred-index-demo 7 | connections 8 | 9 | E2E84778-9472-48A7-851A-87F07879DA5C 10 | 11 | 12 | destinationuid 13 | D56B2A64-50BA-464C-8D64-48EB68D5B376 14 | modifiers 15 | 0 16 | modifiersubtext 17 | 18 | vitoclose 19 | 20 | 21 | 22 | 23 | createdby 24 | Dean Jackson 25 | description 26 | Search Gutenberg.org Book Catalogue 27 | disabled 28 | 29 | name 30 | Gutenberg Book Search 31 | objects 32 | 33 | 34 | config 35 | 36 | browser 37 | 38 | spaces 39 | 40 | url 41 | {query} 42 | utf8 43 | 44 | 45 | type 46 | alfred.workflow.action.openurl 47 | uid 48 | D56B2A64-50BA-464C-8D64-48EB68D5B376 49 | version 50 | 1 51 | 52 | 53 | config 54 | 55 | alfredfiltersresults 56 | 57 | alfredfiltersresultsmatchmode 58 | 0 59 | argumenttrimmode 60 | 0 61 | argumenttype 62 | 0 63 | escaping 64 | 102 65 | keyword 66 | books 67 | queuedelaycustom 68 | 1 69 | queuedelayimmediatelyinitially 70 | 71 | queuedelaymode 72 | 0 73 | queuemode 74 | 1 75 | runningsubtext 76 | Searching books… 77 | script 78 | /usr/bin/python books.py "$1" 79 | scriptargtype 80 | 1 81 | scriptfile 82 | 83 | subtext 84 | 85 | title 86 | Search Gutenberg Book Catalogue 87 | type 88 | 0 89 | withspace 90 | 91 | 92 | type 93 | alfred.workflow.input.scriptfilter 94 | uid 95 | E2E84778-9472-48A7-851A-87F07879DA5C 96 | version 97 | 2 98 | 99 | 100 | readme 101 | 102 | uidata 103 | 104 | D56B2A64-50BA-464C-8D64-48EB68D5B376 105 | 106 | note 107 | Open book page in browser 108 | xpos 109 | 240 110 | ypos 111 | 30 112 | 113 | E2E84778-9472-48A7-851A-87F07879DA5C 114 | 115 | note 116 | Search Gutenberg.org ebooks 117 | xpos 118 | 40 119 | ypos 120 | 30 121 | 122 | 123 | version 124 | 1.4 125 | webaddress 126 | 127 | 128 | 129 | -------------------------------------------------------------------------------- /src/workflow/.alfredversionchecked: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deanishe/alfred-index-demo/c3b479fe00f4bb53e78b78c21afcaddea086adba/src/workflow/.alfredversionchecked -------------------------------------------------------------------------------- /src/workflow/Notify.tgz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deanishe/alfred-index-demo/c3b479fe00f4bb53e78b78c21afcaddea086adba/src/workflow/Notify.tgz -------------------------------------------------------------------------------- /src/workflow/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2014 Dean Jackson 5 | # 6 | # MIT Licence. See http://opensource.org/licenses/MIT 7 | # 8 | # Created on 2014-02-15 9 | # 10 | 11 | """A helper library for `Alfred `_ workflows.""" 12 | 13 | import os 14 | 15 | # Workflow objects 16 | from .workflow import Workflow, manager 17 | from .workflow3 import Variables, Workflow3 18 | 19 | # Exceptions 20 | from .workflow import PasswordNotFound, KeychainError 21 | 22 | # Icons 23 | from .workflow import ( 24 | ICON_ACCOUNT, 25 | ICON_BURN, 26 | ICON_CLOCK, 27 | ICON_COLOR, 28 | ICON_COLOUR, 29 | ICON_EJECT, 30 | ICON_ERROR, 31 | ICON_FAVORITE, 32 | ICON_FAVOURITE, 33 | ICON_GROUP, 34 | ICON_HELP, 35 | ICON_HOME, 36 | ICON_INFO, 37 | ICON_NETWORK, 38 | ICON_NOTE, 39 | ICON_SETTINGS, 40 | ICON_SWIRL, 41 | ICON_SWITCH, 42 | ICON_SYNC, 43 | ICON_TRASH, 44 | ICON_USER, 45 | ICON_WARNING, 46 | ICON_WEB, 47 | ) 48 | 49 | # Filter matching rules 50 | from .workflow import ( 51 | MATCH_ALL, 52 | MATCH_ALLCHARS, 53 | MATCH_ATOM, 54 | MATCH_CAPITALS, 55 | MATCH_INITIALS, 56 | MATCH_INITIALS_CONTAIN, 57 | MATCH_INITIALS_STARTSWITH, 58 | MATCH_STARTSWITH, 59 | MATCH_SUBSTRING, 60 | ) 61 | 62 | 63 | __title__ = 'Alfred-Workflow' 64 | __version__ = open(os.path.join(os.path.dirname(__file__), 'version')).read() 65 | __author__ = 'Dean Jackson' 66 | __licence__ = 'MIT' 67 | __copyright__ = 'Copyright 2014-2017 Dean Jackson' 68 | 69 | __all__ = [ 70 | 'Variables', 71 | 'Workflow', 72 | 'Workflow3', 73 | 'manager', 74 | 'PasswordNotFound', 75 | 'KeychainError', 76 | 'ICON_ACCOUNT', 77 | 'ICON_BURN', 78 | 'ICON_CLOCK', 79 | 'ICON_COLOR', 80 | 'ICON_COLOUR', 81 | 'ICON_EJECT', 82 | 'ICON_ERROR', 83 | 'ICON_FAVORITE', 84 | 'ICON_FAVOURITE', 85 | 'ICON_GROUP', 86 | 'ICON_HELP', 87 | 'ICON_HOME', 88 | 'ICON_INFO', 89 | 'ICON_NETWORK', 90 | 'ICON_NOTE', 91 | 'ICON_SETTINGS', 92 | 'ICON_SWIRL', 93 | 'ICON_SWITCH', 94 | 'ICON_SYNC', 95 | 'ICON_TRASH', 96 | 'ICON_USER', 97 | 'ICON_WARNING', 98 | 'ICON_WEB', 99 | 'MATCH_ALL', 100 | 'MATCH_ALLCHARS', 101 | 'MATCH_ATOM', 102 | 'MATCH_CAPITALS', 103 | 'MATCH_INITIALS', 104 | 'MATCH_INITIALS_CONTAIN', 105 | 'MATCH_INITIALS_STARTSWITH', 106 | 'MATCH_STARTSWITH', 107 | 'MATCH_SUBSTRING', 108 | ] 109 | -------------------------------------------------------------------------------- /src/workflow/background.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2014 deanishe@deanishe.net 5 | # 6 | # MIT Licence. See http://opensource.org/licenses/MIT 7 | # 8 | # Created on 2014-04-06 9 | # 10 | 11 | """ 12 | This module provides an API to run commands in background processes. 13 | Combine with the :ref:`caching API ` to work from cached data 14 | while you fetch fresh data in the background. 15 | 16 | See :ref:`the User Manual ` for more information 17 | and examples. 18 | """ 19 | 20 | from __future__ import print_function, unicode_literals 21 | 22 | import sys 23 | import os 24 | import subprocess 25 | import pickle 26 | 27 | from workflow import Workflow 28 | 29 | __all__ = ['is_running', 'run_in_background'] 30 | 31 | _wf = None 32 | 33 | 34 | def wf(): 35 | global _wf 36 | if _wf is None: 37 | _wf = Workflow() 38 | return _wf 39 | 40 | 41 | def _log(): 42 | return wf().logger 43 | 44 | 45 | def _arg_cache(name): 46 | """Return path to pickle cache file for arguments. 47 | 48 | :param name: name of task 49 | :type name: ``unicode`` 50 | :returns: Path to cache file 51 | :rtype: ``unicode`` filepath 52 | 53 | """ 54 | return wf().cachefile(name + '.argcache') 55 | 56 | 57 | def _pid_file(name): 58 | """Return path to PID file for ``name``. 59 | 60 | :param name: name of task 61 | :type name: ``unicode`` 62 | :returns: Path to PID file for task 63 | :rtype: ``unicode`` filepath 64 | 65 | """ 66 | return wf().cachefile(name + '.pid') 67 | 68 | 69 | def _process_exists(pid): 70 | """Check if a process with PID ``pid`` exists. 71 | 72 | :param pid: PID to check 73 | :type pid: ``int`` 74 | :returns: ``True`` if process exists, else ``False`` 75 | :rtype: ``Boolean`` 76 | 77 | """ 78 | try: 79 | os.kill(pid, 0) 80 | except OSError: # not running 81 | return False 82 | return True 83 | 84 | 85 | def is_running(name): 86 | """Test whether task ``name`` is currently running. 87 | 88 | :param name: name of task 89 | :type name: unicode 90 | :returns: ``True`` if task with name ``name`` is running, else ``False`` 91 | :rtype: bool 92 | 93 | """ 94 | pidfile = _pid_file(name) 95 | if not os.path.exists(pidfile): 96 | return False 97 | 98 | with open(pidfile, 'rb') as file_obj: 99 | pid = int(file_obj.read().strip()) 100 | 101 | if _process_exists(pid): 102 | return True 103 | 104 | elif os.path.exists(pidfile): 105 | os.unlink(pidfile) 106 | 107 | return False 108 | 109 | 110 | def _background(stdin='/dev/null', stdout='/dev/null', 111 | stderr='/dev/null'): # pragma: no cover 112 | """Fork the current process into a background daemon. 113 | 114 | :param stdin: where to read input 115 | :type stdin: filepath 116 | :param stdout: where to write stdout output 117 | :type stdout: filepath 118 | :param stderr: where to write stderr output 119 | :type stderr: filepath 120 | 121 | """ 122 | def _fork_and_exit_parent(errmsg): 123 | try: 124 | pid = os.fork() 125 | if pid > 0: 126 | os._exit(0) 127 | except OSError as err: 128 | _log().critical('%s: (%d) %s', errmsg, err.errno, err.strerror) 129 | raise err 130 | 131 | # Do first fork. 132 | _fork_and_exit_parent('fork #1 failed') 133 | 134 | # Decouple from parent environment. 135 | os.chdir(wf().workflowdir) 136 | os.setsid() 137 | 138 | # Do second fork. 139 | _fork_and_exit_parent('fork #2 failed') 140 | 141 | # Now I am a daemon! 142 | # Redirect standard file descriptors. 143 | si = open(stdin, 'r', 0) 144 | so = open(stdout, 'a+', 0) 145 | se = open(stderr, 'a+', 0) 146 | if hasattr(sys.stdin, 'fileno'): 147 | os.dup2(si.fileno(), sys.stdin.fileno()) 148 | if hasattr(sys.stdout, 'fileno'): 149 | os.dup2(so.fileno(), sys.stdout.fileno()) 150 | if hasattr(sys.stderr, 'fileno'): 151 | os.dup2(se.fileno(), sys.stderr.fileno()) 152 | 153 | 154 | def run_in_background(name, args, **kwargs): 155 | r"""Cache arguments then call this script again via :func:`subprocess.call`. 156 | 157 | :param name: name of task 158 | :type name: unicode 159 | :param args: arguments passed as first argument to :func:`subprocess.call` 160 | :param \**kwargs: keyword arguments to :func:`subprocess.call` 161 | :returns: exit code of sub-process 162 | :rtype: int 163 | 164 | When you call this function, it caches its arguments and then calls 165 | ``background.py`` in a subprocess. The Python subprocess will load the 166 | cached arguments, fork into the background, and then run the command you 167 | specified. 168 | 169 | This function will return as soon as the ``background.py`` subprocess has 170 | forked, returning the exit code of *that* process (i.e. not of the command 171 | you're trying to run). 172 | 173 | If that process fails, an error will be written to the log file. 174 | 175 | If a process is already running under the same name, this function will 176 | return immediately and will not run the specified command. 177 | 178 | """ 179 | if is_running(name): 180 | _log().info('[%s] job already running', name) 181 | return 182 | 183 | argcache = _arg_cache(name) 184 | 185 | # Cache arguments 186 | with open(argcache, 'wb') as file_obj: 187 | pickle.dump({'args': args, 'kwargs': kwargs}, file_obj) 188 | _log().debug('[%s] command cached: %s', name, argcache) 189 | 190 | # Call this script 191 | cmd = ['/usr/bin/python', __file__, name] 192 | _log().debug('[%s] passing job to background runner: %r', name, cmd) 193 | retcode = subprocess.call(cmd) 194 | if retcode: # pragma: no cover 195 | _log().error('[%s] background runner failed with %d', retcode) 196 | else: 197 | _log().debug('[%s] background job started', name) 198 | return retcode 199 | 200 | 201 | def main(wf): # pragma: no cover 202 | """Run command in a background process. 203 | 204 | Load cached arguments, fork into background, then call 205 | :meth:`subprocess.call` with cached arguments. 206 | 207 | """ 208 | log = wf.logger 209 | name = wf.args[0] 210 | argcache = _arg_cache(name) 211 | if not os.path.exists(argcache): 212 | log.critical('[%s] command cache not found: %r', name, argcache) 213 | return 1 214 | 215 | # Load cached arguments 216 | with open(argcache, 'rb') as file_obj: 217 | data = pickle.load(file_obj) 218 | 219 | # Cached arguments 220 | args = data['args'] 221 | kwargs = data['kwargs'] 222 | 223 | # Delete argument cache file 224 | os.unlink(argcache) 225 | 226 | pidfile = _pid_file(name) 227 | 228 | # Fork to background 229 | _background() 230 | 231 | # Write PID to file 232 | with open(pidfile, 'wb') as file_obj: 233 | file_obj.write(str(os.getpid())) 234 | 235 | # Run the command 236 | try: 237 | log.debug('[%s] running command: %r', name, args) 238 | 239 | retcode = subprocess.call(args, **kwargs) 240 | 241 | if retcode: 242 | log.error('[%s] command failed with status %d', name, retcode) 243 | 244 | finally: 245 | if os.path.exists(pidfile): 246 | os.unlink(pidfile) 247 | log.debug('[%s] job complete', name) 248 | 249 | 250 | if __name__ == '__main__': # pragma: no cover 251 | wf().run(main) 252 | -------------------------------------------------------------------------------- /src/workflow/notify.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2015 deanishe@deanishe.net 5 | # 6 | # MIT Licence. See http://opensource.org/licenses/MIT 7 | # 8 | # Created on 2015-11-26 9 | # 10 | 11 | # TODO: Exclude this module from test and code coverage in py2.6 12 | 13 | """ 14 | Post notifications via the macOS Notification Center. This feature 15 | is only available on Mountain Lion (10.8) and later. It will 16 | silently fail on older systems. 17 | 18 | The main API is a single function, :func:`~workflow.notify.notify`. 19 | 20 | It works by copying a simple application to your workflow's data 21 | directory. It replaces the application's icon with your workflow's 22 | icon and then calls the application to post notifications. 23 | """ 24 | 25 | from __future__ import print_function, unicode_literals 26 | 27 | import os 28 | import plistlib 29 | import shutil 30 | import subprocess 31 | import sys 32 | import tarfile 33 | import tempfile 34 | import uuid 35 | 36 | import workflow 37 | 38 | 39 | _wf = None 40 | _log = None 41 | 42 | 43 | #: Available system sounds from System Preferences > Sound > Sound Effects 44 | SOUNDS = ( 45 | 'Basso', 46 | 'Blow', 47 | 'Bottle', 48 | 'Frog', 49 | 'Funk', 50 | 'Glass', 51 | 'Hero', 52 | 'Morse', 53 | 'Ping', 54 | 'Pop', 55 | 'Purr', 56 | 'Sosumi', 57 | 'Submarine', 58 | 'Tink', 59 | ) 60 | 61 | 62 | def wf(): 63 | """Return Workflow object for this module. 64 | 65 | Returns: 66 | workflow.Workflow: Workflow object for current workflow. 67 | """ 68 | global _wf 69 | if _wf is None: 70 | _wf = workflow.Workflow() 71 | return _wf 72 | 73 | 74 | def log(): 75 | """Return logger for this module. 76 | 77 | Returns: 78 | logging.Logger: Logger for this module. 79 | """ 80 | global _log 81 | if _log is None: 82 | _log = wf().logger 83 | return _log 84 | 85 | 86 | def notifier_program(): 87 | """Return path to notifier applet executable. 88 | 89 | Returns: 90 | unicode: Path to Notify.app ``applet`` executable. 91 | """ 92 | return wf().datafile('Notify.app/Contents/MacOS/applet') 93 | 94 | 95 | def notifier_icon_path(): 96 | """Return path to icon file in installed Notify.app. 97 | 98 | Returns: 99 | unicode: Path to ``applet.icns`` within the app bundle. 100 | """ 101 | return wf().datafile('Notify.app/Contents/Resources/applet.icns') 102 | 103 | 104 | def install_notifier(): 105 | """Extract ``Notify.app`` from the workflow to data directory. 106 | 107 | Changes the bundle ID of the installed app and gives it the 108 | workflow's icon. 109 | """ 110 | archive = os.path.join(os.path.dirname(__file__), 'Notify.tgz') 111 | destdir = wf().datadir 112 | app_path = os.path.join(destdir, 'Notify.app') 113 | n = notifier_program() 114 | log().debug('installing Notify.app to %r ...', destdir) 115 | # z = zipfile.ZipFile(archive, 'r') 116 | # z.extractall(destdir) 117 | tgz = tarfile.open(archive, 'r:gz') 118 | tgz.extractall(destdir) 119 | assert os.path.exists(n), \ 120 | 'Notify.app could not be installed in %s' % destdir 121 | 122 | # Replace applet icon 123 | icon = notifier_icon_path() 124 | workflow_icon = wf().workflowfile('icon.png') 125 | if os.path.exists(icon): 126 | os.unlink(icon) 127 | 128 | png_to_icns(workflow_icon, icon) 129 | 130 | # Set file icon 131 | # PyObjC isn't available for 2.6, so this is 2.7 only. Actually, 132 | # none of this code will "work" on pre-10.8 systems. Let it run 133 | # until I figure out a better way of excluding this module 134 | # from coverage in py2.6. 135 | if sys.version_info >= (2, 7): # pragma: no cover 136 | from AppKit import NSWorkspace, NSImage 137 | 138 | ws = NSWorkspace.sharedWorkspace() 139 | img = NSImage.alloc().init() 140 | img.initWithContentsOfFile_(icon) 141 | ws.setIcon_forFile_options_(img, app_path, 0) 142 | 143 | # Change bundle ID of installed app 144 | ip_path = os.path.join(app_path, 'Contents/Info.plist') 145 | bundle_id = '{0}.{1}'.format(wf().bundleid, uuid.uuid4().hex) 146 | data = plistlib.readPlist(ip_path) 147 | log().debug('changing bundle ID to %r', bundle_id) 148 | data['CFBundleIdentifier'] = bundle_id 149 | plistlib.writePlist(data, ip_path) 150 | 151 | 152 | def validate_sound(sound): 153 | """Coerce ``sound`` to valid sound name. 154 | 155 | Returns ``None`` for invalid sounds. Sound names can be found 156 | in ``System Preferences > Sound > Sound Effects``. 157 | 158 | Args: 159 | sound (str): Name of system sound. 160 | 161 | Returns: 162 | str: Proper name of sound or ``None``. 163 | """ 164 | if not sound: 165 | return None 166 | 167 | # Case-insensitive comparison of `sound` 168 | if sound.lower() in [s.lower() for s in SOUNDS]: 169 | # Title-case is correct for all system sounds as of macOS 10.11 170 | return sound.title() 171 | return None 172 | 173 | 174 | def notify(title='', text='', sound=None): 175 | """Post notification via Notify.app helper. 176 | 177 | Args: 178 | title (str, optional): Notification title. 179 | text (str, optional): Notification body text. 180 | sound (str, optional): Name of sound to play. 181 | 182 | Raises: 183 | ValueError: Raised if both ``title`` and ``text`` are empty. 184 | 185 | Returns: 186 | bool: ``True`` if notification was posted, else ``False``. 187 | """ 188 | if title == text == '': 189 | raise ValueError('Empty notification') 190 | 191 | sound = validate_sound(sound) or '' 192 | 193 | n = notifier_program() 194 | 195 | if not os.path.exists(n): 196 | install_notifier() 197 | 198 | env = os.environ.copy() 199 | enc = 'utf-8' 200 | env['NOTIFY_TITLE'] = title.encode(enc) 201 | env['NOTIFY_MESSAGE'] = text.encode(enc) 202 | env['NOTIFY_SOUND'] = sound.encode(enc) 203 | cmd = [n] 204 | retcode = subprocess.call(cmd, env=env) 205 | if retcode == 0: 206 | return True 207 | 208 | log().error('Notify.app exited with status {0}.'.format(retcode)) 209 | return False 210 | 211 | 212 | def convert_image(inpath, outpath, size): 213 | """Convert an image file using ``sips``. 214 | 215 | Args: 216 | inpath (str): Path of source file. 217 | outpath (str): Path to destination file. 218 | size (int): Width and height of destination image in pixels. 219 | 220 | Raises: 221 | RuntimeError: Raised if ``sips`` exits with non-zero status. 222 | """ 223 | cmd = [ 224 | b'sips', 225 | b'-z', str(size), str(size), 226 | inpath, 227 | b'--out', outpath] 228 | # log().debug(cmd) 229 | with open(os.devnull, 'w') as pipe: 230 | retcode = subprocess.call(cmd, stdout=pipe, stderr=subprocess.STDOUT) 231 | 232 | if retcode != 0: 233 | raise RuntimeError('sips exited with %d' % retcode) 234 | 235 | 236 | def png_to_icns(png_path, icns_path): 237 | """Convert PNG file to ICNS using ``iconutil``. 238 | 239 | Create an iconset from the source PNG file. Generate PNG files 240 | in each size required by macOS, then call ``iconutil`` to turn 241 | them into a single ICNS file. 242 | 243 | Args: 244 | png_path (str): Path to source PNG file. 245 | icns_path (str): Path to destination ICNS file. 246 | 247 | Raises: 248 | RuntimeError: Raised if ``iconutil`` or ``sips`` fail. 249 | """ 250 | tempdir = tempfile.mkdtemp(prefix='aw-', dir=wf().datadir) 251 | 252 | try: 253 | iconset = os.path.join(tempdir, 'Icon.iconset') 254 | 255 | assert not os.path.exists(iconset), \ 256 | 'iconset already exists: ' + iconset 257 | os.makedirs(iconset) 258 | 259 | # Copy source icon to icon set and generate all the other 260 | # sizes needed 261 | configs = [] 262 | for i in (16, 32, 128, 256, 512): 263 | configs.append(('icon_{0}x{0}.png'.format(i), i)) 264 | configs.append((('icon_{0}x{0}@2x.png'.format(i), i * 2))) 265 | 266 | shutil.copy(png_path, os.path.join(iconset, 'icon_256x256.png')) 267 | shutil.copy(png_path, os.path.join(iconset, 'icon_128x128@2x.png')) 268 | 269 | for name, size in configs: 270 | outpath = os.path.join(iconset, name) 271 | if os.path.exists(outpath): 272 | continue 273 | convert_image(png_path, outpath, size) 274 | 275 | cmd = [ 276 | b'iconutil', 277 | b'-c', b'icns', 278 | b'-o', icns_path, 279 | iconset] 280 | 281 | retcode = subprocess.call(cmd) 282 | if retcode != 0: 283 | raise RuntimeError('iconset exited with %d' % retcode) 284 | 285 | assert os.path.exists(icns_path), \ 286 | 'generated ICNS file not found: ' + repr(icns_path) 287 | finally: 288 | try: 289 | shutil.rmtree(tempdir) 290 | except OSError: # pragma: no cover 291 | pass 292 | 293 | 294 | if __name__ == '__main__': # pragma: nocover 295 | # Simple command-line script to test module with 296 | # This won't work on 2.6, as `argparse` isn't available 297 | # by default. 298 | import argparse 299 | 300 | from unicodedata import normalize 301 | 302 | def ustr(s): 303 | """Coerce `s` to normalised Unicode.""" 304 | return normalize('NFD', s.decode('utf-8')) 305 | 306 | p = argparse.ArgumentParser() 307 | p.add_argument('-p', '--png', help="PNG image to convert to ICNS.") 308 | p.add_argument('-l', '--list-sounds', help="Show available sounds.", 309 | action='store_true') 310 | p.add_argument('-t', '--title', 311 | help="Notification title.", type=ustr, 312 | default='') 313 | p.add_argument('-s', '--sound', type=ustr, 314 | help="Optional notification sound.", default='') 315 | p.add_argument('text', type=ustr, 316 | help="Notification body text.", default='', nargs='?') 317 | o = p.parse_args() 318 | 319 | # List available sounds 320 | if o.list_sounds: 321 | for sound in SOUNDS: 322 | print(sound) 323 | sys.exit(0) 324 | 325 | # Convert PNG to ICNS 326 | if o.png: 327 | icns = os.path.join( 328 | os.path.dirname(o.png), 329 | os.path.splitext(os.path.basename(o.png))[0] + '.icns') 330 | 331 | print('converting {0!r} to {1!r} ...'.format(o.png, icns), 332 | file=sys.stderr) 333 | 334 | assert not os.path.exists(icns), \ 335 | 'destination file already exists: ' + icns 336 | 337 | png_to_icns(o.png, icns) 338 | sys.exit(0) 339 | 340 | # Post notification 341 | if o.title == o.text == '': 342 | print('ERROR: empty notification.', file=sys.stderr) 343 | sys.exit(1) 344 | else: 345 | notify(o.title, o.text, o.sound) 346 | -------------------------------------------------------------------------------- /src/workflow/update.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | # 4 | # Copyright (c) 2014 Fabio Niephaus , 5 | # Dean Jackson 6 | # 7 | # MIT Licence. See http://opensource.org/licenses/MIT 8 | # 9 | # Created on 2014-08-16 10 | # 11 | 12 | """Self-updating from GitHub. 13 | 14 | .. versionadded:: 1.9 15 | 16 | .. note:: 17 | 18 | This module is not intended to be used directly. Automatic updates 19 | are controlled by the ``update_settings`` :class:`dict` passed to 20 | :class:`~workflow.workflow.Workflow` objects. 21 | 22 | """ 23 | 24 | from __future__ import print_function, unicode_literals 25 | 26 | import os 27 | import tempfile 28 | import re 29 | import subprocess 30 | 31 | import workflow 32 | import web 33 | 34 | # __all__ = [] 35 | 36 | 37 | RELEASES_BASE = 'https://api.github.com/repos/{0}/releases' 38 | 39 | 40 | _wf = None 41 | 42 | 43 | def wf(): 44 | """Lazy `Workflow` object.""" 45 | global _wf 46 | if _wf is None: 47 | _wf = workflow.Workflow() 48 | return _wf 49 | 50 | 51 | class Version(object): 52 | """Mostly semantic versioning. 53 | 54 | The main difference to proper :ref:`semantic versioning ` 55 | is that this implementation doesn't require a minor or patch version. 56 | 57 | Version strings may also be prefixed with "v", e.g.: 58 | 59 | >>> v = Version('v1.1.1') 60 | >>> v.tuple 61 | (1, 1, 1, '') 62 | 63 | >>> v = Version('2.0') 64 | >>> v.tuple 65 | (2, 0, 0, '') 66 | 67 | >>> Version('3.1-beta').tuple 68 | (3, 1, 0, 'beta') 69 | 70 | >>> Version('1.0.1') > Version('0.0.1') 71 | True 72 | """ 73 | 74 | #: Match version and pre-release/build information in version strings 75 | match_version = re.compile(r'([0-9\.]+)(.+)?').match 76 | 77 | def __init__(self, vstr): 78 | """Create new `Version` object. 79 | 80 | Args: 81 | vstr (basestring): Semantic version string. 82 | """ 83 | self.vstr = vstr 84 | self.major = 0 85 | self.minor = 0 86 | self.patch = 0 87 | self.suffix = '' 88 | self.build = '' 89 | self._parse(vstr) 90 | 91 | def _parse(self, vstr): 92 | if vstr.startswith('v'): 93 | m = self.match_version(vstr[1:]) 94 | else: 95 | m = self.match_version(vstr) 96 | if not m: 97 | raise ValueError('invalid version number: {0}'.format(vstr)) 98 | 99 | version, suffix = m.groups() 100 | parts = self._parse_dotted_string(version) 101 | self.major = parts.pop(0) 102 | if len(parts): 103 | self.minor = parts.pop(0) 104 | if len(parts): 105 | self.patch = parts.pop(0) 106 | if not len(parts) == 0: 107 | raise ValueError('invalid version (too long) : {0}'.format(vstr)) 108 | 109 | if suffix: 110 | # Build info 111 | idx = suffix.find('+') 112 | if idx > -1: 113 | self.build = suffix[idx+1:] 114 | suffix = suffix[:idx] 115 | if suffix: 116 | if not suffix.startswith('-'): 117 | raise ValueError( 118 | 'suffix must start with - : {0}'.format(suffix)) 119 | self.suffix = suffix[1:] 120 | 121 | # wf().logger.debug('version str `{}` -> {}'.format(vstr, repr(self))) 122 | 123 | def _parse_dotted_string(self, s): 124 | """Parse string ``s`` into list of ints and strings.""" 125 | parsed = [] 126 | parts = s.split('.') 127 | for p in parts: 128 | if p.isdigit(): 129 | p = int(p) 130 | parsed.append(p) 131 | return parsed 132 | 133 | @property 134 | def tuple(self): 135 | """Version number as a tuple of major, minor, patch, pre-release.""" 136 | return (self.major, self.minor, self.patch, self.suffix) 137 | 138 | def __lt__(self, other): 139 | """Implement comparison.""" 140 | if not isinstance(other, Version): 141 | raise ValueError('not a Version instance: {0!r}'.format(other)) 142 | t = self.tuple[:3] 143 | o = other.tuple[:3] 144 | if t < o: 145 | return True 146 | if t == o: # We need to compare suffixes 147 | if self.suffix and not other.suffix: 148 | return True 149 | if other.suffix and not self.suffix: 150 | return False 151 | return (self._parse_dotted_string(self.suffix) < 152 | self._parse_dotted_string(other.suffix)) 153 | # t > o 154 | return False 155 | 156 | def __eq__(self, other): 157 | """Implement comparison.""" 158 | if not isinstance(other, Version): 159 | raise ValueError('not a Version instance: {0!r}'.format(other)) 160 | return self.tuple == other.tuple 161 | 162 | def __ne__(self, other): 163 | """Implement comparison.""" 164 | return not self.__eq__(other) 165 | 166 | def __gt__(self, other): 167 | """Implement comparison.""" 168 | if not isinstance(other, Version): 169 | raise ValueError('not a Version instance: {0!r}'.format(other)) 170 | return other.__lt__(self) 171 | 172 | def __le__(self, other): 173 | """Implement comparison.""" 174 | if not isinstance(other, Version): 175 | raise ValueError('not a Version instance: {0!r}'.format(other)) 176 | return not other.__lt__(self) 177 | 178 | def __ge__(self, other): 179 | """Implement comparison.""" 180 | return not self.__lt__(other) 181 | 182 | def __str__(self): 183 | """Return semantic version string.""" 184 | vstr = '{0}.{1}.{2}'.format(self.major, self.minor, self.patch) 185 | if self.suffix: 186 | vstr = '{0}-{1}'.format(vstr, self.suffix) 187 | if self.build: 188 | vstr = '{0}+{1}'.format(vstr, self.build) 189 | return vstr 190 | 191 | def __repr__(self): 192 | """Return 'code' representation of `Version`.""" 193 | return "Version('{0}')".format(str(self)) 194 | 195 | 196 | def download_workflow(url): 197 | """Download workflow at ``url`` to a local temporary file. 198 | 199 | :param url: URL to .alfredworkflow file in GitHub repo 200 | :returns: path to downloaded file 201 | 202 | """ 203 | filename = url.split('/')[-1] 204 | 205 | if (not filename.endswith('.alfredworkflow') and 206 | not filename.endswith('.alfred3workflow')): 207 | raise ValueError('attachment not a workflow: {0}'.format(filename)) 208 | 209 | local_path = os.path.join(tempfile.gettempdir(), filename) 210 | 211 | wf().logger.debug( 212 | 'downloading updated workflow from `%s` to `%s` ...', url, local_path) 213 | 214 | response = web.get(url) 215 | 216 | with open(local_path, 'wb') as output: 217 | output.write(response.content) 218 | 219 | return local_path 220 | 221 | 222 | def build_api_url(slug): 223 | """Generate releases URL from GitHub slug. 224 | 225 | :param slug: Repo name in form ``username/repo`` 226 | :returns: URL to the API endpoint for the repo's releases 227 | 228 | """ 229 | if len(slug.split('/')) != 2: 230 | raise ValueError('invalid GitHub slug: {0}'.format(slug)) 231 | 232 | return RELEASES_BASE.format(slug) 233 | 234 | 235 | def _validate_release(release): 236 | """Return release for running version of Alfred.""" 237 | alf3 = wf().alfred_version.major == 3 238 | 239 | downloads = {'.alfredworkflow': [], '.alfred3workflow': []} 240 | dl_count = 0 241 | version = release['tag_name'] 242 | 243 | for asset in release.get('assets', []): 244 | url = asset.get('browser_download_url') 245 | if not url: # pragma: nocover 246 | continue 247 | 248 | ext = os.path.splitext(url)[1].lower() 249 | if ext not in downloads: 250 | continue 251 | 252 | # Ignore Alfred 3-only files if Alfred 2 is running 253 | if ext == '.alfred3workflow' and not alf3: 254 | continue 255 | 256 | downloads[ext].append(url) 257 | dl_count += 1 258 | 259 | # download_urls.append(url) 260 | 261 | if dl_count == 0: 262 | wf().logger.warning( 263 | 'invalid release (no workflow file): %s', version) 264 | return None 265 | 266 | for k in downloads: 267 | if len(downloads[k]) > 1: 268 | wf().logger.warning( 269 | 'invalid release (multiple %s files): %s', k, version) 270 | return None 271 | 272 | # Prefer .alfred3workflow file if there is one and Alfred 3 is 273 | # running. 274 | if alf3 and len(downloads['.alfred3workflow']): 275 | download_url = downloads['.alfred3workflow'][0] 276 | 277 | else: 278 | download_url = downloads['.alfredworkflow'][0] 279 | 280 | wf().logger.debug('release %s: %s', version, download_url) 281 | 282 | return { 283 | 'version': version, 284 | 'download_url': download_url, 285 | 'prerelease': release['prerelease'] 286 | } 287 | 288 | 289 | def get_valid_releases(github_slug, prereleases=False): 290 | """Return list of all valid releases. 291 | 292 | :param github_slug: ``username/repo`` for workflow's GitHub repo 293 | :param prereleases: Whether to include pre-releases. 294 | :returns: list of dicts. Each :class:`dict` has the form 295 | ``{'version': '1.1', 'download_url': 'http://github.com/...', 296 | 'prerelease': False }`` 297 | 298 | 299 | A valid release is one that contains one ``.alfredworkflow`` file. 300 | 301 | If the GitHub version (i.e. tag) is of the form ``v1.1``, the leading 302 | ``v`` will be stripped. 303 | 304 | """ 305 | api_url = build_api_url(github_slug) 306 | releases = [] 307 | 308 | wf().logger.debug('retrieving releases list: %s', api_url) 309 | 310 | def retrieve_releases(): 311 | wf().logger.info( 312 | 'retrieving releases: %s', github_slug) 313 | return web.get(api_url).json() 314 | 315 | slug = github_slug.replace('/', '-') 316 | for release in wf().cached_data('gh-releases-' + slug, retrieve_releases): 317 | 318 | release = _validate_release(release) 319 | if release is None: 320 | wf().logger.debug('invalid release: %r', release) 321 | continue 322 | 323 | elif release['prerelease'] and not prereleases: 324 | wf().logger.debug('ignoring prerelease: %s', release['version']) 325 | continue 326 | 327 | wf().logger.debug('release: %r', release) 328 | 329 | releases.append(release) 330 | 331 | return releases 332 | 333 | 334 | def check_update(github_slug, current_version, prereleases=False): 335 | """Check whether a newer release is available on GitHub. 336 | 337 | :param github_slug: ``username/repo`` for workflow's GitHub repo 338 | :param current_version: the currently installed version of the 339 | workflow. :ref:`Semantic versioning ` is required. 340 | :param prereleases: Whether to include pre-releases. 341 | :type current_version: ``unicode`` 342 | :returns: ``True`` if an update is available, else ``False`` 343 | 344 | If an update is available, its version number and download URL will 345 | be cached. 346 | 347 | """ 348 | releases = get_valid_releases(github_slug, prereleases) 349 | 350 | if not len(releases): 351 | raise ValueError('no valid releases for %s', github_slug) 352 | 353 | wf().logger.info('%d releases for %s', len(releases), github_slug) 354 | 355 | # GitHub returns releases newest-first 356 | latest_release = releases[0] 357 | 358 | # (latest_version, download_url) = get_latest_release(releases) 359 | vr = Version(latest_release['version']) 360 | vl = Version(current_version) 361 | wf().logger.debug('latest=%r, installed=%r', vr, vl) 362 | if vr > vl: 363 | 364 | wf().cache_data('__workflow_update_status', { 365 | 'version': latest_release['version'], 366 | 'download_url': latest_release['download_url'], 367 | 'available': True 368 | }) 369 | 370 | return True 371 | 372 | wf().cache_data('__workflow_update_status', {'available': False}) 373 | return False 374 | 375 | 376 | def install_update(): 377 | """If a newer release is available, download and install it. 378 | 379 | :returns: ``True`` if an update is installed, else ``False`` 380 | 381 | """ 382 | update_data = wf().cached_data('__workflow_update_status', max_age=0) 383 | 384 | if not update_data or not update_data.get('available'): 385 | wf().logger.info('no update available') 386 | return False 387 | 388 | local_file = download_workflow(update_data['download_url']) 389 | 390 | wf().logger.info('installing updated workflow ...') 391 | subprocess.call(['open', local_file]) 392 | 393 | update_data['available'] = False 394 | wf().cache_data('__workflow_update_status', update_data) 395 | return True 396 | 397 | 398 | if __name__ == '__main__': # pragma: nocover 399 | import sys 400 | 401 | def show_help(status=0): 402 | """Print help message.""" 403 | print('Usage : update.py (check|install) ' 404 | '[--prereleases] ') 405 | sys.exit(status) 406 | 407 | argv = sys.argv[:] 408 | if '-h' in argv or '--help' in argv: 409 | show_help() 410 | 411 | prereleases = '--prereleases' in argv 412 | 413 | if prereleases: 414 | argv.remove('--prereleases') 415 | 416 | if len(argv) != 4: 417 | show_help(1) 418 | 419 | action, github_slug, version = argv[1:] 420 | 421 | if action == 'check': 422 | check_update(github_slug, version, prereleases) 423 | elif action == 'install': 424 | install_update() 425 | else: 426 | show_help(1) 427 | -------------------------------------------------------------------------------- /src/workflow/version: -------------------------------------------------------------------------------- 1 | 1.27 -------------------------------------------------------------------------------- /src/workflow/web.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | # 3 | # Copyright (c) 2014 Dean Jackson 4 | # 5 | # MIT Licence. See http://opensource.org/licenses/MIT 6 | # 7 | # Created on 2014-02-15 8 | # 9 | 10 | """Lightweight HTTP library with a requests-like interface.""" 11 | 12 | import codecs 13 | import json 14 | import mimetypes 15 | import os 16 | import random 17 | import re 18 | import socket 19 | import string 20 | import unicodedata 21 | import urllib 22 | import urllib2 23 | import urlparse 24 | import zlib 25 | 26 | 27 | USER_AGENT = u'Alfred-Workflow/1.19 (+http://www.deanishe.net/alfred-workflow)' 28 | 29 | # Valid characters for multipart form data boundaries 30 | BOUNDARY_CHARS = string.digits + string.ascii_letters 31 | 32 | # HTTP response codes 33 | RESPONSES = { 34 | 100: 'Continue', 35 | 101: 'Switching Protocols', 36 | 200: 'OK', 37 | 201: 'Created', 38 | 202: 'Accepted', 39 | 203: 'Non-Authoritative Information', 40 | 204: 'No Content', 41 | 205: 'Reset Content', 42 | 206: 'Partial Content', 43 | 300: 'Multiple Choices', 44 | 301: 'Moved Permanently', 45 | 302: 'Found', 46 | 303: 'See Other', 47 | 304: 'Not Modified', 48 | 305: 'Use Proxy', 49 | 307: 'Temporary Redirect', 50 | 400: 'Bad Request', 51 | 401: 'Unauthorized', 52 | 402: 'Payment Required', 53 | 403: 'Forbidden', 54 | 404: 'Not Found', 55 | 405: 'Method Not Allowed', 56 | 406: 'Not Acceptable', 57 | 407: 'Proxy Authentication Required', 58 | 408: 'Request Timeout', 59 | 409: 'Conflict', 60 | 410: 'Gone', 61 | 411: 'Length Required', 62 | 412: 'Precondition Failed', 63 | 413: 'Request Entity Too Large', 64 | 414: 'Request-URI Too Long', 65 | 415: 'Unsupported Media Type', 66 | 416: 'Requested Range Not Satisfiable', 67 | 417: 'Expectation Failed', 68 | 500: 'Internal Server Error', 69 | 501: 'Not Implemented', 70 | 502: 'Bad Gateway', 71 | 503: 'Service Unavailable', 72 | 504: 'Gateway Timeout', 73 | 505: 'HTTP Version Not Supported' 74 | } 75 | 76 | 77 | def str_dict(dic): 78 | """Convert keys and values in ``dic`` into UTF-8-encoded :class:`str`. 79 | 80 | :param dic: Mapping of Unicode strings 81 | :type dic: dict 82 | :returns: Dictionary containing only UTF-8 strings 83 | :rtype: dict 84 | 85 | """ 86 | if isinstance(dic, CaseInsensitiveDictionary): 87 | dic2 = CaseInsensitiveDictionary() 88 | else: 89 | dic2 = {} 90 | for k, v in dic.items(): 91 | if isinstance(k, unicode): 92 | k = k.encode('utf-8') 93 | if isinstance(v, unicode): 94 | v = v.encode('utf-8') 95 | dic2[k] = v 96 | return dic2 97 | 98 | 99 | class NoRedirectHandler(urllib2.HTTPRedirectHandler): 100 | """Prevent redirections.""" 101 | 102 | def redirect_request(self, *args): 103 | return None 104 | 105 | 106 | # Adapted from https://gist.github.com/babakness/3901174 107 | class CaseInsensitiveDictionary(dict): 108 | """Dictionary with caseless key search. 109 | 110 | Enables case insensitive searching while preserving case sensitivity 111 | when keys are listed, ie, via keys() or items() methods. 112 | 113 | Works by storing a lowercase version of the key as the new key and 114 | stores the original key-value pair as the key's value 115 | (values become dictionaries). 116 | 117 | """ 118 | 119 | def __init__(self, initval=None): 120 | """Create new case-insensitive dictionary.""" 121 | if isinstance(initval, dict): 122 | for key, value in initval.iteritems(): 123 | self.__setitem__(key, value) 124 | 125 | elif isinstance(initval, list): 126 | for (key, value) in initval: 127 | self.__setitem__(key, value) 128 | 129 | def __contains__(self, key): 130 | return dict.__contains__(self, key.lower()) 131 | 132 | def __getitem__(self, key): 133 | return dict.__getitem__(self, key.lower())['val'] 134 | 135 | def __setitem__(self, key, value): 136 | return dict.__setitem__(self, key.lower(), {'key': key, 'val': value}) 137 | 138 | def get(self, key, default=None): 139 | try: 140 | v = dict.__getitem__(self, key.lower()) 141 | except KeyError: 142 | return default 143 | else: 144 | return v['val'] 145 | 146 | def update(self, other): 147 | for k, v in other.items(): 148 | self[k] = v 149 | 150 | def items(self): 151 | return [(v['key'], v['val']) for v in dict.itervalues(self)] 152 | 153 | def keys(self): 154 | return [v['key'] for v in dict.itervalues(self)] 155 | 156 | def values(self): 157 | return [v['val'] for v in dict.itervalues(self)] 158 | 159 | def iteritems(self): 160 | for v in dict.itervalues(self): 161 | yield v['key'], v['val'] 162 | 163 | def iterkeys(self): 164 | for v in dict.itervalues(self): 165 | yield v['key'] 166 | 167 | def itervalues(self): 168 | for v in dict.itervalues(self): 169 | yield v['val'] 170 | 171 | 172 | class Response(object): 173 | """ 174 | Returned by :func:`request` / :func:`get` / :func:`post` functions. 175 | 176 | Simplified version of the ``Response`` object in the ``requests`` library. 177 | 178 | >>> r = request('http://www.google.com') 179 | >>> r.status_code 180 | 200 181 | >>> r.encoding 182 | ISO-8859-1 183 | >>> r.content # bytes 184 | ... 185 | >>> r.text # unicode, decoded according to charset in HTTP header/meta tag 186 | u' ...' 187 | >>> r.json() # content parsed as JSON 188 | 189 | """ 190 | 191 | def __init__(self, request, stream=False): 192 | """Call `request` with :mod:`urllib2` and process results. 193 | 194 | :param request: :class:`urllib2.Request` instance 195 | :param stream: Whether to stream response or retrieve it all at once 196 | :type stream: bool 197 | 198 | """ 199 | self.request = request 200 | self._stream = stream 201 | self.url = None 202 | self.raw = None 203 | self._encoding = None 204 | self.error = None 205 | self.status_code = None 206 | self.reason = None 207 | self.headers = CaseInsensitiveDictionary() 208 | self._content = None 209 | self._content_loaded = False 210 | self._gzipped = False 211 | 212 | # Execute query 213 | try: 214 | self.raw = urllib2.urlopen(request) 215 | except urllib2.HTTPError as err: 216 | self.error = err 217 | try: 218 | self.url = err.geturl() 219 | # sometimes (e.g. when authentication fails) 220 | # urllib can't get a URL from an HTTPError 221 | # This behaviour changes across Python versions, 222 | # so no test cover (it isn't important). 223 | except AttributeError: # pragma: no cover 224 | pass 225 | self.status_code = err.code 226 | else: 227 | self.status_code = self.raw.getcode() 228 | self.url = self.raw.geturl() 229 | self.reason = RESPONSES.get(self.status_code) 230 | 231 | # Parse additional info if request succeeded 232 | if not self.error: 233 | headers = self.raw.info() 234 | self.transfer_encoding = headers.getencoding() 235 | self.mimetype = headers.gettype() 236 | for key in headers.keys(): 237 | self.headers[key.lower()] = headers.get(key) 238 | 239 | # Is content gzipped? 240 | # Transfer-Encoding appears to not be used in the wild 241 | # (contrary to the HTTP standard), but no harm in testing 242 | # for it 243 | if ('gzip' in headers.get('content-encoding', '') or 244 | 'gzip' in headers.get('transfer-encoding', '')): 245 | self._gzipped = True 246 | 247 | @property 248 | def stream(self): 249 | """Whether response is streamed. 250 | 251 | Returns: 252 | bool: `True` if response is streamed. 253 | """ 254 | return self._stream 255 | 256 | @stream.setter 257 | def stream(self, value): 258 | if self._content_loaded: 259 | raise RuntimeError("`content` has already been read from " 260 | "this Response.") 261 | 262 | self._stream = value 263 | 264 | def json(self): 265 | """Decode response contents as JSON. 266 | 267 | :returns: object decoded from JSON 268 | :rtype: list, dict or unicode 269 | 270 | """ 271 | return json.loads(self.content, self.encoding or 'utf-8') 272 | 273 | @property 274 | def encoding(self): 275 | """Text encoding of document or ``None``. 276 | 277 | :returns: Text encoding if found. 278 | :rtype: str or ``None`` 279 | 280 | """ 281 | if not self._encoding: 282 | self._encoding = self._get_encoding() 283 | 284 | return self._encoding 285 | 286 | @property 287 | def content(self): 288 | """Raw content of response (i.e. bytes). 289 | 290 | :returns: Body of HTTP response 291 | :rtype: str 292 | 293 | """ 294 | if not self._content: 295 | 296 | # Decompress gzipped content 297 | if self._gzipped: 298 | decoder = zlib.decompressobj(16 + zlib.MAX_WBITS) 299 | self._content = decoder.decompress(self.raw.read()) 300 | 301 | else: 302 | self._content = self.raw.read() 303 | 304 | self._content_loaded = True 305 | 306 | return self._content 307 | 308 | @property 309 | def text(self): 310 | """Unicode-decoded content of response body. 311 | 312 | If no encoding can be determined from HTTP headers or the content 313 | itself, the encoded response body will be returned instead. 314 | 315 | :returns: Body of HTTP response 316 | :rtype: unicode or str 317 | 318 | """ 319 | if self.encoding: 320 | return unicodedata.normalize('NFC', unicode(self.content, 321 | self.encoding)) 322 | return self.content 323 | 324 | def iter_content(self, chunk_size=4096, decode_unicode=False): 325 | """Iterate over response data. 326 | 327 | .. versionadded:: 1.6 328 | 329 | :param chunk_size: Number of bytes to read into memory 330 | :type chunk_size: int 331 | :param decode_unicode: Decode to Unicode using detected encoding 332 | :type decode_unicode: bool 333 | :returns: iterator 334 | 335 | """ 336 | if not self.stream: 337 | raise RuntimeError("You cannot call `iter_content` on a " 338 | "Response unless you passed `stream=True`" 339 | " to `get()`/`post()`/`request()`.") 340 | 341 | if self._content_loaded: 342 | raise RuntimeError( 343 | "`content` has already been read from this Response.") 344 | 345 | def decode_stream(iterator, r): 346 | 347 | decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace') 348 | 349 | for chunk in iterator: 350 | data = decoder.decode(chunk) 351 | if data: 352 | yield data 353 | 354 | data = decoder.decode(b'', final=True) 355 | if data: # pragma: no cover 356 | yield data 357 | 358 | def generate(): 359 | 360 | if self._gzipped: 361 | decoder = zlib.decompressobj(16 + zlib.MAX_WBITS) 362 | 363 | while True: 364 | chunk = self.raw.read(chunk_size) 365 | if not chunk: 366 | break 367 | 368 | if self._gzipped: 369 | chunk = decoder.decompress(chunk) 370 | 371 | yield chunk 372 | 373 | chunks = generate() 374 | 375 | if decode_unicode and self.encoding: 376 | chunks = decode_stream(chunks, self) 377 | 378 | return chunks 379 | 380 | def save_to_path(self, filepath): 381 | """Save retrieved data to file at ``filepath``. 382 | 383 | .. versionadded: 1.9.6 384 | 385 | :param filepath: Path to save retrieved data. 386 | 387 | """ 388 | filepath = os.path.abspath(filepath) 389 | dirname = os.path.dirname(filepath) 390 | if not os.path.exists(dirname): 391 | os.makedirs(dirname) 392 | 393 | self.stream = True 394 | 395 | with open(filepath, 'wb') as fileobj: 396 | for data in self.iter_content(): 397 | fileobj.write(data) 398 | 399 | def raise_for_status(self): 400 | """Raise stored error if one occurred. 401 | 402 | error will be instance of :class:`urllib2.HTTPError` 403 | """ 404 | if self.error is not None: 405 | raise self.error 406 | return 407 | 408 | def _get_encoding(self): 409 | """Get encoding from HTTP headers or content. 410 | 411 | :returns: encoding or `None` 412 | :rtype: unicode or ``None`` 413 | 414 | """ 415 | headers = self.raw.info() 416 | encoding = None 417 | 418 | if headers.getparam('charset'): 419 | encoding = headers.getparam('charset') 420 | 421 | # HTTP Content-Type header 422 | for param in headers.getplist(): 423 | if param.startswith('charset='): 424 | encoding = param[8:] 425 | break 426 | 427 | if not self.stream: # Try sniffing response content 428 | # Encoding declared in document should override HTTP headers 429 | if self.mimetype == 'text/html': # sniff HTML headers 430 | m = re.search("""""", 431 | self.content) 432 | if m: 433 | encoding = m.group(1) 434 | 435 | elif ((self.mimetype.startswith('application/') or 436 | self.mimetype.startswith('text/')) and 437 | 'xml' in self.mimetype): 438 | m = re.search("""]*\?>""", 439 | self.content) 440 | if m: 441 | encoding = m.group(1) 442 | 443 | # Format defaults 444 | if self.mimetype == 'application/json' and not encoding: 445 | # The default encoding for JSON 446 | encoding = 'utf-8' 447 | 448 | elif self.mimetype == 'application/xml' and not encoding: 449 | # The default for 'application/xml' 450 | encoding = 'utf-8' 451 | 452 | if encoding: 453 | encoding = encoding.lower() 454 | 455 | return encoding 456 | 457 | 458 | def request(method, url, params=None, data=None, headers=None, cookies=None, 459 | files=None, auth=None, timeout=60, allow_redirects=False, 460 | stream=False): 461 | """Initiate an HTTP(S) request. Returns :class:`Response` object. 462 | 463 | :param method: 'GET' or 'POST' 464 | :type method: unicode 465 | :param url: URL to open 466 | :type url: unicode 467 | :param params: mapping of URL parameters 468 | :type params: dict 469 | :param data: mapping of form data ``{'field_name': 'value'}`` or 470 | :class:`str` 471 | :type data: dict or str 472 | :param headers: HTTP headers 473 | :type headers: dict 474 | :param cookies: cookies to send to server 475 | :type cookies: dict 476 | :param files: files to upload (see below). 477 | :type files: dict 478 | :param auth: username, password 479 | :type auth: tuple 480 | :param timeout: connection timeout limit in seconds 481 | :type timeout: int 482 | :param allow_redirects: follow redirections 483 | :type allow_redirects: bool 484 | :param stream: Stream content instead of fetching it all at once. 485 | :type stream: bool 486 | :returns: Response object 487 | :rtype: :class:`Response` 488 | 489 | 490 | The ``files`` argument is a dictionary:: 491 | 492 | {'fieldname' : { 'filename': 'blah.txt', 493 | 'content': '', 494 | 'mimetype': 'text/plain'} 495 | } 496 | 497 | * ``fieldname`` is the name of the field in the HTML form. 498 | * ``mimetype`` is optional. If not provided, :mod:`mimetypes` will 499 | be used to guess the mimetype, or ``application/octet-stream`` 500 | will be used. 501 | 502 | """ 503 | # TODO: cookies 504 | socket.setdefaulttimeout(timeout) 505 | 506 | # Default handlers 507 | openers = [] 508 | 509 | if not allow_redirects: 510 | openers.append(NoRedirectHandler()) 511 | 512 | if auth is not None: # Add authorisation handler 513 | username, password = auth 514 | password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() 515 | password_manager.add_password(None, url, username, password) 516 | auth_manager = urllib2.HTTPBasicAuthHandler(password_manager) 517 | openers.append(auth_manager) 518 | 519 | # Install our custom chain of openers 520 | opener = urllib2.build_opener(*openers) 521 | urllib2.install_opener(opener) 522 | 523 | if not headers: 524 | headers = CaseInsensitiveDictionary() 525 | else: 526 | headers = CaseInsensitiveDictionary(headers) 527 | 528 | if 'user-agent' not in headers: 529 | headers['user-agent'] = USER_AGENT 530 | 531 | # Accept gzip-encoded content 532 | encodings = [s.strip() for s in 533 | headers.get('accept-encoding', '').split(',')] 534 | if 'gzip' not in encodings: 535 | encodings.append('gzip') 536 | 537 | headers['accept-encoding'] = ', '.join(encodings) 538 | 539 | # Force POST by providing an empty data string 540 | if method == 'POST' and not data: 541 | data = '' 542 | 543 | if files: 544 | if not data: 545 | data = {} 546 | new_headers, data = encode_multipart_formdata(data, files) 547 | headers.update(new_headers) 548 | elif data and isinstance(data, dict): 549 | data = urllib.urlencode(str_dict(data)) 550 | 551 | # Make sure everything is encoded text 552 | headers = str_dict(headers) 553 | 554 | if isinstance(url, unicode): 555 | url = url.encode('utf-8') 556 | 557 | if params: # GET args (POST args are handled in encode_multipart_formdata) 558 | 559 | scheme, netloc, path, query, fragment = urlparse.urlsplit(url) 560 | 561 | if query: # Combine query string and `params` 562 | url_params = urlparse.parse_qs(query) 563 | # `params` take precedence over URL query string 564 | url_params.update(params) 565 | params = url_params 566 | 567 | query = urllib.urlencode(str_dict(params), doseq=True) 568 | url = urlparse.urlunsplit((scheme, netloc, path, query, fragment)) 569 | 570 | req = urllib2.Request(url, data, headers) 571 | return Response(req, stream) 572 | 573 | 574 | def get(url, params=None, headers=None, cookies=None, auth=None, 575 | timeout=60, allow_redirects=True, stream=False): 576 | """Initiate a GET request. Arguments as for :func:`request`. 577 | 578 | :returns: :class:`Response` instance 579 | 580 | """ 581 | return request('GET', url, params, headers=headers, cookies=cookies, 582 | auth=auth, timeout=timeout, allow_redirects=allow_redirects, 583 | stream=stream) 584 | 585 | 586 | def post(url, params=None, data=None, headers=None, cookies=None, files=None, 587 | auth=None, timeout=60, allow_redirects=False, stream=False): 588 | """Initiate a POST request. Arguments as for :func:`request`. 589 | 590 | :returns: :class:`Response` instance 591 | 592 | """ 593 | return request('POST', url, params, data, headers, cookies, files, auth, 594 | timeout, allow_redirects, stream) 595 | 596 | 597 | def encode_multipart_formdata(fields, files): 598 | """Encode form data (``fields``) and ``files`` for POST request. 599 | 600 | :param fields: mapping of ``{name : value}`` pairs for normal form fields. 601 | :type fields: dict 602 | :param files: dictionary of fieldnames/files elements for file data. 603 | See below for details. 604 | :type files: dict of :class:`dict` 605 | :returns: ``(headers, body)`` ``headers`` is a 606 | :class:`dict` of HTTP headers 607 | :rtype: 2-tuple ``(dict, str)`` 608 | 609 | The ``files`` argument is a dictionary:: 610 | 611 | {'fieldname' : { 'filename': 'blah.txt', 612 | 'content': '', 613 | 'mimetype': 'text/plain'} 614 | } 615 | 616 | - ``fieldname`` is the name of the field in the HTML form. 617 | - ``mimetype`` is optional. If not provided, :mod:`mimetypes` will 618 | be used to guess the mimetype, or ``application/octet-stream`` 619 | will be used. 620 | 621 | """ 622 | def get_content_type(filename): 623 | """Return or guess mimetype of ``filename``. 624 | 625 | :param filename: filename of file 626 | :type filename: unicode/str 627 | :returns: mime-type, e.g. ``text/html`` 628 | :rtype: str 629 | 630 | """ 631 | 632 | return mimetypes.guess_type(filename)[0] or 'application/octet-stream' 633 | 634 | boundary = '-----' + ''.join(random.choice(BOUNDARY_CHARS) 635 | for i in range(30)) 636 | CRLF = '\r\n' 637 | output = [] 638 | 639 | # Normal form fields 640 | for (name, value) in fields.items(): 641 | if isinstance(name, unicode): 642 | name = name.encode('utf-8') 643 | if isinstance(value, unicode): 644 | value = value.encode('utf-8') 645 | output.append('--' + boundary) 646 | output.append('Content-Disposition: form-data; name="%s"' % name) 647 | output.append('') 648 | output.append(value) 649 | 650 | # Files to upload 651 | for name, d in files.items(): 652 | filename = d[u'filename'] 653 | content = d[u'content'] 654 | if u'mimetype' in d: 655 | mimetype = d[u'mimetype'] 656 | else: 657 | mimetype = get_content_type(filename) 658 | if isinstance(name, unicode): 659 | name = name.encode('utf-8') 660 | if isinstance(filename, unicode): 661 | filename = filename.encode('utf-8') 662 | if isinstance(mimetype, unicode): 663 | mimetype = mimetype.encode('utf-8') 664 | output.append('--' + boundary) 665 | output.append('Content-Disposition: form-data; ' 666 | 'name="%s"; filename="%s"' % (name, filename)) 667 | output.append('Content-Type: %s' % mimetype) 668 | output.append('') 669 | output.append(content) 670 | 671 | output.append('--' + boundary + '--') 672 | output.append('') 673 | body = CRLF.join(output) 674 | headers = { 675 | 'Content-Type': 'multipart/form-data; boundary=%s' % boundary, 676 | 'Content-Length': str(len(body)), 677 | } 678 | return (headers, body) 679 | -------------------------------------------------------------------------------- /src/workflow/workflow.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | # 3 | # Copyright (c) 2014 Dean Jackson 4 | # 5 | # MIT Licence. See http://opensource.org/licenses/MIT 6 | # 7 | # Created on 2014-02-15 8 | # 9 | 10 | """The :class:`Workflow` object is the main interface to this library. 11 | 12 | :class:`Workflow` is targeted at Alfred 2. Use 13 | :class:`~workflow.Workflow3` if you want to use Alfred 3's new 14 | features, such as :ref:`workflow variables ` or 15 | more powerful modifiers. 16 | 17 | See :ref:`setup` in the :ref:`user-manual` for an example of how to set 18 | up your Python script to best utilise the :class:`Workflow` object. 19 | 20 | """ 21 | 22 | from __future__ import print_function, unicode_literals 23 | 24 | import atexit 25 | import binascii 26 | from contextlib import contextmanager 27 | import cPickle 28 | from copy import deepcopy 29 | import errno 30 | import json 31 | import logging 32 | import logging.handlers 33 | import os 34 | import pickle 35 | import plistlib 36 | import re 37 | import shutil 38 | import signal 39 | import string 40 | import subprocess 41 | import sys 42 | import time 43 | import unicodedata 44 | 45 | try: 46 | import xml.etree.cElementTree as ET 47 | except ImportError: # pragma: no cover 48 | import xml.etree.ElementTree as ET 49 | 50 | 51 | #: Sentinel for properties that haven't been set yet (that might 52 | #: correctly have the value ``None``) 53 | UNSET = object() 54 | 55 | #################################################################### 56 | # Standard system icons 57 | #################################################################### 58 | 59 | # These icons are default macOS icons. They are super-high quality, and 60 | # will be familiar to users. 61 | # This library uses `ICON_ERROR` when a workflow dies in flames, so 62 | # in my own workflows, I use `ICON_WARNING` for less fatal errors 63 | # (e.g. bad user input, no results etc.) 64 | 65 | # The system icons are all in this directory. There are many more than 66 | # are listed here 67 | 68 | ICON_ROOT = '/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources' 69 | 70 | ICON_ACCOUNT = os.path.join(ICON_ROOT, 'Accounts.icns') 71 | ICON_BURN = os.path.join(ICON_ROOT, 'BurningIcon.icns') 72 | ICON_CLOCK = os.path.join(ICON_ROOT, 'Clock.icns') 73 | ICON_COLOR = os.path.join(ICON_ROOT, 'ProfileBackgroundColor.icns') 74 | ICON_COLOUR = ICON_COLOR # Queen's English, if you please 75 | ICON_EJECT = os.path.join(ICON_ROOT, 'EjectMediaIcon.icns') 76 | # Shown when a workflow throws an error 77 | ICON_ERROR = os.path.join(ICON_ROOT, 'AlertStopIcon.icns') 78 | ICON_FAVORITE = os.path.join(ICON_ROOT, 'ToolbarFavoritesIcon.icns') 79 | ICON_FAVOURITE = ICON_FAVORITE 80 | ICON_GROUP = os.path.join(ICON_ROOT, 'GroupIcon.icns') 81 | ICON_HELP = os.path.join(ICON_ROOT, 'HelpIcon.icns') 82 | ICON_HOME = os.path.join(ICON_ROOT, 'HomeFolderIcon.icns') 83 | ICON_INFO = os.path.join(ICON_ROOT, 'ToolbarInfo.icns') 84 | ICON_NETWORK = os.path.join(ICON_ROOT, 'GenericNetworkIcon.icns') 85 | ICON_NOTE = os.path.join(ICON_ROOT, 'AlertNoteIcon.icns') 86 | ICON_SETTINGS = os.path.join(ICON_ROOT, 'ToolbarAdvanced.icns') 87 | ICON_SWIRL = os.path.join(ICON_ROOT, 'ErasingIcon.icns') 88 | ICON_SWITCH = os.path.join(ICON_ROOT, 'General.icns') 89 | ICON_SYNC = os.path.join(ICON_ROOT, 'Sync.icns') 90 | ICON_TRASH = os.path.join(ICON_ROOT, 'TrashIcon.icns') 91 | ICON_USER = os.path.join(ICON_ROOT, 'UserIcon.icns') 92 | ICON_WARNING = os.path.join(ICON_ROOT, 'AlertCautionIcon.icns') 93 | ICON_WEB = os.path.join(ICON_ROOT, 'BookmarkIcon.icns') 94 | 95 | #################################################################### 96 | # non-ASCII to ASCII diacritic folding. 97 | # Used by `fold_to_ascii` method 98 | #################################################################### 99 | 100 | ASCII_REPLACEMENTS = { 101 | 'À': 'A', 102 | 'Á': 'A', 103 | 'Â': 'A', 104 | 'Ã': 'A', 105 | 'Ä': 'A', 106 | 'Å': 'A', 107 | 'Æ': 'AE', 108 | 'Ç': 'C', 109 | 'È': 'E', 110 | 'É': 'E', 111 | 'Ê': 'E', 112 | 'Ë': 'E', 113 | 'Ì': 'I', 114 | 'Í': 'I', 115 | 'Î': 'I', 116 | 'Ï': 'I', 117 | 'Ð': 'D', 118 | 'Ñ': 'N', 119 | 'Ò': 'O', 120 | 'Ó': 'O', 121 | 'Ô': 'O', 122 | 'Õ': 'O', 123 | 'Ö': 'O', 124 | 'Ø': 'O', 125 | 'Ù': 'U', 126 | 'Ú': 'U', 127 | 'Û': 'U', 128 | 'Ü': 'U', 129 | 'Ý': 'Y', 130 | 'Þ': 'Th', 131 | 'ß': 'ss', 132 | 'à': 'a', 133 | 'á': 'a', 134 | 'â': 'a', 135 | 'ã': 'a', 136 | 'ä': 'a', 137 | 'å': 'a', 138 | 'æ': 'ae', 139 | 'ç': 'c', 140 | 'è': 'e', 141 | 'é': 'e', 142 | 'ê': 'e', 143 | 'ë': 'e', 144 | 'ì': 'i', 145 | 'í': 'i', 146 | 'î': 'i', 147 | 'ï': 'i', 148 | 'ð': 'd', 149 | 'ñ': 'n', 150 | 'ò': 'o', 151 | 'ó': 'o', 152 | 'ô': 'o', 153 | 'õ': 'o', 154 | 'ö': 'o', 155 | 'ø': 'o', 156 | 'ù': 'u', 157 | 'ú': 'u', 158 | 'û': 'u', 159 | 'ü': 'u', 160 | 'ý': 'y', 161 | 'þ': 'th', 162 | 'ÿ': 'y', 163 | 'Ł': 'L', 164 | 'ł': 'l', 165 | 'Ń': 'N', 166 | 'ń': 'n', 167 | 'Ņ': 'N', 168 | 'ņ': 'n', 169 | 'Ň': 'N', 170 | 'ň': 'n', 171 | 'Ŋ': 'ng', 172 | 'ŋ': 'NG', 173 | 'Ō': 'O', 174 | 'ō': 'o', 175 | 'Ŏ': 'O', 176 | 'ŏ': 'o', 177 | 'Ő': 'O', 178 | 'ő': 'o', 179 | 'Œ': 'OE', 180 | 'œ': 'oe', 181 | 'Ŕ': 'R', 182 | 'ŕ': 'r', 183 | 'Ŗ': 'R', 184 | 'ŗ': 'r', 185 | 'Ř': 'R', 186 | 'ř': 'r', 187 | 'Ś': 'S', 188 | 'ś': 's', 189 | 'Ŝ': 'S', 190 | 'ŝ': 's', 191 | 'Ş': 'S', 192 | 'ş': 's', 193 | 'Š': 'S', 194 | 'š': 's', 195 | 'Ţ': 'T', 196 | 'ţ': 't', 197 | 'Ť': 'T', 198 | 'ť': 't', 199 | 'Ŧ': 'T', 200 | 'ŧ': 't', 201 | 'Ũ': 'U', 202 | 'ũ': 'u', 203 | 'Ū': 'U', 204 | 'ū': 'u', 205 | 'Ŭ': 'U', 206 | 'ŭ': 'u', 207 | 'Ů': 'U', 208 | 'ů': 'u', 209 | 'Ű': 'U', 210 | 'ű': 'u', 211 | 'Ŵ': 'W', 212 | 'ŵ': 'w', 213 | 'Ŷ': 'Y', 214 | 'ŷ': 'y', 215 | 'Ÿ': 'Y', 216 | 'Ź': 'Z', 217 | 'ź': 'z', 218 | 'Ż': 'Z', 219 | 'ż': 'z', 220 | 'Ž': 'Z', 221 | 'ž': 'z', 222 | 'ſ': 's', 223 | 'Α': 'A', 224 | 'Β': 'B', 225 | 'Γ': 'G', 226 | 'Δ': 'D', 227 | 'Ε': 'E', 228 | 'Ζ': 'Z', 229 | 'Η': 'E', 230 | 'Θ': 'Th', 231 | 'Ι': 'I', 232 | 'Κ': 'K', 233 | 'Λ': 'L', 234 | 'Μ': 'M', 235 | 'Ν': 'N', 236 | 'Ξ': 'Ks', 237 | 'Ο': 'O', 238 | 'Π': 'P', 239 | 'Ρ': 'R', 240 | 'Σ': 'S', 241 | 'Τ': 'T', 242 | 'Υ': 'U', 243 | 'Φ': 'Ph', 244 | 'Χ': 'Kh', 245 | 'Ψ': 'Ps', 246 | 'Ω': 'O', 247 | 'α': 'a', 248 | 'β': 'b', 249 | 'γ': 'g', 250 | 'δ': 'd', 251 | 'ε': 'e', 252 | 'ζ': 'z', 253 | 'η': 'e', 254 | 'θ': 'th', 255 | 'ι': 'i', 256 | 'κ': 'k', 257 | 'λ': 'l', 258 | 'μ': 'm', 259 | 'ν': 'n', 260 | 'ξ': 'x', 261 | 'ο': 'o', 262 | 'π': 'p', 263 | 'ρ': 'r', 264 | 'ς': 's', 265 | 'σ': 's', 266 | 'τ': 't', 267 | 'υ': 'u', 268 | 'φ': 'ph', 269 | 'χ': 'kh', 270 | 'ψ': 'ps', 271 | 'ω': 'o', 272 | 'А': 'A', 273 | 'Б': 'B', 274 | 'В': 'V', 275 | 'Г': 'G', 276 | 'Д': 'D', 277 | 'Е': 'E', 278 | 'Ж': 'Zh', 279 | 'З': 'Z', 280 | 'И': 'I', 281 | 'Й': 'I', 282 | 'К': 'K', 283 | 'Л': 'L', 284 | 'М': 'M', 285 | 'Н': 'N', 286 | 'О': 'O', 287 | 'П': 'P', 288 | 'Р': 'R', 289 | 'С': 'S', 290 | 'Т': 'T', 291 | 'У': 'U', 292 | 'Ф': 'F', 293 | 'Х': 'Kh', 294 | 'Ц': 'Ts', 295 | 'Ч': 'Ch', 296 | 'Ш': 'Sh', 297 | 'Щ': 'Shch', 298 | 'Ъ': "'", 299 | 'Ы': 'Y', 300 | 'Ь': "'", 301 | 'Э': 'E', 302 | 'Ю': 'Iu', 303 | 'Я': 'Ia', 304 | 'а': 'a', 305 | 'б': 'b', 306 | 'в': 'v', 307 | 'г': 'g', 308 | 'д': 'd', 309 | 'е': 'e', 310 | 'ж': 'zh', 311 | 'з': 'z', 312 | 'и': 'i', 313 | 'й': 'i', 314 | 'к': 'k', 315 | 'л': 'l', 316 | 'м': 'm', 317 | 'н': 'n', 318 | 'о': 'o', 319 | 'п': 'p', 320 | 'р': 'r', 321 | 'с': 's', 322 | 'т': 't', 323 | 'у': 'u', 324 | 'ф': 'f', 325 | 'х': 'kh', 326 | 'ц': 'ts', 327 | 'ч': 'ch', 328 | 'ш': 'sh', 329 | 'щ': 'shch', 330 | 'ъ': "'", 331 | 'ы': 'y', 332 | 'ь': "'", 333 | 'э': 'e', 334 | 'ю': 'iu', 335 | 'я': 'ia', 336 | # 'ᴀ': '', 337 | # 'ᴁ': '', 338 | # 'ᴂ': '', 339 | # 'ᴃ': '', 340 | # 'ᴄ': '', 341 | # 'ᴅ': '', 342 | # 'ᴆ': '', 343 | # 'ᴇ': '', 344 | # 'ᴈ': '', 345 | # 'ᴉ': '', 346 | # 'ᴊ': '', 347 | # 'ᴋ': '', 348 | # 'ᴌ': '', 349 | # 'ᴍ': '', 350 | # 'ᴎ': '', 351 | # 'ᴏ': '', 352 | # 'ᴐ': '', 353 | # 'ᴑ': '', 354 | # 'ᴒ': '', 355 | # 'ᴓ': '', 356 | # 'ᴔ': '', 357 | # 'ᴕ': '', 358 | # 'ᴖ': '', 359 | # 'ᴗ': '', 360 | # 'ᴘ': '', 361 | # 'ᴙ': '', 362 | # 'ᴚ': '', 363 | # 'ᴛ': '', 364 | # 'ᴜ': '', 365 | # 'ᴝ': '', 366 | # 'ᴞ': '', 367 | # 'ᴟ': '', 368 | # 'ᴠ': '', 369 | # 'ᴡ': '', 370 | # 'ᴢ': '', 371 | # 'ᴣ': '', 372 | # 'ᴤ': '', 373 | # 'ᴥ': '', 374 | 'ᴦ': 'G', 375 | 'ᴧ': 'L', 376 | 'ᴨ': 'P', 377 | 'ᴩ': 'R', 378 | 'ᴪ': 'PS', 379 | 'ẞ': 'Ss', 380 | 'Ỳ': 'Y', 381 | 'ỳ': 'y', 382 | 'Ỵ': 'Y', 383 | 'ỵ': 'y', 384 | 'Ỹ': 'Y', 385 | 'ỹ': 'y', 386 | } 387 | 388 | #################################################################### 389 | # Smart-to-dumb punctuation mapping 390 | #################################################################### 391 | 392 | DUMB_PUNCTUATION = { 393 | '‘': "'", 394 | '’': "'", 395 | '‚': "'", 396 | '“': '"', 397 | '”': '"', 398 | '„': '"', 399 | '–': '-', 400 | '—': '-' 401 | } 402 | 403 | 404 | #################################################################### 405 | # Used by `Workflow.filter` 406 | #################################################################### 407 | 408 | # Anchor characters in a name 409 | #: Characters that indicate the beginning of a "word" in CamelCase 410 | INITIALS = string.ascii_uppercase + string.digits 411 | 412 | #: Split on non-letters, numbers 413 | split_on_delimiters = re.compile('[^a-zA-Z0-9]').split 414 | 415 | # Match filter flags 416 | #: Match items that start with ``query`` 417 | MATCH_STARTSWITH = 1 418 | #: Match items whose capital letters start with ``query`` 419 | MATCH_CAPITALS = 2 420 | #: Match items with a component "word" that matches ``query`` 421 | MATCH_ATOM = 4 422 | #: Match items whose initials (based on atoms) start with ``query`` 423 | MATCH_INITIALS_STARTSWITH = 8 424 | #: Match items whose initials (based on atoms) contain ``query`` 425 | MATCH_INITIALS_CONTAIN = 16 426 | #: Combination of :const:`MATCH_INITIALS_STARTSWITH` and 427 | #: :const:`MATCH_INITIALS_CONTAIN` 428 | MATCH_INITIALS = 24 429 | #: Match items if ``query`` is a substring 430 | MATCH_SUBSTRING = 32 431 | #: Match items if all characters in ``query`` appear in the item in order 432 | MATCH_ALLCHARS = 64 433 | #: Combination of all other ``MATCH_*`` constants 434 | MATCH_ALL = 127 435 | 436 | 437 | #################################################################### 438 | # Used by `Workflow.check_update` 439 | #################################################################### 440 | 441 | # Number of days to wait between checking for updates to the workflow 442 | DEFAULT_UPDATE_FREQUENCY = 1 443 | 444 | 445 | #################################################################### 446 | # Lockfile and Keychain access errors 447 | #################################################################### 448 | 449 | class AcquisitionError(Exception): 450 | """Raised if a lock cannot be acquired.""" 451 | 452 | 453 | class KeychainError(Exception): 454 | """Raised for unknown Keychain errors. 455 | 456 | Raised by methods :meth:`Workflow.save_password`, 457 | :meth:`Workflow.get_password` and :meth:`Workflow.delete_password` 458 | when ``security`` CLI app returns an unknown error code. 459 | 460 | """ 461 | 462 | 463 | class PasswordNotFound(KeychainError): 464 | """Password not in Keychain. 465 | 466 | Raised by method :meth:`Workflow.get_password` when ``account`` 467 | is unknown to the Keychain. 468 | 469 | """ 470 | 471 | 472 | class PasswordExists(KeychainError): 473 | """Raised when trying to overwrite an existing account password. 474 | 475 | You should never receive this error: it is used internally 476 | by the :meth:`Workflow.save_password` method to know if it needs 477 | to delete the old password first (a Keychain implementation detail). 478 | 479 | """ 480 | 481 | 482 | #################################################################### 483 | # Helper functions 484 | #################################################################### 485 | 486 | def isascii(text): 487 | """Test if ``text`` contains only ASCII characters. 488 | 489 | :param text: text to test for ASCII-ness 490 | :type text: ``unicode`` 491 | :returns: ``True`` if ``text`` contains only ASCII characters 492 | :rtype: ``Boolean`` 493 | 494 | """ 495 | try: 496 | text.encode('ascii') 497 | except UnicodeEncodeError: 498 | return False 499 | return True 500 | 501 | 502 | #################################################################### 503 | # Implementation classes 504 | #################################################################### 505 | 506 | class SerializerManager(object): 507 | """Contains registered serializers. 508 | 509 | .. versionadded:: 1.8 510 | 511 | A configured instance of this class is available at 512 | :attr:`workflow.manager`. 513 | 514 | Use :meth:`register()` to register new (or replace 515 | existing) serializers, which you can specify by name when calling 516 | :class:`~workflow.Workflow` data storage methods. 517 | 518 | See :ref:`guide-serialization` and :ref:`guide-persistent-data` 519 | for further information. 520 | 521 | """ 522 | 523 | def __init__(self): 524 | """Create new SerializerManager object.""" 525 | self._serializers = {} 526 | 527 | def register(self, name, serializer): 528 | """Register ``serializer`` object under ``name``. 529 | 530 | Raises :class:`AttributeError` if ``serializer`` in invalid. 531 | 532 | .. note:: 533 | 534 | ``name`` will be used as the file extension of the saved files. 535 | 536 | :param name: Name to register ``serializer`` under 537 | :type name: ``unicode`` or ``str`` 538 | :param serializer: object with ``load()`` and ``dump()`` 539 | methods 540 | 541 | """ 542 | # Basic validation 543 | getattr(serializer, 'load') 544 | getattr(serializer, 'dump') 545 | 546 | self._serializers[name] = serializer 547 | 548 | def serializer(self, name): 549 | """Return serializer object for ``name``. 550 | 551 | :param name: Name of serializer to return 552 | :type name: ``unicode`` or ``str`` 553 | :returns: serializer object or ``None`` if no such serializer 554 | is registered. 555 | 556 | """ 557 | return self._serializers.get(name) 558 | 559 | def unregister(self, name): 560 | """Remove registered serializer with ``name``. 561 | 562 | Raises a :class:`ValueError` if there is no such registered 563 | serializer. 564 | 565 | :param name: Name of serializer to remove 566 | :type name: ``unicode`` or ``str`` 567 | :returns: serializer object 568 | 569 | """ 570 | if name not in self._serializers: 571 | raise ValueError('No such serializer registered : {0}'.format( 572 | name)) 573 | 574 | serializer = self._serializers[name] 575 | del self._serializers[name] 576 | 577 | return serializer 578 | 579 | @property 580 | def serializers(self): 581 | """Return names of registered serializers.""" 582 | return sorted(self._serializers.keys()) 583 | 584 | 585 | class JSONSerializer(object): 586 | """Wrapper around :mod:`json`. Sets ``indent`` and ``encoding``. 587 | 588 | .. versionadded:: 1.8 589 | 590 | Use this serializer if you need readable data files. JSON doesn't 591 | support Python objects as well as ``cPickle``/``pickle``, so be 592 | careful which data you try to serialize as JSON. 593 | 594 | """ 595 | 596 | @classmethod 597 | def load(cls, file_obj): 598 | """Load serialized object from open JSON file. 599 | 600 | .. versionadded:: 1.8 601 | 602 | :param file_obj: file handle 603 | :type file_obj: ``file`` object 604 | :returns: object loaded from JSON file 605 | :rtype: object 606 | 607 | """ 608 | return json.load(file_obj) 609 | 610 | @classmethod 611 | def dump(cls, obj, file_obj): 612 | """Serialize object ``obj`` to open JSON file. 613 | 614 | .. versionadded:: 1.8 615 | 616 | :param obj: Python object to serialize 617 | :type obj: JSON-serializable data structure 618 | :param file_obj: file handle 619 | :type file_obj: ``file`` object 620 | 621 | """ 622 | return json.dump(obj, file_obj, indent=2, encoding='utf-8') 623 | 624 | 625 | class CPickleSerializer(object): 626 | """Wrapper around :mod:`cPickle`. Sets ``protocol``. 627 | 628 | .. versionadded:: 1.8 629 | 630 | This is the default serializer and the best combination of speed and 631 | flexibility. 632 | 633 | """ 634 | 635 | @classmethod 636 | def load(cls, file_obj): 637 | """Load serialized object from open pickle file. 638 | 639 | .. versionadded:: 1.8 640 | 641 | :param file_obj: file handle 642 | :type file_obj: ``file`` object 643 | :returns: object loaded from pickle file 644 | :rtype: object 645 | 646 | """ 647 | return cPickle.load(file_obj) 648 | 649 | @classmethod 650 | def dump(cls, obj, file_obj): 651 | """Serialize object ``obj`` to open pickle file. 652 | 653 | .. versionadded:: 1.8 654 | 655 | :param obj: Python object to serialize 656 | :type obj: Python object 657 | :param file_obj: file handle 658 | :type file_obj: ``file`` object 659 | 660 | """ 661 | return cPickle.dump(obj, file_obj, protocol=-1) 662 | 663 | 664 | class PickleSerializer(object): 665 | """Wrapper around :mod:`pickle`. Sets ``protocol``. 666 | 667 | .. versionadded:: 1.8 668 | 669 | Use this serializer if you need to add custom pickling. 670 | 671 | """ 672 | 673 | @classmethod 674 | def load(cls, file_obj): 675 | """Load serialized object from open pickle file. 676 | 677 | .. versionadded:: 1.8 678 | 679 | :param file_obj: file handle 680 | :type file_obj: ``file`` object 681 | :returns: object loaded from pickle file 682 | :rtype: object 683 | 684 | """ 685 | return pickle.load(file_obj) 686 | 687 | @classmethod 688 | def dump(cls, obj, file_obj): 689 | """Serialize object ``obj`` to open pickle file. 690 | 691 | .. versionadded:: 1.8 692 | 693 | :param obj: Python object to serialize 694 | :type obj: Python object 695 | :param file_obj: file handle 696 | :type file_obj: ``file`` object 697 | 698 | """ 699 | return pickle.dump(obj, file_obj, protocol=-1) 700 | 701 | 702 | # Set up default manager and register built-in serializers 703 | manager = SerializerManager() 704 | manager.register('cpickle', CPickleSerializer) 705 | manager.register('pickle', PickleSerializer) 706 | manager.register('json', JSONSerializer) 707 | 708 | 709 | class Item(object): 710 | """Represents a feedback item for Alfred. 711 | 712 | Generates Alfred-compliant XML for a single item. 713 | 714 | You probably shouldn't use this class directly, but via 715 | :meth:`Workflow.add_item`. See :meth:`~Workflow.add_item` 716 | for details of arguments. 717 | 718 | """ 719 | 720 | def __init__(self, title, subtitle='', modifier_subtitles=None, 721 | arg=None, autocomplete=None, valid=False, uid=None, 722 | icon=None, icontype=None, type=None, largetext=None, 723 | copytext=None, quicklookurl=None): 724 | """Same arguments as :meth:`Workflow.add_item`.""" 725 | self.title = title 726 | self.subtitle = subtitle 727 | self.modifier_subtitles = modifier_subtitles or {} 728 | self.arg = arg 729 | self.autocomplete = autocomplete 730 | self.valid = valid 731 | self.uid = uid 732 | self.icon = icon 733 | self.icontype = icontype 734 | self.type = type 735 | self.largetext = largetext 736 | self.copytext = copytext 737 | self.quicklookurl = quicklookurl 738 | 739 | @property 740 | def elem(self): 741 | """Create and return feedback item for Alfred. 742 | 743 | :returns: :class:`ElementTree.Element ` 744 | instance for this :class:`Item` instance. 745 | 746 | """ 747 | # Attributes on element 748 | attr = {} 749 | if self.valid: 750 | attr['valid'] = 'yes' 751 | else: 752 | attr['valid'] = 'no' 753 | # Allow empty string for autocomplete. This is a useful value, 754 | # as TABing the result will revert the query back to just the 755 | # keyword 756 | if self.autocomplete is not None: 757 | attr['autocomplete'] = self.autocomplete 758 | 759 | # Optional attributes 760 | for name in ('uid', 'type'): 761 | value = getattr(self, name, None) 762 | if value: 763 | attr[name] = value 764 | 765 | root = ET.Element('item', attr) 766 | ET.SubElement(root, 'title').text = self.title 767 | ET.SubElement(root, 'subtitle').text = self.subtitle 768 | 769 | # Add modifier subtitles 770 | for mod in ('cmd', 'ctrl', 'alt', 'shift', 'fn'): 771 | if mod in self.modifier_subtitles: 772 | ET.SubElement(root, 'subtitle', 773 | {'mod': mod}).text = self.modifier_subtitles[mod] 774 | 775 | # Add arg as element instead of attribute on , as it's more 776 | # flexible (newlines aren't allowed in attributes) 777 | if self.arg: 778 | ET.SubElement(root, 'arg').text = self.arg 779 | 780 | # Add icon if there is one 781 | if self.icon: 782 | if self.icontype: 783 | attr = dict(type=self.icontype) 784 | else: 785 | attr = {} 786 | ET.SubElement(root, 'icon', attr).text = self.icon 787 | 788 | if self.largetext: 789 | ET.SubElement(root, 'text', 790 | {'type': 'largetype'}).text = self.largetext 791 | 792 | if self.copytext: 793 | ET.SubElement(root, 'text', 794 | {'type': 'copy'}).text = self.copytext 795 | 796 | if self.quicklookurl: 797 | ET.SubElement(root, 'quicklookurl').text = self.quicklookurl 798 | 799 | return root 800 | 801 | 802 | class LockFile(object): 803 | """Context manager to protect filepaths with lockfiles. 804 | 805 | .. versionadded:: 1.13 806 | 807 | Creates a lockfile alongside ``protected_path``. Other ``LockFile`` 808 | instances will refuse to lock the same path. 809 | 810 | >>> path = '/path/to/file' 811 | >>> with LockFile(path): 812 | >>> with open(path, 'wb') as fp: 813 | >>> fp.write(data) 814 | 815 | Args: 816 | protected_path (unicode): File to protect with a lockfile 817 | timeout (int, optional): Raises an :class:`AcquisitionError` 818 | if lock cannot be acquired within this number of seconds. 819 | If ``timeout`` is 0 (the default), wait forever. 820 | delay (float, optional): How often to check (in seconds) if 821 | lock has been released. 822 | 823 | """ 824 | 825 | def __init__(self, protected_path, timeout=0, delay=0.05): 826 | """Create new :class:`LockFile` object.""" 827 | self.lockfile = protected_path + '.lock' 828 | self.timeout = timeout 829 | self.delay = delay 830 | self._locked = False 831 | atexit.register(self.release) 832 | 833 | @property 834 | def locked(self): 835 | """`True` if file is locked by this instance.""" 836 | return self._locked 837 | 838 | def acquire(self, blocking=True): 839 | """Acquire the lock if possible. 840 | 841 | If the lock is in use and ``blocking`` is ``False``, return 842 | ``False``. 843 | 844 | Otherwise, check every `self.delay` seconds until it acquires 845 | lock or exceeds `self.timeout` and raises an `~AcquisitionError`. 846 | 847 | """ 848 | start = time.time() 849 | while True: 850 | 851 | self._validate_lockfile() 852 | 853 | try: 854 | fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR) 855 | with os.fdopen(fd, 'w') as fd: 856 | fd.write(str(os.getpid())) 857 | break 858 | except OSError as err: 859 | if err.errno != errno.EEXIST: # pragma: no cover 860 | raise 861 | 862 | if self.timeout and (time.time() - start) >= self.timeout: 863 | raise AcquisitionError('lock acquisition timed out') 864 | if not blocking: 865 | return False 866 | time.sleep(self.delay) 867 | 868 | self._locked = True 869 | return True 870 | 871 | def _validate_lockfile(self): 872 | """Check existence and validity of lockfile. 873 | 874 | If the lockfile exists, but contains an invalid PID 875 | or the PID of a non-existant process, it is removed. 876 | 877 | """ 878 | try: 879 | with open(self.lockfile) as fp: 880 | s = fp.read() 881 | except Exception: 882 | return 883 | 884 | try: 885 | pid = int(s) 886 | except ValueError: 887 | return self.release() 888 | 889 | from background import _process_exists 890 | if not _process_exists(pid): 891 | self.release() 892 | 893 | def release(self): 894 | """Release the lock by deleting `self.lockfile`.""" 895 | self._locked = False 896 | try: 897 | os.unlink(self.lockfile) 898 | except (OSError, IOError) as err: # pragma: no cover 899 | if err.errno != 2: 900 | raise err 901 | 902 | def __enter__(self): 903 | """Acquire lock.""" 904 | self.acquire() 905 | return self 906 | 907 | def __exit__(self, typ, value, traceback): 908 | """Release lock.""" 909 | self.release() 910 | 911 | def __del__(self): 912 | """Clear up `self.lockfile`.""" 913 | if self._locked: # pragma: no cover 914 | self.release() 915 | 916 | 917 | @contextmanager 918 | def atomic_writer(file_path, mode): 919 | """Atomic file writer. 920 | 921 | .. versionadded:: 1.12 922 | 923 | Context manager that ensures the file is only written if the write 924 | succeeds. The data is first written to a temporary file. 925 | 926 | :param file_path: path of file to write to. 927 | :type file_path: ``unicode`` 928 | :param mode: sames as for :func:`open` 929 | :type mode: string 930 | 931 | """ 932 | temp_suffix = '.aw.temp' 933 | temp_file_path = file_path + temp_suffix 934 | with open(temp_file_path, mode) as file_obj: 935 | try: 936 | yield file_obj 937 | os.rename(temp_file_path, file_path) 938 | finally: 939 | try: 940 | os.remove(temp_file_path) 941 | except (OSError, IOError): 942 | pass 943 | 944 | 945 | class uninterruptible(object): 946 | """Decorator that postpones SIGTERM until wrapped function returns. 947 | 948 | .. versionadded:: 1.12 949 | 950 | .. important:: This decorator is NOT thread-safe. 951 | 952 | As of version 2.7, Alfred allows Script Filters to be killed. If 953 | your workflow is killed in the middle of critical code (e.g. 954 | writing data to disk), this may corrupt your workflow's data. 955 | 956 | Use this decorator to wrap critical functions that *must* complete. 957 | If the script is killed while a wrapped function is executing, 958 | the SIGTERM will be caught and handled after your function has 959 | finished executing. 960 | 961 | Alfred-Workflow uses this internally to ensure its settings, data 962 | and cache writes complete. 963 | 964 | """ 965 | 966 | def __init__(self, func, class_name=''): 967 | """Decorate `func`.""" 968 | self.func = func 969 | self._caught_signal = None 970 | 971 | def signal_handler(self, signum, frame): 972 | """Called when process receives SIGTERM.""" 973 | self._caught_signal = (signum, frame) 974 | 975 | def __call__(self, *args, **kwargs): 976 | """Trap ``SIGTERM`` and call wrapped function.""" 977 | self._caught_signal = None 978 | # Register handler for SIGTERM, then call `self.func` 979 | self.old_signal_handler = signal.getsignal(signal.SIGTERM) 980 | signal.signal(signal.SIGTERM, self.signal_handler) 981 | 982 | self.func(*args, **kwargs) 983 | 984 | # Restore old signal handler 985 | signal.signal(signal.SIGTERM, self.old_signal_handler) 986 | 987 | # Handle any signal caught during execution 988 | if self._caught_signal is not None: 989 | signum, frame = self._caught_signal 990 | if callable(self.old_signal_handler): 991 | self.old_signal_handler(signum, frame) 992 | elif self.old_signal_handler == signal.SIG_DFL: 993 | sys.exit(0) 994 | 995 | def __get__(self, obj=None, klass=None): 996 | """Decorator API.""" 997 | return self.__class__(self.func.__get__(obj, klass), 998 | klass.__name__) 999 | 1000 | 1001 | class Settings(dict): 1002 | """A dictionary that saves itself when changed. 1003 | 1004 | Dictionary keys & values will be saved as a JSON file 1005 | at ``filepath``. If the file does not exist, the dictionary 1006 | (and settings file) will be initialised with ``defaults``. 1007 | 1008 | :param filepath: where to save the settings 1009 | :type filepath: :class:`unicode` 1010 | :param defaults: dict of default settings 1011 | :type defaults: :class:`dict` 1012 | 1013 | 1014 | An appropriate instance is provided by :class:`Workflow` instances at 1015 | :attr:`Workflow.settings`. 1016 | 1017 | """ 1018 | 1019 | def __init__(self, filepath, defaults=None): 1020 | """Create new :class:`Settings` object.""" 1021 | super(Settings, self).__init__() 1022 | self._filepath = filepath 1023 | self._nosave = False 1024 | self._original = {} 1025 | if os.path.exists(self._filepath): 1026 | self._load() 1027 | elif defaults: 1028 | for key, val in defaults.items(): 1029 | self[key] = val 1030 | self.save() # save default settings 1031 | 1032 | def _load(self): 1033 | """Load cached settings from JSON file `self._filepath`.""" 1034 | self._nosave = True 1035 | d = {} 1036 | with open(self._filepath, 'rb') as file_obj: 1037 | for key, value in json.load(file_obj, encoding='utf-8').items(): 1038 | d[key] = value 1039 | self.update(d) 1040 | self._original = deepcopy(d) 1041 | self._nosave = False 1042 | 1043 | @uninterruptible 1044 | def save(self): 1045 | """Save settings to JSON file specified in ``self._filepath``. 1046 | 1047 | If you're using this class via :attr:`Workflow.settings`, which 1048 | you probably are, ``self._filepath`` will be ``settings.json`` 1049 | in your workflow's data directory (see :attr:`~Workflow.datadir`). 1050 | """ 1051 | if self._nosave: 1052 | return 1053 | data = {} 1054 | data.update(self) 1055 | # for key, value in self.items(): 1056 | # data[key] = value 1057 | with LockFile(self._filepath): 1058 | with atomic_writer(self._filepath, 'wb') as file_obj: 1059 | json.dump(data, file_obj, sort_keys=True, indent=2, 1060 | encoding='utf-8') 1061 | 1062 | # dict methods 1063 | def __setitem__(self, key, value): 1064 | """Implement :class:`dict` interface.""" 1065 | if self._original.get(key) != value: 1066 | super(Settings, self).__setitem__(key, value) 1067 | self.save() 1068 | 1069 | def __delitem__(self, key): 1070 | """Implement :class:`dict` interface.""" 1071 | super(Settings, self).__delitem__(key) 1072 | self.save() 1073 | 1074 | def update(self, *args, **kwargs): 1075 | """Override :class:`dict` method to save on update.""" 1076 | super(Settings, self).update(*args, **kwargs) 1077 | self.save() 1078 | 1079 | def setdefault(self, key, value=None): 1080 | """Override :class:`dict` method to save on update.""" 1081 | ret = super(Settings, self).setdefault(key, value) 1082 | self.save() 1083 | return ret 1084 | 1085 | 1086 | class Workflow(object): 1087 | """The ``Workflow`` object is the main interface to Alfred-Workflow. 1088 | 1089 | It provides APIs for accessing the Alfred/workflow environment, 1090 | storing & caching data, using Keychain, and generating Script 1091 | Filter feedback. 1092 | 1093 | ``Workflow`` is compatible with both Alfred 2 and 3. The 1094 | :class:`~workflow.Workflow3` subclass provides additional, 1095 | Alfred 3-only features, such as workflow variables. 1096 | 1097 | :param default_settings: default workflow settings. If no settings file 1098 | exists, :class:`Workflow.settings` will be pre-populated with 1099 | ``default_settings``. 1100 | :type default_settings: :class:`dict` 1101 | :param update_settings: settings for updating your workflow from 1102 | GitHub releases. The only required key is ``github_slug``, 1103 | whose value must take the form of ``username/repo``. 1104 | If specified, ``Workflow`` will check the repo's releases 1105 | for updates. Your workflow must also have a semantic version 1106 | number. Please see the :ref:`User Manual ` and 1107 | `update API docs ` for more information. 1108 | :type update_settings: :class:`dict` 1109 | :param input_encoding: encoding of command line arguments. You 1110 | should probably leave this as the default (``utf-8``), which 1111 | is the encoding Alfred uses. 1112 | :type input_encoding: :class:`unicode` 1113 | :param normalization: normalisation to apply to CLI args. 1114 | See :meth:`Workflow.decode` for more details. 1115 | :type normalization: :class:`unicode` 1116 | :param capture_args: Capture and act on ``workflow:*`` arguments. See 1117 | :ref:`Magic arguments ` for details. 1118 | :type capture_args: :class:`Boolean` 1119 | :param libraries: sequence of paths to directories containing 1120 | libraries. These paths will be prepended to ``sys.path``. 1121 | :type libraries: :class:`tuple` or :class:`list` 1122 | :param help_url: URL to webpage where a user can ask for help with 1123 | the workflow, report bugs, etc. This could be the GitHub repo 1124 | or a page on AlfredForum.com. If your workflow throws an error, 1125 | this URL will be displayed in the log and Alfred's debugger. It can 1126 | also be opened directly in a web browser with the ``workflow:help`` 1127 | :ref:`magic argument `. 1128 | :type help_url: :class:`unicode` or :class:`str` 1129 | 1130 | """ 1131 | 1132 | # Which class to use to generate feedback items. You probably 1133 | # won't want to change this 1134 | item_class = Item 1135 | 1136 | def __init__(self, default_settings=None, update_settings=None, 1137 | input_encoding='utf-8', normalization='NFC', 1138 | capture_args=True, libraries=None, 1139 | help_url=None): 1140 | """Create new :class:`Workflow` object.""" 1141 | self._default_settings = default_settings or {} 1142 | self._update_settings = update_settings or {} 1143 | self._input_encoding = input_encoding 1144 | self._normalizsation = normalization 1145 | self._capture_args = capture_args 1146 | self.help_url = help_url 1147 | self._workflowdir = None 1148 | self._settings_path = None 1149 | self._settings = None 1150 | self._bundleid = None 1151 | self._debugging = None 1152 | self._name = None 1153 | self._cache_serializer = 'cpickle' 1154 | self._data_serializer = 'cpickle' 1155 | self._info = None 1156 | self._info_loaded = False 1157 | self._logger = None 1158 | self._items = [] 1159 | self._alfred_env = None 1160 | # Version number of the workflow 1161 | self._version = UNSET 1162 | # Version from last workflow run 1163 | self._last_version_run = UNSET 1164 | # Cache for regex patterns created for filter keys 1165 | self._search_pattern_cache = {} 1166 | # Magic arguments 1167 | #: The prefix for all magic arguments. Default is ``workflow:`` 1168 | self.magic_prefix = 'workflow:' 1169 | #: Mapping of available magic arguments. The built-in magic 1170 | #: arguments are registered by default. To add your own magic arguments 1171 | #: (or override built-ins), add a key:value pair where the key is 1172 | #: what the user should enter (prefixed with :attr:`magic_prefix`) 1173 | #: and the value is a callable that will be called when the argument 1174 | #: is entered. If you would like to display a message in Alfred, the 1175 | #: function should return a ``unicode`` string. 1176 | #: 1177 | #: By default, the magic arguments documented 1178 | #: :ref:`here ` are registered. 1179 | self.magic_arguments = {} 1180 | 1181 | self._register_default_magic() 1182 | 1183 | if libraries: 1184 | sys.path = libraries + sys.path 1185 | 1186 | #################################################################### 1187 | # API methods 1188 | #################################################################### 1189 | 1190 | # info.plist contents and alfred_* environment variables ---------- 1191 | 1192 | @property 1193 | def alfred_version(self): 1194 | """Alfred version as :class:`~workflow.update.Version` object.""" 1195 | from update import Version 1196 | return Version(self.alfred_env.get('version')) 1197 | 1198 | @property 1199 | def alfred_env(self): 1200 | """Dict of Alfred's environmental variables minus ``alfred_`` prefix. 1201 | 1202 | .. versionadded:: 1.7 1203 | 1204 | The variables Alfred 2.4+ exports are: 1205 | 1206 | ============================ ========================================= 1207 | Variable Description 1208 | ============================ ========================================= 1209 | debug Set to ``1`` if Alfred's debugger is 1210 | open, otherwise unset. 1211 | preferences Path to Alfred.alfredpreferences 1212 | (where your workflows and settings are 1213 | stored). 1214 | preferences_localhash Machine-specific preferences are stored 1215 | in ``Alfred.alfredpreferences/preferences/local/`` 1216 | (see ``preferences`` above for 1217 | the path to ``Alfred.alfredpreferences``) 1218 | theme ID of selected theme 1219 | theme_background Background colour of selected theme in 1220 | format ``rgba(r,g,b,a)`` 1221 | theme_subtext Show result subtext. 1222 | ``0`` = Always, 1223 | ``1`` = Alternative actions only, 1224 | ``2`` = Selected result only, 1225 | ``3`` = Never 1226 | version Alfred version number, e.g. ``'2.4'`` 1227 | version_build Alfred build number, e.g. ``277`` 1228 | workflow_bundleid Bundle ID, e.g. 1229 | ``net.deanishe.alfred-mailto`` 1230 | workflow_cache Path to workflow's cache directory 1231 | workflow_data Path to workflow's data directory 1232 | workflow_name Name of current workflow 1233 | workflow_uid UID of workflow 1234 | workflow_version The version number specified in the 1235 | workflow configuration sheet/info.plist 1236 | ============================ ========================================= 1237 | 1238 | **Note:** all values are Unicode strings except ``version_build`` and 1239 | ``theme_subtext``, which are integers. 1240 | 1241 | :returns: ``dict`` of Alfred's environmental variables without the 1242 | ``alfred_`` prefix, e.g. ``preferences``, ``workflow_data``. 1243 | 1244 | """ 1245 | if self._alfred_env is not None: 1246 | return self._alfred_env 1247 | 1248 | data = {} 1249 | 1250 | for key in ( 1251 | 'alfred_debug', 1252 | 'alfred_preferences', 1253 | 'alfred_preferences_localhash', 1254 | 'alfred_theme', 1255 | 'alfred_theme_background', 1256 | 'alfred_theme_subtext', 1257 | 'alfred_version', 1258 | 'alfred_version_build', 1259 | 'alfred_workflow_bundleid', 1260 | 'alfred_workflow_cache', 1261 | 'alfred_workflow_data', 1262 | 'alfred_workflow_name', 1263 | 'alfred_workflow_uid', 1264 | 'alfred_workflow_version'): 1265 | 1266 | value = os.getenv(key) 1267 | 1268 | if isinstance(value, str): 1269 | if key in ('alfred_debug', 'alfred_version_build', 1270 | 'alfred_theme_subtext'): 1271 | value = int(value) 1272 | else: 1273 | value = self.decode(value) 1274 | 1275 | data[key[7:]] = value 1276 | 1277 | self._alfred_env = data 1278 | 1279 | return self._alfred_env 1280 | 1281 | @property 1282 | def info(self): 1283 | """:class:`dict` of ``info.plist`` contents.""" 1284 | if not self._info_loaded: 1285 | self._load_info_plist() 1286 | return self._info 1287 | 1288 | @property 1289 | def bundleid(self): 1290 | """Workflow bundle ID from environmental vars or ``info.plist``. 1291 | 1292 | :returns: bundle ID 1293 | :rtype: ``unicode`` 1294 | 1295 | """ 1296 | if not self._bundleid: 1297 | if self.alfred_env.get('workflow_bundleid'): 1298 | self._bundleid = self.alfred_env.get('workflow_bundleid') 1299 | else: 1300 | self._bundleid = unicode(self.info['bundleid'], 'utf-8') 1301 | 1302 | return self._bundleid 1303 | 1304 | @property 1305 | def debugging(self): 1306 | """Whether Alfred's debugger is open. 1307 | 1308 | :returns: ``True`` if Alfred's debugger is open. 1309 | :rtype: ``bool`` 1310 | 1311 | """ 1312 | if self._debugging is None: 1313 | if self.alfred_env.get('debug') == 1: 1314 | self._debugging = True 1315 | else: 1316 | self._debugging = False 1317 | return self._debugging 1318 | 1319 | @property 1320 | def name(self): 1321 | """Workflow name from Alfred's environmental vars or ``info.plist``. 1322 | 1323 | :returns: workflow name 1324 | :rtype: ``unicode`` 1325 | 1326 | """ 1327 | if not self._name: 1328 | if self.alfred_env.get('workflow_name'): 1329 | self._name = self.decode(self.alfred_env.get('workflow_name')) 1330 | else: 1331 | self._name = self.decode(self.info['name']) 1332 | 1333 | return self._name 1334 | 1335 | @property 1336 | def version(self): 1337 | """Return the version of the workflow. 1338 | 1339 | .. versionadded:: 1.9.10 1340 | 1341 | Get the workflow version from environment variable, 1342 | the ``update_settings`` dict passed on 1343 | instantiation, the ``version`` file located in the workflow's 1344 | root directory or ``info.plist``. Return ``None`` if none 1345 | exists or :class:`ValueError` if the version number is invalid 1346 | (i.e. not semantic). 1347 | 1348 | :returns: Version of the workflow (not Alfred-Workflow) 1349 | :rtype: :class:`~workflow.update.Version` object 1350 | 1351 | """ 1352 | if self._version is UNSET: 1353 | 1354 | version = None 1355 | # environment variable has priority 1356 | if self.alfred_env.get('workflow_version'): 1357 | version = self.alfred_env['workflow_version'] 1358 | 1359 | # Try `update_settings` 1360 | elif self._update_settings: 1361 | version = self._update_settings.get('version') 1362 | 1363 | # `version` file 1364 | if not version: 1365 | filepath = self.workflowfile('version') 1366 | 1367 | if os.path.exists(filepath): 1368 | with open(filepath, 'rb') as fileobj: 1369 | version = fileobj.read() 1370 | 1371 | # info.plist 1372 | if not version: 1373 | version = self.info.get('version') 1374 | 1375 | if version: 1376 | from update import Version 1377 | version = Version(version) 1378 | 1379 | self._version = version 1380 | 1381 | return self._version 1382 | 1383 | # Workflow utility methods ----------------------------------------- 1384 | 1385 | @property 1386 | def args(self): 1387 | """Return command line args as normalised unicode. 1388 | 1389 | Args are decoded and normalised via :meth:`~Workflow.decode`. 1390 | 1391 | The encoding and normalisation are the ``input_encoding`` and 1392 | ``normalization`` arguments passed to :class:`Workflow` (``UTF-8`` 1393 | and ``NFC`` are the defaults). 1394 | 1395 | If :class:`Workflow` is called with ``capture_args=True`` 1396 | (the default), :class:`Workflow` will look for certain 1397 | ``workflow:*`` args and, if found, perform the corresponding 1398 | actions and exit the workflow. 1399 | 1400 | See :ref:`Magic arguments ` for details. 1401 | 1402 | """ 1403 | msg = None 1404 | args = [self.decode(arg) for arg in sys.argv[1:]] 1405 | 1406 | # Handle magic args 1407 | if len(args) and self._capture_args: 1408 | for name in self.magic_arguments: 1409 | key = '{0}{1}'.format(self.magic_prefix, name) 1410 | if key in args: 1411 | msg = self.magic_arguments[name]() 1412 | 1413 | if msg: 1414 | self.logger.debug(msg) 1415 | if not sys.stdout.isatty(): # Show message in Alfred 1416 | self.add_item(msg, valid=False, icon=ICON_INFO) 1417 | self.send_feedback() 1418 | sys.exit(0) 1419 | return args 1420 | 1421 | @property 1422 | def cachedir(self): 1423 | """Path to workflow's cache directory. 1424 | 1425 | The cache directory is a subdirectory of Alfred's own cache directory 1426 | in ``~/Library/Caches``. The full path is: 1427 | 1428 | ``~/Library/Caches/com.runningwithcrayons.Alfred-X/Workflow Data/`` 1429 | 1430 | ``Alfred-X`` may be ``Alfred-2`` or ``Alfred-3``. 1431 | 1432 | :returns: full path to workflow's cache directory 1433 | :rtype: ``unicode`` 1434 | 1435 | """ 1436 | if self.alfred_env.get('workflow_cache'): 1437 | dirpath = self.alfred_env.get('workflow_cache') 1438 | 1439 | else: 1440 | dirpath = self._default_cachedir 1441 | 1442 | return self._create(dirpath) 1443 | 1444 | @property 1445 | def _default_cachedir(self): 1446 | """Alfred 2's default cache directory.""" 1447 | return os.path.join( 1448 | os.path.expanduser( 1449 | '~/Library/Caches/com.runningwithcrayons.Alfred-2/' 1450 | 'Workflow Data/'), 1451 | self.bundleid) 1452 | 1453 | @property 1454 | def datadir(self): 1455 | """Path to workflow's data directory. 1456 | 1457 | The data directory is a subdirectory of Alfred's own data directory in 1458 | ``~/Library/Application Support``. The full path is: 1459 | 1460 | ``~/Library/Application Support/Alfred 2/Workflow Data/`` 1461 | 1462 | :returns: full path to workflow data directory 1463 | :rtype: ``unicode`` 1464 | 1465 | """ 1466 | if self.alfred_env.get('workflow_data'): 1467 | dirpath = self.alfred_env.get('workflow_data') 1468 | 1469 | else: 1470 | dirpath = self._default_datadir 1471 | 1472 | return self._create(dirpath) 1473 | 1474 | @property 1475 | def _default_datadir(self): 1476 | """Alfred 2's default data directory.""" 1477 | return os.path.join(os.path.expanduser( 1478 | '~/Library/Application Support/Alfred 2/Workflow Data/'), 1479 | self.bundleid) 1480 | 1481 | @property 1482 | def workflowdir(self): 1483 | """Path to workflow's root directory (where ``info.plist`` is). 1484 | 1485 | :returns: full path to workflow root directory 1486 | :rtype: ``unicode`` 1487 | 1488 | """ 1489 | if not self._workflowdir: 1490 | # Try the working directory first, then the directory 1491 | # the library is in. CWD will be the workflow root if 1492 | # a workflow is being run in Alfred 1493 | candidates = [ 1494 | os.path.abspath(os.getcwdu()), 1495 | os.path.dirname(os.path.abspath(os.path.dirname(__file__)))] 1496 | 1497 | # climb the directory tree until we find `info.plist` 1498 | for dirpath in candidates: 1499 | 1500 | # Ensure directory path is Unicode 1501 | dirpath = self.decode(dirpath) 1502 | 1503 | while True: 1504 | if os.path.exists(os.path.join(dirpath, 'info.plist')): 1505 | self._workflowdir = dirpath 1506 | break 1507 | 1508 | elif dirpath == '/': 1509 | # no `info.plist` found 1510 | break 1511 | 1512 | # Check the parent directory 1513 | dirpath = os.path.dirname(dirpath) 1514 | 1515 | # No need to check other candidates 1516 | if self._workflowdir: 1517 | break 1518 | 1519 | if not self._workflowdir: 1520 | raise IOError("'info.plist' not found in directory tree") 1521 | 1522 | return self._workflowdir 1523 | 1524 | def cachefile(self, filename): 1525 | """Path to ``filename`` in workflow's cache directory. 1526 | 1527 | Return absolute path to ``filename`` within your workflow's 1528 | :attr:`cache directory `. 1529 | 1530 | :param filename: basename of file 1531 | :type filename: ``unicode`` 1532 | :returns: full path to file within cache directory 1533 | :rtype: ``unicode`` 1534 | 1535 | """ 1536 | return os.path.join(self.cachedir, filename) 1537 | 1538 | def datafile(self, filename): 1539 | """Path to ``filename`` in workflow's data directory. 1540 | 1541 | Return absolute path to ``filename`` within your workflow's 1542 | :attr:`data directory `. 1543 | 1544 | :param filename: basename of file 1545 | :type filename: ``unicode`` 1546 | :returns: full path to file within data directory 1547 | :rtype: ``unicode`` 1548 | 1549 | """ 1550 | return os.path.join(self.datadir, filename) 1551 | 1552 | def workflowfile(self, filename): 1553 | """Return full path to ``filename`` in workflow's root directory. 1554 | 1555 | :param filename: basename of file 1556 | :type filename: ``unicode`` 1557 | :returns: full path to file within data directory 1558 | :rtype: ``unicode`` 1559 | 1560 | """ 1561 | return os.path.join(self.workflowdir, filename) 1562 | 1563 | @property 1564 | def logfile(self): 1565 | """Path to logfile. 1566 | 1567 | :returns: path to logfile within workflow's cache directory 1568 | :rtype: ``unicode`` 1569 | 1570 | """ 1571 | return self.cachefile('%s.log' % self.bundleid) 1572 | 1573 | @property 1574 | def logger(self): 1575 | """Logger that logs to both console and a log file. 1576 | 1577 | If Alfred's debugger is open, log level will be ``DEBUG``, 1578 | else it will be ``INFO``. 1579 | 1580 | Use :meth:`open_log` to open the log file in Console. 1581 | 1582 | :returns: an initialised :class:`~logging.Logger` 1583 | 1584 | """ 1585 | if self._logger: 1586 | return self._logger 1587 | 1588 | # Initialise new logger and optionally handlers 1589 | logger = logging.getLogger('workflow') 1590 | 1591 | if not len(logger.handlers): # Only add one set of handlers 1592 | 1593 | fmt = logging.Formatter( 1594 | '%(asctime)s %(filename)s:%(lineno)s' 1595 | ' %(levelname)-8s %(message)s', 1596 | datefmt='%H:%M:%S') 1597 | 1598 | logfile = logging.handlers.RotatingFileHandler( 1599 | self.logfile, 1600 | maxBytes=1024 * 1024, 1601 | backupCount=1) 1602 | logfile.setFormatter(fmt) 1603 | logger.addHandler(logfile) 1604 | 1605 | console = logging.StreamHandler() 1606 | console.setFormatter(fmt) 1607 | logger.addHandler(console) 1608 | 1609 | if self.debugging: 1610 | logger.setLevel(logging.DEBUG) 1611 | else: 1612 | logger.setLevel(logging.INFO) 1613 | 1614 | self._logger = logger 1615 | 1616 | return self._logger 1617 | 1618 | @logger.setter 1619 | def logger(self, logger): 1620 | """Set a custom logger. 1621 | 1622 | :param logger: The logger to use 1623 | :type logger: `~logging.Logger` instance 1624 | 1625 | """ 1626 | self._logger = logger 1627 | 1628 | @property 1629 | def settings_path(self): 1630 | """Path to settings file within workflow's data directory. 1631 | 1632 | :returns: path to ``settings.json`` file 1633 | :rtype: ``unicode`` 1634 | 1635 | """ 1636 | if not self._settings_path: 1637 | self._settings_path = self.datafile('settings.json') 1638 | return self._settings_path 1639 | 1640 | @property 1641 | def settings(self): 1642 | """Return a dictionary subclass that saves itself when changed. 1643 | 1644 | See :ref:`guide-settings` in the :ref:`user-manual` for more 1645 | information on how to use :attr:`settings` and **important 1646 | limitations** on what it can do. 1647 | 1648 | :returns: :class:`~workflow.workflow.Settings` instance 1649 | initialised from the data in JSON file at 1650 | :attr:`settings_path` or if that doesn't exist, with the 1651 | ``default_settings`` :class:`dict` passed to 1652 | :class:`Workflow` on instantiation. 1653 | :rtype: :class:`~workflow.workflow.Settings` instance 1654 | 1655 | """ 1656 | if not self._settings: 1657 | self.logger.debug('reading settings from %s', self.settings_path) 1658 | self._settings = Settings(self.settings_path, 1659 | self._default_settings) 1660 | return self._settings 1661 | 1662 | @property 1663 | def cache_serializer(self): 1664 | """Name of default cache serializer. 1665 | 1666 | .. versionadded:: 1.8 1667 | 1668 | This serializer is used by :meth:`cache_data()` and 1669 | :meth:`cached_data()` 1670 | 1671 | See :class:`SerializerManager` for details. 1672 | 1673 | :returns: serializer name 1674 | :rtype: ``unicode`` 1675 | 1676 | """ 1677 | return self._cache_serializer 1678 | 1679 | @cache_serializer.setter 1680 | def cache_serializer(self, serializer_name): 1681 | """Set the default cache serialization format. 1682 | 1683 | .. versionadded:: 1.8 1684 | 1685 | This serializer is used by :meth:`cache_data()` and 1686 | :meth:`cached_data()` 1687 | 1688 | The specified serializer must already by registered with the 1689 | :class:`SerializerManager` at `~workflow.workflow.manager`, 1690 | otherwise a :class:`ValueError` will be raised. 1691 | 1692 | :param serializer_name: Name of default serializer to use. 1693 | :type serializer_name: 1694 | 1695 | """ 1696 | if manager.serializer(serializer_name) is None: 1697 | raise ValueError( 1698 | 'Unknown serializer : `{0}`. Register your serializer ' 1699 | 'with `manager` first.'.format(serializer_name)) 1700 | 1701 | self.logger.debug('default cache serializer: %s', serializer_name) 1702 | 1703 | self._cache_serializer = serializer_name 1704 | 1705 | @property 1706 | def data_serializer(self): 1707 | """Name of default data serializer. 1708 | 1709 | .. versionadded:: 1.8 1710 | 1711 | This serializer is used by :meth:`store_data()` and 1712 | :meth:`stored_data()` 1713 | 1714 | See :class:`SerializerManager` for details. 1715 | 1716 | :returns: serializer name 1717 | :rtype: ``unicode`` 1718 | 1719 | """ 1720 | return self._data_serializer 1721 | 1722 | @data_serializer.setter 1723 | def data_serializer(self, serializer_name): 1724 | """Set the default cache serialization format. 1725 | 1726 | .. versionadded:: 1.8 1727 | 1728 | This serializer is used by :meth:`store_data()` and 1729 | :meth:`stored_data()` 1730 | 1731 | The specified serializer must already by registered with the 1732 | :class:`SerializerManager` at `~workflow.workflow.manager`, 1733 | otherwise a :class:`ValueError` will be raised. 1734 | 1735 | :param serializer_name: Name of serializer to use by default. 1736 | 1737 | """ 1738 | if manager.serializer(serializer_name) is None: 1739 | raise ValueError( 1740 | 'Unknown serializer : `{0}`. Register your serializer ' 1741 | 'with `manager` first.'.format(serializer_name)) 1742 | 1743 | self.logger.debug('default data serializer: %s', serializer_name) 1744 | 1745 | self._data_serializer = serializer_name 1746 | 1747 | def stored_data(self, name): 1748 | """Retrieve data from data directory. 1749 | 1750 | Returns ``None`` if there are no data stored under ``name``. 1751 | 1752 | .. versionadded:: 1.8 1753 | 1754 | :param name: name of datastore 1755 | 1756 | """ 1757 | metadata_path = self.datafile('.{0}.alfred-workflow'.format(name)) 1758 | 1759 | if not os.path.exists(metadata_path): 1760 | self.logger.debug('no data stored for `%s`', name) 1761 | return None 1762 | 1763 | with open(metadata_path, 'rb') as file_obj: 1764 | serializer_name = file_obj.read().strip() 1765 | 1766 | serializer = manager.serializer(serializer_name) 1767 | 1768 | if serializer is None: 1769 | raise ValueError( 1770 | 'Unknown serializer `{0}`. Register a corresponding ' 1771 | 'serializer with `manager.register()` ' 1772 | 'to load this data.'.format(serializer_name)) 1773 | 1774 | self.logger.debug('data `%s` stored as `%s`', name, serializer_name) 1775 | 1776 | filename = '{0}.{1}'.format(name, serializer_name) 1777 | data_path = self.datafile(filename) 1778 | 1779 | if not os.path.exists(data_path): 1780 | self.logger.debug('no data stored: %s', name) 1781 | if os.path.exists(metadata_path): 1782 | os.unlink(metadata_path) 1783 | 1784 | return None 1785 | 1786 | with open(data_path, 'rb') as file_obj: 1787 | data = serializer.load(file_obj) 1788 | 1789 | self.logger.debug('stored data loaded: %s', data_path) 1790 | 1791 | return data 1792 | 1793 | def store_data(self, name, data, serializer=None): 1794 | """Save data to data directory. 1795 | 1796 | .. versionadded:: 1.8 1797 | 1798 | If ``data`` is ``None``, the datastore will be deleted. 1799 | 1800 | Note that the datastore does NOT support mutliple threads. 1801 | 1802 | :param name: name of datastore 1803 | :param data: object(s) to store. **Note:** some serializers 1804 | can only handled certain types of data. 1805 | :param serializer: name of serializer to use. If no serializer 1806 | is specified, the default will be used. See 1807 | :class:`SerializerManager` for more information. 1808 | :returns: data in datastore or ``None`` 1809 | 1810 | """ 1811 | # Ensure deletion is not interrupted by SIGTERM 1812 | @uninterruptible 1813 | def delete_paths(paths): 1814 | """Clear one or more data stores""" 1815 | for path in paths: 1816 | if os.path.exists(path): 1817 | os.unlink(path) 1818 | self.logger.debug('deleted data file: %s', path) 1819 | 1820 | serializer_name = serializer or self.data_serializer 1821 | 1822 | # In order for `stored_data()` to be able to load data stored with 1823 | # an arbitrary serializer, yet still have meaningful file extensions, 1824 | # the format (i.e. extension) is saved to an accompanying file 1825 | metadata_path = self.datafile('.{0}.alfred-workflow'.format(name)) 1826 | filename = '{0}.{1}'.format(name, serializer_name) 1827 | data_path = self.datafile(filename) 1828 | 1829 | if data_path == self.settings_path: 1830 | raise ValueError( 1831 | 'Cannot save data to' + 1832 | '`{0}` with format `{1}`. '.format(name, serializer_name) + 1833 | "This would overwrite Alfred-Workflow's settings file.") 1834 | 1835 | serializer = manager.serializer(serializer_name) 1836 | 1837 | if serializer is None: 1838 | raise ValueError( 1839 | 'Invalid serializer `{0}`. Register your serializer with ' 1840 | '`manager.register()` first.'.format(serializer_name)) 1841 | 1842 | if data is None: # Delete cached data 1843 | delete_paths((metadata_path, data_path)) 1844 | return 1845 | 1846 | # Ensure write is not interrupted by SIGTERM 1847 | @uninterruptible 1848 | def _store(): 1849 | # Save file extension 1850 | with atomic_writer(metadata_path, 'wb') as file_obj: 1851 | file_obj.write(serializer_name) 1852 | 1853 | with atomic_writer(data_path, 'wb') as file_obj: 1854 | serializer.dump(data, file_obj) 1855 | 1856 | _store() 1857 | 1858 | self.logger.debug('saved data: %s', data_path) 1859 | 1860 | def cached_data(self, name, data_func=None, max_age=60): 1861 | """Return cached data if younger than ``max_age`` seconds. 1862 | 1863 | Retrieve data from cache or re-generate and re-cache data if 1864 | stale/non-existant. If ``max_age`` is 0, return cached data no 1865 | matter how old. 1866 | 1867 | :param name: name of datastore 1868 | :param data_func: function to (re-)generate data. 1869 | :type data_func: ``callable`` 1870 | :param max_age: maximum age of cached data in seconds 1871 | :type max_age: ``int`` 1872 | :returns: cached data, return value of ``data_func`` or ``None`` 1873 | if ``data_func`` is not set 1874 | 1875 | """ 1876 | serializer = manager.serializer(self.cache_serializer) 1877 | 1878 | cache_path = self.cachefile('%s.%s' % (name, self.cache_serializer)) 1879 | age = self.cached_data_age(name) 1880 | 1881 | if (age < max_age or max_age == 0) and os.path.exists(cache_path): 1882 | 1883 | with open(cache_path, 'rb') as file_obj: 1884 | self.logger.debug('loading cached data: %s', cache_path) 1885 | return serializer.load(file_obj) 1886 | 1887 | if not data_func: 1888 | return None 1889 | 1890 | data = data_func() 1891 | self.cache_data(name, data) 1892 | 1893 | return data 1894 | 1895 | def cache_data(self, name, data): 1896 | """Save ``data`` to cache under ``name``. 1897 | 1898 | If ``data`` is ``None``, the corresponding cache file will be 1899 | deleted. 1900 | 1901 | :param name: name of datastore 1902 | :param data: data to store. This may be any object supported by 1903 | the cache serializer 1904 | 1905 | """ 1906 | serializer = manager.serializer(self.cache_serializer) 1907 | 1908 | cache_path = self.cachefile('%s.%s' % (name, self.cache_serializer)) 1909 | 1910 | if data is None: 1911 | if os.path.exists(cache_path): 1912 | os.unlink(cache_path) 1913 | self.logger.debug('deleted cache file: %s', cache_path) 1914 | return 1915 | 1916 | with atomic_writer(cache_path, 'wb') as file_obj: 1917 | serializer.dump(data, file_obj) 1918 | 1919 | self.logger.debug('cached data: %s', cache_path) 1920 | 1921 | def cached_data_fresh(self, name, max_age): 1922 | """Whether cache `name` is less than `max_age` seconds old. 1923 | 1924 | :param name: name of datastore 1925 | :param max_age: maximum age of data in seconds 1926 | :type max_age: ``int`` 1927 | :returns: ``True`` if data is less than ``max_age`` old, else 1928 | ``False`` 1929 | 1930 | """ 1931 | age = self.cached_data_age(name) 1932 | 1933 | if not age: 1934 | return False 1935 | 1936 | return age < max_age 1937 | 1938 | def cached_data_age(self, name): 1939 | """Return age in seconds of cache `name` or 0 if cache doesn't exist. 1940 | 1941 | :param name: name of datastore 1942 | :type name: ``unicode`` 1943 | :returns: age of datastore in seconds 1944 | :rtype: ``int`` 1945 | 1946 | """ 1947 | cache_path = self.cachefile('%s.%s' % (name, self.cache_serializer)) 1948 | 1949 | if not os.path.exists(cache_path): 1950 | return 0 1951 | 1952 | return time.time() - os.stat(cache_path).st_mtime 1953 | 1954 | def filter(self, query, items, key=lambda x: x, ascending=False, 1955 | include_score=False, min_score=0, max_results=0, 1956 | match_on=MATCH_ALL, fold_diacritics=True): 1957 | """Fuzzy search filter. Returns list of ``items`` that match ``query``. 1958 | 1959 | ``query`` is case-insensitive. Any item that does not contain the 1960 | entirety of ``query`` is rejected. 1961 | 1962 | .. warning:: 1963 | 1964 | If ``query`` is an empty string or contains only whitespace, 1965 | a :class:`ValueError` will be raised. 1966 | 1967 | :param query: query to test items against 1968 | :type query: ``unicode`` 1969 | :param items: iterable of items to test 1970 | :type items: ``list`` or ``tuple`` 1971 | :param key: function to get comparison key from ``items``. 1972 | Must return a ``unicode`` string. The default simply returns 1973 | the item. 1974 | :type key: ``callable`` 1975 | :param ascending: set to ``True`` to get worst matches first 1976 | :type ascending: ``Boolean`` 1977 | :param include_score: Useful for debugging the scoring algorithm. 1978 | If ``True``, results will be a list of tuples 1979 | ``(item, score, rule)``. 1980 | :type include_score: ``Boolean`` 1981 | :param min_score: If non-zero, ignore results with a score lower 1982 | than this. 1983 | :type min_score: ``int`` 1984 | :param max_results: If non-zero, prune results list to this length. 1985 | :type max_results: ``int`` 1986 | :param match_on: Filter option flags. Bitwise-combined list of 1987 | ``MATCH_*`` constants (see below). 1988 | :type match_on: ``int`` 1989 | :param fold_diacritics: Convert search keys to ASCII-only 1990 | characters if ``query`` only contains ASCII characters. 1991 | :type fold_diacritics: ``Boolean`` 1992 | :returns: list of ``items`` matching ``query`` or list of 1993 | ``(item, score, rule)`` `tuples` if ``include_score`` is ``True``. 1994 | ``rule`` is the ``MATCH_*`` rule that matched the item. 1995 | :rtype: ``list`` 1996 | 1997 | **Matching rules** 1998 | 1999 | By default, :meth:`filter` uses all of the following flags (i.e. 2000 | :const:`MATCH_ALL`). The tests are always run in the given order: 2001 | 2002 | 1. :const:`MATCH_STARTSWITH` 2003 | Item search key starts with ``query`` (case-insensitive). 2004 | 2. :const:`MATCH_CAPITALS` 2005 | The list of capital letters in item search key starts with 2006 | ``query`` (``query`` may be lower-case). E.g., ``of`` 2007 | would match ``OmniFocus``, ``gc`` would match ``Google Chrome``. 2008 | 3. :const:`MATCH_ATOM` 2009 | Search key is split into "atoms" on non-word characters 2010 | (.,-,' etc.). Matches if ``query`` is one of these atoms 2011 | (case-insensitive). 2012 | 4. :const:`MATCH_INITIALS_STARTSWITH` 2013 | Initials are the first characters of the above-described 2014 | "atoms" (case-insensitive). 2015 | 5. :const:`MATCH_INITIALS_CONTAIN` 2016 | ``query`` is a substring of the above-described initials. 2017 | 6. :const:`MATCH_INITIALS` 2018 | Combination of (4) and (5). 2019 | 7. :const:`MATCH_SUBSTRING` 2020 | ``query`` is a substring of item search key (case-insensitive). 2021 | 8. :const:`MATCH_ALLCHARS` 2022 | All characters in ``query`` appear in item search key in 2023 | the same order (case-insensitive). 2024 | 9. :const:`MATCH_ALL` 2025 | Combination of all the above. 2026 | 2027 | 2028 | :const:`MATCH_ALLCHARS` is considerably slower than the other 2029 | tests and provides much less accurate results. 2030 | 2031 | **Examples:** 2032 | 2033 | To ignore :const:`MATCH_ALLCHARS` (tends to provide the worst 2034 | matches and is expensive to run), use 2035 | ``match_on=MATCH_ALL ^ MATCH_ALLCHARS``. 2036 | 2037 | To match only on capitals, use ``match_on=MATCH_CAPITALS``. 2038 | 2039 | To match only on startswith and substring, use 2040 | ``match_on=MATCH_STARTSWITH | MATCH_SUBSTRING``. 2041 | 2042 | **Diacritic folding** 2043 | 2044 | .. versionadded:: 1.3 2045 | 2046 | If ``fold_diacritics`` is ``True`` (the default), and ``query`` 2047 | contains only ASCII characters, non-ASCII characters in search keys 2048 | will be converted to ASCII equivalents (e.g. **ü** -> **u**, 2049 | **ß** -> **ss**, **é** -> **e**). 2050 | 2051 | See :const:`ASCII_REPLACEMENTS` for all replacements. 2052 | 2053 | If ``query`` contains non-ASCII characters, search keys will not be 2054 | altered. 2055 | 2056 | """ 2057 | if not query: 2058 | raise ValueError('Empty `query`') 2059 | 2060 | # Remove preceding/trailing spaces 2061 | query = query.strip() 2062 | 2063 | if not query: 2064 | raise ValueError('`query` contains only whitespace') 2065 | 2066 | # Use user override if there is one 2067 | fold_diacritics = self.settings.get('__workflow_diacritic_folding', 2068 | fold_diacritics) 2069 | 2070 | results = [] 2071 | 2072 | for item in items: 2073 | skip = False 2074 | score = 0 2075 | words = [s.strip() for s in query.split(' ')] 2076 | value = key(item).strip() 2077 | if value == '': 2078 | continue 2079 | for word in words: 2080 | if word == '': 2081 | continue 2082 | s, rule = self._filter_item(value, word, match_on, 2083 | fold_diacritics) 2084 | 2085 | if not s: # Skip items that don't match part of the query 2086 | skip = True 2087 | score += s 2088 | 2089 | if skip: 2090 | continue 2091 | 2092 | if score: 2093 | # use "reversed" `score` (i.e. highest becomes lowest) and 2094 | # `value` as sort key. This means items with the same score 2095 | # will be sorted in alphabetical not reverse alphabetical order 2096 | results.append(((100.0 / score, value.lower(), score), 2097 | (item, score, rule))) 2098 | 2099 | # sort on keys, then discard the keys 2100 | results.sort(reverse=ascending) 2101 | results = [t[1] for t in results] 2102 | 2103 | if min_score: 2104 | results = [r for r in results if r[1] > min_score] 2105 | 2106 | if max_results and len(results) > max_results: 2107 | results = results[:max_results] 2108 | 2109 | # return list of ``(item, score, rule)`` 2110 | if include_score: 2111 | return results 2112 | # just return list of items 2113 | return [t[0] for t in results] 2114 | 2115 | def _filter_item(self, value, query, match_on, fold_diacritics): 2116 | """Filter ``value`` against ``query`` using rules ``match_on``. 2117 | 2118 | :returns: ``(score, rule)`` 2119 | 2120 | """ 2121 | query = query.lower() 2122 | 2123 | if not isascii(query): 2124 | fold_diacritics = False 2125 | 2126 | if fold_diacritics: 2127 | value = self.fold_to_ascii(value) 2128 | 2129 | # pre-filter any items that do not contain all characters 2130 | # of ``query`` to save on running several more expensive tests 2131 | if not set(query) <= set(value.lower()): 2132 | 2133 | return (0, None) 2134 | 2135 | # item starts with query 2136 | if match_on & MATCH_STARTSWITH and value.lower().startswith(query): 2137 | score = 100.0 - (len(value) / len(query)) 2138 | 2139 | return (score, MATCH_STARTSWITH) 2140 | 2141 | # query matches capitalised letters in item, 2142 | # e.g. of = OmniFocus 2143 | if match_on & MATCH_CAPITALS: 2144 | initials = ''.join([c for c in value if c in INITIALS]) 2145 | if initials.lower().startswith(query): 2146 | score = 100.0 - (len(initials) / len(query)) 2147 | 2148 | return (score, MATCH_CAPITALS) 2149 | 2150 | # split the item into "atoms", i.e. words separated by 2151 | # spaces or other non-word characters 2152 | if (match_on & MATCH_ATOM or 2153 | match_on & MATCH_INITIALS_CONTAIN or 2154 | match_on & MATCH_INITIALS_STARTSWITH): 2155 | atoms = [s.lower() for s in split_on_delimiters(value)] 2156 | # print('atoms : %s --> %s' % (value, atoms)) 2157 | # initials of the atoms 2158 | initials = ''.join([s[0] for s in atoms if s]) 2159 | 2160 | if match_on & MATCH_ATOM: 2161 | # is `query` one of the atoms in item? 2162 | # similar to substring, but scores more highly, as it's 2163 | # a word within the item 2164 | if query in atoms: 2165 | score = 100.0 - (len(value) / len(query)) 2166 | 2167 | return (score, MATCH_ATOM) 2168 | 2169 | # `query` matches start (or all) of the initials of the 2170 | # atoms, e.g. ``himym`` matches "How I Met Your Mother" 2171 | # *and* "how i met your mother" (the ``capitals`` rule only 2172 | # matches the former) 2173 | if (match_on & MATCH_INITIALS_STARTSWITH and 2174 | initials.startswith(query)): 2175 | score = 100.0 - (len(initials) / len(query)) 2176 | 2177 | return (score, MATCH_INITIALS_STARTSWITH) 2178 | 2179 | # `query` is a substring of initials, e.g. ``doh`` matches 2180 | # "The Dukes of Hazzard" 2181 | elif (match_on & MATCH_INITIALS_CONTAIN and 2182 | query in initials): 2183 | score = 95.0 - (len(initials) / len(query)) 2184 | 2185 | return (score, MATCH_INITIALS_CONTAIN) 2186 | 2187 | # `query` is a substring of item 2188 | if match_on & MATCH_SUBSTRING and query in value.lower(): 2189 | score = 90.0 - (len(value) / len(query)) 2190 | 2191 | return (score, MATCH_SUBSTRING) 2192 | 2193 | # finally, assign a score based on how close together the 2194 | # characters in `query` are in item. 2195 | if match_on & MATCH_ALLCHARS: 2196 | search = self._search_for_query(query) 2197 | match = search(value) 2198 | if match: 2199 | score = 100.0 / ((1 + match.start()) * 2200 | (match.end() - match.start() + 1)) 2201 | 2202 | return (score, MATCH_ALLCHARS) 2203 | 2204 | # Nothing matched 2205 | return (0, None) 2206 | 2207 | def _search_for_query(self, query): 2208 | if query in self._search_pattern_cache: 2209 | return self._search_pattern_cache[query] 2210 | 2211 | # Build pattern: include all characters 2212 | pattern = [] 2213 | for c in query: 2214 | # pattern.append('[^{0}]*{0}'.format(re.escape(c))) 2215 | pattern.append('.*?{0}'.format(re.escape(c))) 2216 | pattern = ''.join(pattern) 2217 | search = re.compile(pattern, re.IGNORECASE).search 2218 | 2219 | self._search_pattern_cache[query] = search 2220 | return search 2221 | 2222 | def run(self, func, text_errors=False): 2223 | """Call ``func`` to run your workflow. 2224 | 2225 | :param func: Callable to call with ``self`` (i.e. the :class:`Workflow` 2226 | instance) as first argument. 2227 | :param text_errors: Emit error messages in plain text, not in 2228 | Alfred's XML/JSON feedback format. Use this when you're not 2229 | running Alfred-Workflow in a Script Filter and would like 2230 | to pass the error message to, say, a notification. 2231 | :type text_errors: ``Boolean`` 2232 | 2233 | ``func`` will be called with :class:`Workflow` instance as first 2234 | argument. 2235 | 2236 | ``func`` should be the main entry point to your workflow. 2237 | 2238 | Any exceptions raised will be logged and an error message will be 2239 | output to Alfred. 2240 | 2241 | """ 2242 | start = time.time() 2243 | 2244 | # Call workflow's entry function/method within a try-except block 2245 | # to catch any errors and display an error message in Alfred 2246 | try: 2247 | 2248 | if self.version: 2249 | self.logger.debug('workflow version: %s', self.version) 2250 | 2251 | # Run update check if configured for self-updates. 2252 | # This call has to go in the `run` try-except block, as it will 2253 | # initialise `self.settings`, which will raise an exception 2254 | # if `settings.json` isn't valid. 2255 | 2256 | if self._update_settings: 2257 | self.check_update() 2258 | 2259 | # Run workflow's entry function/method 2260 | func(self) 2261 | 2262 | # Set last version run to current version after a successful 2263 | # run 2264 | self.set_last_version() 2265 | 2266 | except Exception as err: 2267 | self.logger.exception(err) 2268 | if self.help_url: 2269 | self.logger.info('for assistance, see: %s', self.help_url) 2270 | 2271 | if not sys.stdout.isatty(): # Show error in Alfred 2272 | if text_errors: 2273 | print(unicode(err).encode('utf-8'), end='') 2274 | else: 2275 | self._items = [] 2276 | if self._name: 2277 | name = self._name 2278 | elif self._bundleid: 2279 | name = self._bundleid 2280 | else: # pragma: no cover 2281 | name = os.path.dirname(__file__) 2282 | self.add_item("Error in workflow '%s'" % name, 2283 | unicode(err), 2284 | icon=ICON_ERROR) 2285 | self.send_feedback() 2286 | return 1 2287 | 2288 | finally: 2289 | self.logger.debug('workflow finished in %0.3f seconds', 2290 | time.time() - start) 2291 | 2292 | return 0 2293 | 2294 | # Alfred feedback methods ------------------------------------------ 2295 | 2296 | def add_item(self, title, subtitle='', modifier_subtitles=None, arg=None, 2297 | autocomplete=None, valid=False, uid=None, icon=None, 2298 | icontype=None, type=None, largetext=None, copytext=None, 2299 | quicklookurl=None): 2300 | """Add an item to be output to Alfred. 2301 | 2302 | :param title: Title shown in Alfred 2303 | :type title: ``unicode`` 2304 | :param subtitle: Subtitle shown in Alfred 2305 | :type subtitle: ``unicode`` 2306 | :param modifier_subtitles: Subtitles shown when modifier 2307 | (CMD, OPT etc.) is pressed. Use a ``dict`` with the lowercase 2308 | keys ``cmd``, ``ctrl``, ``shift``, ``alt`` and ``fn`` 2309 | :type modifier_subtitles: ``dict`` 2310 | :param arg: Argument passed by Alfred as ``{query}`` when item is 2311 | actioned 2312 | :type arg: ``unicode`` 2313 | :param autocomplete: Text expanded in Alfred when item is TABbed 2314 | :type autocomplete: ``unicode`` 2315 | :param valid: Whether or not item can be actioned 2316 | :type valid: ``Boolean`` 2317 | :param uid: Used by Alfred to remember/sort items 2318 | :type uid: ``unicode`` 2319 | :param icon: Filename of icon to use 2320 | :type icon: ``unicode`` 2321 | :param icontype: Type of icon. Must be one of ``None`` , ``'filetype'`` 2322 | or ``'fileicon'``. Use ``'filetype'`` when ``icon`` is a filetype 2323 | such as ``'public.folder'``. Use ``'fileicon'`` when you wish to 2324 | use the icon of the file specified as ``icon``, e.g. 2325 | ``icon='/Applications/Safari.app', icontype='fileicon'``. 2326 | Leave as `None` if ``icon`` points to an actual 2327 | icon file. 2328 | :type icontype: ``unicode`` 2329 | :param type: Result type. Currently only ``'file'`` is supported 2330 | (by Alfred). This will tell Alfred to enable file actions for 2331 | this item. 2332 | :type type: ``unicode`` 2333 | :param largetext: Text to be displayed in Alfred's large text box 2334 | if user presses CMD+L on item. 2335 | :type largetext: ``unicode`` 2336 | :param copytext: Text to be copied to pasteboard if user presses 2337 | CMD+C on item. 2338 | :type copytext: ``unicode`` 2339 | :param quicklookurl: URL to be displayed using Alfred's Quick Look 2340 | feature (tapping ``SHIFT`` or ``⌘+Y`` on a result). 2341 | :type quicklookurl: ``unicode`` 2342 | :returns: :class:`Item` instance 2343 | 2344 | See :ref:`icons` for a list of the supported system icons. 2345 | 2346 | .. note:: 2347 | 2348 | Although this method returns an :class:`Item` instance, you don't 2349 | need to hold onto it or worry about it. All generated :class:`Item` 2350 | instances are also collected internally and sent to Alfred when 2351 | :meth:`send_feedback` is called. 2352 | 2353 | The generated :class:`Item` is only returned in case you want to 2354 | edit it or do something with it other than send it to Alfred. 2355 | 2356 | """ 2357 | item = self.item_class(title, subtitle, modifier_subtitles, arg, 2358 | autocomplete, valid, uid, icon, icontype, type, 2359 | largetext, copytext, quicklookurl) 2360 | self._items.append(item) 2361 | return item 2362 | 2363 | def send_feedback(self): 2364 | """Print stored items to console/Alfred as XML.""" 2365 | root = ET.Element('items') 2366 | for item in self._items: 2367 | root.append(item.elem) 2368 | sys.stdout.write('\n') 2369 | sys.stdout.write(ET.tostring(root).encode('utf-8')) 2370 | sys.stdout.flush() 2371 | 2372 | #################################################################### 2373 | # Updating methods 2374 | #################################################################### 2375 | 2376 | @property 2377 | def first_run(self): 2378 | """Return ``True`` if it's the first time this version has run. 2379 | 2380 | .. versionadded:: 1.9.10 2381 | 2382 | Raises a :class:`ValueError` if :attr:`version` isn't set. 2383 | 2384 | """ 2385 | if not self.version: 2386 | raise ValueError('No workflow version set') 2387 | 2388 | if not self.last_version_run: 2389 | return True 2390 | 2391 | return self.version != self.last_version_run 2392 | 2393 | @property 2394 | def last_version_run(self): 2395 | """Return version of last version to run (or ``None``). 2396 | 2397 | .. versionadded:: 1.9.10 2398 | 2399 | :returns: :class:`~workflow.update.Version` instance 2400 | or ``None`` 2401 | 2402 | """ 2403 | if self._last_version_run is UNSET: 2404 | 2405 | version = self.settings.get('__workflow_last_version') 2406 | if version: 2407 | from update import Version 2408 | version = Version(version) 2409 | 2410 | self._last_version_run = version 2411 | 2412 | self.logger.debug('last run version: %s', self._last_version_run) 2413 | 2414 | return self._last_version_run 2415 | 2416 | def set_last_version(self, version=None): 2417 | """Set :attr:`last_version_run` to current version. 2418 | 2419 | .. versionadded:: 1.9.10 2420 | 2421 | :param version: version to store (default is current version) 2422 | :type version: :class:`~workflow.update.Version` instance 2423 | or ``unicode`` 2424 | :returns: ``True`` if version is saved, else ``False`` 2425 | 2426 | """ 2427 | if not version: 2428 | if not self.version: 2429 | self.logger.warning( 2430 | "Can't save last version: workflow has no version") 2431 | return False 2432 | 2433 | version = self.version 2434 | 2435 | if isinstance(version, basestring): 2436 | from update import Version 2437 | version = Version(version) 2438 | 2439 | self.settings['__workflow_last_version'] = str(version) 2440 | 2441 | self.logger.debug('set last run version: %s', version) 2442 | 2443 | return True 2444 | 2445 | @property 2446 | def update_available(self): 2447 | """Whether an update is available. 2448 | 2449 | .. versionadded:: 1.9 2450 | 2451 | See :ref:`guide-updates` in the :ref:`user-manual` for detailed 2452 | information on how to enable your workflow to update itself. 2453 | 2454 | :returns: ``True`` if an update is available, else ``False`` 2455 | 2456 | """ 2457 | # Create a new workflow object to ensure standard serialiser 2458 | # is used (update.py is called without the user's settings) 2459 | update_data = Workflow().cached_data('__workflow_update_status', 2460 | max_age=0) 2461 | 2462 | self.logger.debug('update_data: %r', update_data) 2463 | 2464 | if not update_data or not update_data.get('available'): 2465 | return False 2466 | 2467 | return update_data['available'] 2468 | 2469 | @property 2470 | def prereleases(self): 2471 | """Whether workflow should update to pre-release versions. 2472 | 2473 | .. versionadded:: 1.16 2474 | 2475 | :returns: ``True`` if pre-releases are enabled with the :ref:`magic 2476 | argument ` or the ``update_settings`` dict, else 2477 | ``False``. 2478 | 2479 | """ 2480 | if self._update_settings.get('prereleases'): 2481 | return True 2482 | 2483 | return self.settings.get('__workflow_prereleases') or False 2484 | 2485 | def check_update(self, force=False): 2486 | """Call update script if it's time to check for a new release. 2487 | 2488 | .. versionadded:: 1.9 2489 | 2490 | The update script will be run in the background, so it won't 2491 | interfere in the execution of your workflow. 2492 | 2493 | See :ref:`guide-updates` in the :ref:`user-manual` for detailed 2494 | information on how to enable your workflow to update itself. 2495 | 2496 | :param force: Force update check 2497 | :type force: ``Boolean`` 2498 | 2499 | """ 2500 | frequency = self._update_settings.get('frequency', 2501 | DEFAULT_UPDATE_FREQUENCY) 2502 | 2503 | if not force and not self.settings.get('__workflow_autoupdate', True): 2504 | self.logger.debug('Auto update turned off by user') 2505 | return 2506 | 2507 | # Check for new version if it's time 2508 | if (force or not self.cached_data_fresh( 2509 | '__workflow_update_status', frequency * 86400)): 2510 | 2511 | github_slug = self._update_settings['github_slug'] 2512 | # version = self._update_settings['version'] 2513 | version = str(self.version) 2514 | 2515 | from background import run_in_background 2516 | 2517 | # update.py is adjacent to this file 2518 | update_script = os.path.join(os.path.dirname(__file__), 2519 | b'update.py') 2520 | 2521 | cmd = ['/usr/bin/python', update_script, 'check', github_slug, 2522 | version] 2523 | 2524 | if self.prereleases: 2525 | cmd.append('--prereleases') 2526 | 2527 | self.logger.info('Checking for update ...') 2528 | 2529 | run_in_background('__workflow_update_check', cmd) 2530 | 2531 | else: 2532 | self.logger.debug('Update check not due') 2533 | 2534 | def start_update(self): 2535 | """Check for update and download and install new workflow file. 2536 | 2537 | .. versionadded:: 1.9 2538 | 2539 | See :ref:`guide-updates` in the :ref:`user-manual` for detailed 2540 | information on how to enable your workflow to update itself. 2541 | 2542 | :returns: ``True`` if an update is available and will be 2543 | installed, else ``False`` 2544 | 2545 | """ 2546 | import update 2547 | 2548 | github_slug = self._update_settings['github_slug'] 2549 | # version = self._update_settings['version'] 2550 | version = str(self.version) 2551 | 2552 | if not update.check_update(github_slug, version, self.prereleases): 2553 | return False 2554 | 2555 | from background import run_in_background 2556 | 2557 | # update.py is adjacent to this file 2558 | update_script = os.path.join(os.path.dirname(__file__), 2559 | b'update.py') 2560 | 2561 | cmd = ['/usr/bin/python', update_script, 'install', github_slug, 2562 | version] 2563 | 2564 | if self.prereleases: 2565 | cmd.append('--prereleases') 2566 | 2567 | self.logger.debug('Downloading update ...') 2568 | run_in_background('__workflow_update_install', cmd) 2569 | 2570 | return True 2571 | 2572 | #################################################################### 2573 | # Keychain password storage methods 2574 | #################################################################### 2575 | 2576 | def save_password(self, account, password, service=None): 2577 | """Save account credentials. 2578 | 2579 | If the account exists, the old password will first be deleted 2580 | (Keychain throws an error otherwise). 2581 | 2582 | If something goes wrong, a :class:`KeychainError` exception will 2583 | be raised. 2584 | 2585 | :param account: name of the account the password is for, e.g. 2586 | "Pinboard" 2587 | :type account: ``unicode`` 2588 | :param password: the password to secure 2589 | :type password: ``unicode`` 2590 | :param service: Name of the service. By default, this is the 2591 | workflow's bundle ID 2592 | :type service: ``unicode`` 2593 | 2594 | """ 2595 | if not service: 2596 | service = self.bundleid 2597 | 2598 | try: 2599 | self._call_security('add-generic-password', service, account, 2600 | '-w', password) 2601 | self.logger.debug('Saved password : %s:%s', service, account) 2602 | 2603 | except PasswordExists: 2604 | self.logger.debug('Password exists : %s:%s', service, account) 2605 | current_password = self.get_password(account, service) 2606 | 2607 | if current_password == password: 2608 | self.logger.debug('Password unchanged') 2609 | 2610 | else: 2611 | self.delete_password(account, service) 2612 | self._call_security('add-generic-password', service, 2613 | account, '-w', password) 2614 | self.logger.debug('save_password : %s:%s', service, account) 2615 | 2616 | def get_password(self, account, service=None): 2617 | """Retrieve the password saved at ``service/account``. 2618 | 2619 | Raise :class:`PasswordNotFound` exception if password doesn't exist. 2620 | 2621 | :param account: name of the account the password is for, e.g. 2622 | "Pinboard" 2623 | :type account: ``unicode`` 2624 | :param service: Name of the service. By default, this is the workflow's 2625 | bundle ID 2626 | :type service: ``unicode`` 2627 | :returns: account password 2628 | :rtype: ``unicode`` 2629 | 2630 | """ 2631 | if not service: 2632 | service = self.bundleid 2633 | 2634 | output = self._call_security('find-generic-password', service, 2635 | account, '-g') 2636 | 2637 | # Parsing of `security` output is adapted from python-keyring 2638 | # by Jason R. Coombs 2639 | # https://pypi.python.org/pypi/keyring 2640 | m = re.search( 2641 | r'password:\s*(?:0x(?P[0-9A-F]+)\s*)?(?:"(?P.*)")?', 2642 | output) 2643 | 2644 | if m: 2645 | groups = m.groupdict() 2646 | h = groups.get('hex') 2647 | password = groups.get('pw') 2648 | if h: 2649 | password = unicode(binascii.unhexlify(h), 'utf-8') 2650 | 2651 | self.logger.debug('Got password : %s:%s', service, account) 2652 | 2653 | return password 2654 | 2655 | def delete_password(self, account, service=None): 2656 | """Delete the password stored at ``service/account``. 2657 | 2658 | Raise :class:`PasswordNotFound` if account is unknown. 2659 | 2660 | :param account: name of the account the password is for, e.g. 2661 | "Pinboard" 2662 | :type account: ``unicode`` 2663 | :param service: Name of the service. By default, this is the workflow's 2664 | bundle ID 2665 | :type service: ``unicode`` 2666 | 2667 | """ 2668 | if not service: 2669 | service = self.bundleid 2670 | 2671 | self._call_security('delete-generic-password', service, account) 2672 | 2673 | self.logger.debug('Deleted password : %s:%s', service, account) 2674 | 2675 | #################################################################### 2676 | # Methods for workflow:* magic args 2677 | #################################################################### 2678 | 2679 | def _register_default_magic(self): 2680 | """Register the built-in magic arguments.""" 2681 | # TODO: refactor & simplify 2682 | # Wrap callback and message with callable 2683 | def callback(func, msg): 2684 | def wrapper(): 2685 | func() 2686 | return msg 2687 | 2688 | return wrapper 2689 | 2690 | self.magic_arguments['delcache'] = callback(self.clear_cache, 2691 | 'Deleted workflow cache') 2692 | self.magic_arguments['deldata'] = callback(self.clear_data, 2693 | 'Deleted workflow data') 2694 | self.magic_arguments['delsettings'] = callback( 2695 | self.clear_settings, 'Deleted workflow settings') 2696 | self.magic_arguments['reset'] = callback(self.reset, 2697 | 'Reset workflow') 2698 | self.magic_arguments['openlog'] = callback(self.open_log, 2699 | 'Opening workflow log file') 2700 | self.magic_arguments['opencache'] = callback( 2701 | self.open_cachedir, 'Opening workflow cache directory') 2702 | self.magic_arguments['opendata'] = callback( 2703 | self.open_datadir, 'Opening workflow data directory') 2704 | self.magic_arguments['openworkflow'] = callback( 2705 | self.open_workflowdir, 'Opening workflow directory') 2706 | self.magic_arguments['openterm'] = callback( 2707 | self.open_terminal, 'Opening workflow root directory in Terminal') 2708 | 2709 | # Diacritic folding 2710 | def fold_on(): 2711 | self.settings['__workflow_diacritic_folding'] = True 2712 | return 'Diacritics will always be folded' 2713 | 2714 | def fold_off(): 2715 | self.settings['__workflow_diacritic_folding'] = False 2716 | return 'Diacritics will never be folded' 2717 | 2718 | def fold_default(): 2719 | if '__workflow_diacritic_folding' in self.settings: 2720 | del self.settings['__workflow_diacritic_folding'] 2721 | return 'Diacritics folding reset' 2722 | 2723 | self.magic_arguments['foldingon'] = fold_on 2724 | self.magic_arguments['foldingoff'] = fold_off 2725 | self.magic_arguments['foldingdefault'] = fold_default 2726 | 2727 | # Updates 2728 | def update_on(): 2729 | self.settings['__workflow_autoupdate'] = True 2730 | return 'Auto update turned on' 2731 | 2732 | def update_off(): 2733 | self.settings['__workflow_autoupdate'] = False 2734 | return 'Auto update turned off' 2735 | 2736 | def prereleases_on(): 2737 | self.settings['__workflow_prereleases'] = True 2738 | return 'Prerelease updates turned on' 2739 | 2740 | def prereleases_off(): 2741 | self.settings['__workflow_prereleases'] = False 2742 | return 'Prerelease updates turned off' 2743 | 2744 | def do_update(): 2745 | if self.start_update(): 2746 | return 'Downloading and installing update ...' 2747 | else: 2748 | return 'No update available' 2749 | 2750 | self.magic_arguments['autoupdate'] = update_on 2751 | self.magic_arguments['noautoupdate'] = update_off 2752 | self.magic_arguments['prereleases'] = prereleases_on 2753 | self.magic_arguments['noprereleases'] = prereleases_off 2754 | self.magic_arguments['update'] = do_update 2755 | 2756 | # Help 2757 | def do_help(): 2758 | if self.help_url: 2759 | self.open_help() 2760 | return 'Opening workflow help URL in browser' 2761 | else: 2762 | return 'Workflow has no help URL' 2763 | 2764 | def show_version(): 2765 | if self.version: 2766 | return 'Version: {0}'.format(self.version) 2767 | else: 2768 | return 'This workflow has no version number' 2769 | 2770 | def list_magic(): 2771 | """Display all available magic args in Alfred.""" 2772 | isatty = sys.stderr.isatty() 2773 | for name in sorted(self.magic_arguments.keys()): 2774 | if name == 'magic': 2775 | continue 2776 | arg = '{0}{1}'.format(self.magic_prefix, name) 2777 | self.logger.debug(arg) 2778 | 2779 | if not isatty: 2780 | self.add_item(arg, icon=ICON_INFO) 2781 | 2782 | if not isatty: 2783 | self.send_feedback() 2784 | 2785 | self.magic_arguments['help'] = do_help 2786 | self.magic_arguments['magic'] = list_magic 2787 | self.magic_arguments['version'] = show_version 2788 | 2789 | def clear_cache(self, filter_func=lambda f: True): 2790 | """Delete all files in workflow's :attr:`cachedir`. 2791 | 2792 | :param filter_func: Callable to determine whether a file should be 2793 | deleted or not. ``filter_func`` is called with the filename 2794 | of each file in the data directory. If it returns ``True``, 2795 | the file will be deleted. 2796 | By default, *all* files will be deleted. 2797 | :type filter_func: ``callable`` 2798 | """ 2799 | self._delete_directory_contents(self.cachedir, filter_func) 2800 | 2801 | def clear_data(self, filter_func=lambda f: True): 2802 | """Delete all files in workflow's :attr:`datadir`. 2803 | 2804 | :param filter_func: Callable to determine whether a file should be 2805 | deleted or not. ``filter_func`` is called with the filename 2806 | of each file in the data directory. If it returns ``True``, 2807 | the file will be deleted. 2808 | By default, *all* files will be deleted. 2809 | :type filter_func: ``callable`` 2810 | """ 2811 | self._delete_directory_contents(self.datadir, filter_func) 2812 | 2813 | def clear_settings(self): 2814 | """Delete workflow's :attr:`settings_path`.""" 2815 | if os.path.exists(self.settings_path): 2816 | os.unlink(self.settings_path) 2817 | self.logger.debug('Deleted : %r', self.settings_path) 2818 | 2819 | def reset(self): 2820 | """Delete workflow settings, cache and data. 2821 | 2822 | File :attr:`settings ` and directories 2823 | :attr:`cache ` and :attr:`data ` are deleted. 2824 | 2825 | """ 2826 | self.clear_cache() 2827 | self.clear_data() 2828 | self.clear_settings() 2829 | 2830 | def open_log(self): 2831 | """Open :attr:`logfile` in default app (usually Console.app).""" 2832 | subprocess.call(['open', self.logfile]) 2833 | 2834 | def open_cachedir(self): 2835 | """Open the workflow's :attr:`cachedir` in Finder.""" 2836 | subprocess.call(['open', self.cachedir]) 2837 | 2838 | def open_datadir(self): 2839 | """Open the workflow's :attr:`datadir` in Finder.""" 2840 | subprocess.call(['open', self.datadir]) 2841 | 2842 | def open_workflowdir(self): 2843 | """Open the workflow's :attr:`workflowdir` in Finder.""" 2844 | subprocess.call(['open', self.workflowdir]) 2845 | 2846 | def open_terminal(self): 2847 | """Open a Terminal window at workflow's :attr:`workflowdir`.""" 2848 | subprocess.call(['open', '-a', 'Terminal', 2849 | self.workflowdir]) 2850 | 2851 | def open_help(self): 2852 | """Open :attr:`help_url` in default browser.""" 2853 | subprocess.call(['open', self.help_url]) 2854 | 2855 | return 'Opening workflow help URL in browser' 2856 | 2857 | #################################################################### 2858 | # Helper methods 2859 | #################################################################### 2860 | 2861 | def decode(self, text, encoding=None, normalization=None): 2862 | """Return ``text`` as normalised unicode. 2863 | 2864 | If ``encoding`` and/or ``normalization`` is ``None``, the 2865 | ``input_encoding``and ``normalization`` parameters passed to 2866 | :class:`Workflow` are used. 2867 | 2868 | :param text: string 2869 | :type text: encoded or Unicode string. If ``text`` is already a 2870 | Unicode string, it will only be normalised. 2871 | :param encoding: The text encoding to use to decode ``text`` to 2872 | Unicode. 2873 | :type encoding: ``unicode`` or ``None`` 2874 | :param normalization: The nomalisation form to apply to ``text``. 2875 | :type normalization: ``unicode`` or ``None`` 2876 | :returns: decoded and normalised ``unicode`` 2877 | 2878 | :class:`Workflow` uses "NFC" normalisation by default. This is the 2879 | standard for Python and will work well with data from the web (via 2880 | :mod:`~workflow.web` or :mod:`json`). 2881 | 2882 | macOS, on the other hand, uses "NFD" normalisation (nearly), so data 2883 | coming from the system (e.g. via :mod:`subprocess` or 2884 | :func:`os.listdir`/:mod:`os.path`) may not match. You should either 2885 | normalise this data, too, or change the default normalisation used by 2886 | :class:`Workflow`. 2887 | 2888 | """ 2889 | encoding = encoding or self._input_encoding 2890 | normalization = normalization or self._normalizsation 2891 | if not isinstance(text, unicode): 2892 | text = unicode(text, encoding) 2893 | return unicodedata.normalize(normalization, text) 2894 | 2895 | def fold_to_ascii(self, text): 2896 | """Convert non-ASCII characters to closest ASCII equivalent. 2897 | 2898 | .. versionadded:: 1.3 2899 | 2900 | .. note:: This only works for a subset of European languages. 2901 | 2902 | :param text: text to convert 2903 | :type text: ``unicode`` 2904 | :returns: text containing only ASCII characters 2905 | :rtype: ``unicode`` 2906 | 2907 | """ 2908 | if isascii(text): 2909 | return text 2910 | text = ''.join([ASCII_REPLACEMENTS.get(c, c) for c in text]) 2911 | return unicode(unicodedata.normalize('NFKD', 2912 | text).encode('ascii', 'ignore')) 2913 | 2914 | def dumbify_punctuation(self, text): 2915 | """Convert non-ASCII punctuation to closest ASCII equivalent. 2916 | 2917 | This method replaces "smart" quotes and n- or m-dashes with their 2918 | workaday ASCII equivalents. This method is currently not used 2919 | internally, but exists as a helper method for workflow authors. 2920 | 2921 | .. versionadded: 1.9.7 2922 | 2923 | :param text: text to convert 2924 | :type text: ``unicode`` 2925 | :returns: text with only ASCII punctuation 2926 | :rtype: ``unicode`` 2927 | 2928 | """ 2929 | if isascii(text): 2930 | return text 2931 | 2932 | text = ''.join([DUMB_PUNCTUATION.get(c, c) for c in text]) 2933 | return text 2934 | 2935 | def _delete_directory_contents(self, dirpath, filter_func): 2936 | """Delete all files in a directory. 2937 | 2938 | :param dirpath: path to directory to clear 2939 | :type dirpath: ``unicode`` or ``str`` 2940 | :param filter_func function to determine whether a file shall be 2941 | deleted or not. 2942 | :type filter_func ``callable`` 2943 | 2944 | """ 2945 | if os.path.exists(dirpath): 2946 | for filename in os.listdir(dirpath): 2947 | if not filter_func(filename): 2948 | continue 2949 | path = os.path.join(dirpath, filename) 2950 | if os.path.isdir(path): 2951 | shutil.rmtree(path) 2952 | else: 2953 | os.unlink(path) 2954 | self.logger.debug('Deleted : %r', path) 2955 | 2956 | def _load_info_plist(self): 2957 | """Load workflow info from ``info.plist``.""" 2958 | # info.plist should be in the directory above this one 2959 | self._info = plistlib.readPlist(self.workflowfile('info.plist')) 2960 | self._info_loaded = True 2961 | 2962 | def _create(self, dirpath): 2963 | """Create directory `dirpath` if it doesn't exist. 2964 | 2965 | :param dirpath: path to directory 2966 | :type dirpath: ``unicode`` 2967 | :returns: ``dirpath`` argument 2968 | :rtype: ``unicode`` 2969 | 2970 | """ 2971 | if not os.path.exists(dirpath): 2972 | os.makedirs(dirpath) 2973 | return dirpath 2974 | 2975 | def _call_security(self, action, service, account, *args): 2976 | """Call ``security`` CLI program that provides access to keychains. 2977 | 2978 | May raise `PasswordNotFound`, `PasswordExists` or `KeychainError` 2979 | exceptions (the first two are subclasses of `KeychainError`). 2980 | 2981 | :param action: The ``security`` action to call, e.g. 2982 | ``add-generic-password`` 2983 | :type action: ``unicode`` 2984 | :param service: Name of the service. 2985 | :type service: ``unicode`` 2986 | :param account: name of the account the password is for, e.g. 2987 | "Pinboard" 2988 | :type account: ``unicode`` 2989 | :param password: the password to secure 2990 | :type password: ``unicode`` 2991 | :param *args: list of command line arguments to be passed to 2992 | ``security`` 2993 | :type *args: `list` or `tuple` 2994 | :returns: ``(retcode, output)``. ``retcode`` is an `int`, ``output`` a 2995 | ``unicode`` string. 2996 | :rtype: `tuple` (`int`, ``unicode``) 2997 | 2998 | """ 2999 | cmd = ['security', action, '-s', service, '-a', account] + list(args) 3000 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, 3001 | stderr=subprocess.STDOUT) 3002 | stdout, _ = p.communicate() 3003 | if p.returncode == 44: # password does not exist 3004 | raise PasswordNotFound() 3005 | elif p.returncode == 45: # password already exists 3006 | raise PasswordExists() 3007 | elif p.returncode > 0: 3008 | err = KeychainError('Unknown Keychain error : %s' % stdout) 3009 | err.retcode = p.returncode 3010 | raise err 3011 | return stdout.strip().decode('utf-8') 3012 | -------------------------------------------------------------------------------- /src/workflow/workflow3.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | # 3 | # Copyright (c) 2016 Dean Jackson 4 | # 5 | # MIT Licence. See http://opensource.org/licenses/MIT 6 | # 7 | # Created on 2016-06-25 8 | # 9 | 10 | """An Alfred 3-only version of :class:`~workflow.Workflow`. 11 | 12 | :class:`~workflow.Workflow3` supports Alfred 3's new features, such as 13 | setting :ref:`workflow-variables` and 14 | :class:`the more advanced modifiers ` supported by Alfred 3. 15 | 16 | In order for the feedback mechanism to work correctly, it's important 17 | to create :class:`Item3` and :class:`Modifier` objects via the 18 | :meth:`Workflow3.add_item()` and :meth:`Item3.add_modifier()` methods 19 | respectively. If you instantiate :class:`Item3` or :class:`Modifier` 20 | objects directly, the current :class:`Workflow3` object won't be aware 21 | of them, and they won't be sent to Alfred when you call 22 | :meth:`Workflow3.send_feedback()`. 23 | 24 | """ 25 | 26 | from __future__ import print_function, unicode_literals, absolute_import 27 | 28 | import json 29 | import os 30 | import sys 31 | 32 | from .workflow import Workflow 33 | 34 | 35 | class Variables(dict): 36 | """Workflow variables for Run Script actions. 37 | 38 | .. versionadded: 1.26 39 | 40 | This class allows you to set workflow variables from 41 | Run Script actions. 42 | 43 | It is a subclass of :class:`dict`. 44 | 45 | >>> v = Variables(username='deanishe', password='hunter2') 46 | >>> v.arg = u'output value' 47 | >>> print(v) 48 | 49 | See :ref:`variables-run-script` in the User Guide for more 50 | information. 51 | 52 | Args: 53 | arg (unicode, optional): Main output/``{query}``. 54 | **variables: Workflow variables to set. 55 | 56 | 57 | Attributes: 58 | arg (unicode): Output value (``{query}``). 59 | config (dict): Configuration for downstream workflow element. 60 | 61 | """ 62 | 63 | def __init__(self, arg=None, **variables): 64 | """Create a new `Variables` object.""" 65 | self.arg = arg 66 | self.config = {} 67 | super(Variables, self).__init__(**variables) 68 | 69 | @property 70 | def obj(self): 71 | """Return ``alfredworkflow`` `dict`.""" 72 | o = {} 73 | if self: 74 | d2 = {} 75 | for k, v in self.items(): 76 | d2[k] = v 77 | o['variables'] = d2 78 | 79 | if self.config: 80 | o['config'] = self.config 81 | 82 | if self.arg is not None: 83 | o['arg'] = self.arg 84 | 85 | return {'alfredworkflow': o} 86 | 87 | def __unicode__(self): 88 | """Convert to ``alfredworkflow`` JSON object. 89 | 90 | Returns: 91 | unicode: ``alfredworkflow`` JSON object 92 | 93 | """ 94 | if not self and not self.config: 95 | if self.arg: 96 | return self.arg 97 | else: 98 | return u'' 99 | 100 | return json.dumps(self.obj) 101 | 102 | def __str__(self): 103 | """Convert to ``alfredworkflow`` JSON object. 104 | 105 | Returns: 106 | str: UTF-8 encoded ``alfredworkflow`` JSON object 107 | 108 | """ 109 | return unicode(self).encode('utf-8') 110 | 111 | 112 | class Modifier(object): 113 | """Modify :class:`Item3` arg/icon/variables when modifier key is pressed. 114 | 115 | Don't use this class directly (as it won't be associated with any 116 | :class:`Item3`), but rather use :meth:`Item3.add_modifier()` 117 | to add modifiers to results. 118 | 119 | >>> it = wf.add_item('Title', 'Subtitle', valid=True) 120 | >>> it.setvar('name', 'default') 121 | >>> m = it.add_modifier('cmd') 122 | >>> m.setvar('name', 'alternate') 123 | 124 | See :ref:`workflow-variables` in the User Guide for more information 125 | and :ref:`example usage `. 126 | 127 | Args: 128 | key (unicode): Modifier key, e.g. ``"cmd"``, ``"alt"`` etc. 129 | subtitle (unicode, optional): Override default subtitle. 130 | arg (unicode, optional): Argument to pass for this modifier. 131 | valid (bool, optional): Override item's validity. 132 | icon (unicode, optional): Filepath/UTI of icon to use 133 | icontype (unicode, optional): Type of icon. See 134 | :meth:`Workflow.add_item() ` 135 | for valid values. 136 | 137 | Attributes: 138 | arg (unicode): Arg to pass to following action. 139 | config (dict): Configuration for a downstream element, such as 140 | a File Filter. 141 | icon (unicode): Filepath/UTI of icon. 142 | icontype (unicode): Type of icon. See 143 | :meth:`Workflow.add_item() ` 144 | for valid values. 145 | key (unicode): Modifier key (see above). 146 | subtitle (unicode): Override item subtitle. 147 | valid (bool): Override item validity. 148 | variables (dict): Workflow variables set by this modifier. 149 | 150 | """ 151 | 152 | def __init__(self, key, subtitle=None, arg=None, valid=None, icon=None, 153 | icontype=None): 154 | """Create a new :class:`Modifier`. 155 | 156 | Don't use this class directly (as it won't be associated with any 157 | :class:`Item3`), but rather use :meth:`Item3.add_modifier()` 158 | to add modifiers to results. 159 | 160 | Args: 161 | key (unicode): Modifier key, e.g. ``"cmd"``, ``"alt"`` etc. 162 | subtitle (unicode, optional): Override default subtitle. 163 | arg (unicode, optional): Argument to pass for this modifier. 164 | valid (bool, optional): Override item's validity. 165 | icon (unicode, optional): Filepath/UTI of icon to use 166 | icontype (unicode, optional): Type of icon. See 167 | :meth:`Workflow.add_item() ` 168 | for valid values. 169 | 170 | """ 171 | self.key = key 172 | self.subtitle = subtitle 173 | self.arg = arg 174 | self.valid = valid 175 | self.icon = icon 176 | self.icontype = icontype 177 | 178 | self.config = {} 179 | self.variables = {} 180 | 181 | def setvar(self, name, value): 182 | """Set a workflow variable for this Item. 183 | 184 | Args: 185 | name (unicode): Name of variable. 186 | value (unicode): Value of variable. 187 | 188 | """ 189 | self.variables[name] = value 190 | 191 | def getvar(self, name, default=None): 192 | """Return value of workflow variable for ``name`` or ``default``. 193 | 194 | Args: 195 | name (unicode): Variable name. 196 | default (None, optional): Value to return if variable is unset. 197 | 198 | Returns: 199 | unicode or ``default``: Value of variable if set or ``default``. 200 | 201 | """ 202 | return self.variables.get(name, default) 203 | 204 | @property 205 | def obj(self): 206 | """Modifier formatted for JSON serialization for Alfred 3. 207 | 208 | Returns: 209 | dict: Modifier for serializing to JSON. 210 | 211 | """ 212 | o = {} 213 | 214 | if self.subtitle is not None: 215 | o['subtitle'] = self.subtitle 216 | 217 | if self.arg is not None: 218 | o['arg'] = self.arg 219 | 220 | if self.valid is not None: 221 | o['valid'] = self.valid 222 | 223 | if self.variables: 224 | o['variables'] = self.variables 225 | 226 | if self.config: 227 | o['config'] = self.config 228 | 229 | icon = self._icon() 230 | if icon: 231 | o['icon'] = icon 232 | 233 | return o 234 | 235 | def _icon(self): 236 | """Return `icon` object for item. 237 | 238 | Returns: 239 | dict: Mapping for item `icon` (may be empty). 240 | 241 | """ 242 | icon = {} 243 | if self.icon is not None: 244 | icon['path'] = self.icon 245 | 246 | if self.icontype is not None: 247 | icon['type'] = self.icontype 248 | 249 | return icon 250 | 251 | 252 | class Item3(object): 253 | """Represents a feedback item for Alfred 3. 254 | 255 | Generates Alfred-compliant JSON for a single item. 256 | 257 | Don't use this class directly (as it then won't be associated with 258 | any :class:`Workflow3` object), but rather use 259 | :meth:`Workflow3.add_item() `. 260 | See :meth:`~workflow.Workflow3.add_item` for details of arguments. 261 | 262 | """ 263 | 264 | def __init__(self, title, subtitle='', arg=None, autocomplete=None, 265 | valid=False, uid=None, icon=None, icontype=None, 266 | type=None, largetext=None, copytext=None, quicklookurl=None): 267 | """Create a new :class:`Item3` object. 268 | 269 | Use same arguments as for 270 | :class:`Workflow.Item `. 271 | 272 | Argument ``subtitle_modifiers`` is not supported. 273 | 274 | """ 275 | self.title = title 276 | self.subtitle = subtitle 277 | self.arg = arg 278 | self.autocomplete = autocomplete 279 | self.valid = valid 280 | self.uid = uid 281 | self.icon = icon 282 | self.icontype = icontype 283 | self.type = type 284 | self.quicklookurl = quicklookurl 285 | self.largetext = largetext 286 | self.copytext = copytext 287 | 288 | self.modifiers = {} 289 | 290 | self.config = {} 291 | self.variables = {} 292 | 293 | def setvar(self, name, value): 294 | """Set a workflow variable for this Item. 295 | 296 | Args: 297 | name (unicode): Name of variable. 298 | value (unicode): Value of variable. 299 | 300 | """ 301 | self.variables[name] = value 302 | 303 | def getvar(self, name, default=None): 304 | """Return value of workflow variable for ``name`` or ``default``. 305 | 306 | Args: 307 | name (unicode): Variable name. 308 | default (None, optional): Value to return if variable is unset. 309 | 310 | Returns: 311 | unicode or ``default``: Value of variable if set or ``default``. 312 | 313 | """ 314 | return self.variables.get(name, default) 315 | 316 | def add_modifier(self, key, subtitle=None, arg=None, valid=None, icon=None, 317 | icontype=None): 318 | """Add alternative values for a modifier key. 319 | 320 | Args: 321 | key (unicode): Modifier key, e.g. ``"cmd"`` or ``"alt"`` 322 | subtitle (unicode, optional): Override item subtitle. 323 | arg (unicode, optional): Input for following action. 324 | valid (bool, optional): Override item validity. 325 | icon (unicode, optional): Filepath/UTI of icon. 326 | icontype (unicode, optional): Type of icon. See 327 | :meth:`Workflow.add_item() ` 328 | for valid values. 329 | 330 | Returns: 331 | Modifier: Configured :class:`Modifier`. 332 | 333 | """ 334 | mod = Modifier(key, subtitle, arg, valid, icon, icontype) 335 | 336 | for k in self.variables: 337 | mod.setvar(k, self.variables[k]) 338 | 339 | self.modifiers[key] = mod 340 | 341 | return mod 342 | 343 | @property 344 | def obj(self): 345 | """Item formatted for JSON serialization. 346 | 347 | Returns: 348 | dict: Data suitable for Alfred 3 feedback. 349 | 350 | """ 351 | # Required values 352 | o = { 353 | 'title': self.title, 354 | 'subtitle': self.subtitle, 355 | 'valid': self.valid, 356 | } 357 | 358 | # Optional values 359 | if self.arg is not None: 360 | o['arg'] = self.arg 361 | 362 | if self.autocomplete is not None: 363 | o['autocomplete'] = self.autocomplete 364 | 365 | if self.uid is not None: 366 | o['uid'] = self.uid 367 | 368 | if self.type is not None: 369 | o['type'] = self.type 370 | 371 | if self.quicklookurl is not None: 372 | o['quicklookurl'] = self.quicklookurl 373 | 374 | if self.variables: 375 | o['variables'] = self.variables 376 | 377 | if self.config: 378 | o['config'] = self.config 379 | 380 | # Largetype and copytext 381 | text = self._text() 382 | if text: 383 | o['text'] = text 384 | 385 | icon = self._icon() 386 | if icon: 387 | o['icon'] = icon 388 | 389 | # Modifiers 390 | mods = self._modifiers() 391 | if mods: 392 | o['mods'] = mods 393 | 394 | return o 395 | 396 | def _icon(self): 397 | """Return `icon` object for item. 398 | 399 | Returns: 400 | dict: Mapping for item `icon` (may be empty). 401 | 402 | """ 403 | icon = {} 404 | if self.icon is not None: 405 | icon['path'] = self.icon 406 | 407 | if self.icontype is not None: 408 | icon['type'] = self.icontype 409 | 410 | return icon 411 | 412 | def _text(self): 413 | """Return `largetext` and `copytext` object for item. 414 | 415 | Returns: 416 | dict: `text` mapping (may be empty) 417 | 418 | """ 419 | text = {} 420 | if self.largetext is not None: 421 | text['largetype'] = self.largetext 422 | 423 | if self.copytext is not None: 424 | text['copy'] = self.copytext 425 | 426 | return text 427 | 428 | def _modifiers(self): 429 | """Build `mods` dictionary for JSON feedback. 430 | 431 | Returns: 432 | dict: Modifier mapping or `None`. 433 | 434 | """ 435 | if self.modifiers: 436 | mods = {} 437 | for k, mod in self.modifiers.items(): 438 | mods[k] = mod.obj 439 | 440 | return mods 441 | 442 | return None 443 | 444 | 445 | class Workflow3(Workflow): 446 | """Workflow class that generates Alfred 3 feedback. 447 | 448 | ``Workflow3`` is a subclass of :class:`~workflow.Workflow` and 449 | most of its methods are documented there. 450 | 451 | Attributes: 452 | item_class (class): Class used to generate feedback items. 453 | variables (dict): Top level workflow variables. 454 | 455 | """ 456 | 457 | item_class = Item3 458 | 459 | def __init__(self, **kwargs): 460 | """Create a new :class:`Workflow3` object. 461 | 462 | See :class:`~workflow.Workflow` for documentation. 463 | 464 | """ 465 | Workflow.__init__(self, **kwargs) 466 | self.variables = {} 467 | self._rerun = 0 468 | self._session_id = None 469 | 470 | @property 471 | def _default_cachedir(self): 472 | """Alfred 3's default cache directory.""" 473 | return os.path.join( 474 | os.path.expanduser( 475 | '~/Library/Caches/com.runningwithcrayons.Alfred-3/' 476 | 'Workflow Data/'), 477 | self.bundleid) 478 | 479 | @property 480 | def _default_datadir(self): 481 | """Alfred 3's default data directory.""" 482 | return os.path.join(os.path.expanduser( 483 | '~/Library/Application Support/Alfred 3/Workflow Data/'), 484 | self.bundleid) 485 | 486 | @property 487 | def rerun(self): 488 | """How often (in seconds) Alfred should re-run the Script Filter.""" 489 | return self._rerun 490 | 491 | @rerun.setter 492 | def rerun(self, seconds): 493 | """Interval at which Alfred should re-run the Script Filter. 494 | 495 | Args: 496 | seconds (int): Interval between runs. 497 | """ 498 | self._rerun = seconds 499 | 500 | @property 501 | def session_id(self): 502 | """A unique session ID every time the user uses the workflow. 503 | 504 | .. versionadded:: 1.25 505 | 506 | The session ID persists while the user is using this workflow. 507 | It expires when the user runs a different workflow or closes 508 | Alfred. 509 | 510 | """ 511 | if not self._session_id: 512 | sid = os.getenv('_WF_SESSION_ID') 513 | if not sid: 514 | from uuid import uuid4 515 | sid = uuid4().hex 516 | self.setvar('_WF_SESSION_ID', sid) 517 | 518 | self._session_id = sid 519 | 520 | return self._session_id 521 | 522 | def setvar(self, name, value): 523 | """Set a "global" workflow variable. 524 | 525 | These variables are always passed to downstream workflow objects. 526 | 527 | If you have set :attr:`rerun`, these variables are also passed 528 | back to the script when Alfred runs it again. 529 | 530 | Args: 531 | name (unicode): Name of variable. 532 | value (unicode): Value of variable. 533 | 534 | """ 535 | self.variables[name] = value 536 | 537 | def getvar(self, name, default=None): 538 | """Return value of workflow variable for ``name`` or ``default``. 539 | 540 | Args: 541 | name (unicode): Variable name. 542 | default (None, optional): Value to return if variable is unset. 543 | 544 | Returns: 545 | unicode or ``default``: Value of variable if set or ``default``. 546 | 547 | """ 548 | return self.variables.get(name, default) 549 | 550 | def add_item(self, title, subtitle='', arg=None, autocomplete=None, 551 | valid=False, uid=None, icon=None, icontype=None, 552 | type=None, largetext=None, copytext=None, quicklookurl=None): 553 | """Add an item to be output to Alfred. 554 | 555 | See :meth:`Workflow.add_item() ` for the 556 | main documentation. 557 | 558 | The key difference is that this method does not support the 559 | ``modifier_subtitles`` argument. Use the :meth:`~Item3.add_modifier()` 560 | method instead on the returned item instead. 561 | 562 | Returns: 563 | Item3: Alfred feedback item. 564 | 565 | """ 566 | item = self.item_class(title, subtitle, arg, 567 | autocomplete, valid, uid, icon, icontype, type, 568 | largetext, copytext, quicklookurl) 569 | 570 | self._items.append(item) 571 | return item 572 | 573 | @property 574 | def _session_prefix(self): 575 | """Filename prefix for current session.""" 576 | return '_wfsess-{0}-'.format(self.session_id) 577 | 578 | def _mk_session_name(self, name): 579 | """New cache name/key based on session ID.""" 580 | return '{0}{1}'.format(self._session_prefix, name) 581 | 582 | def cache_data(self, name, data, session=False): 583 | """Cache API with session-scoped expiry. 584 | 585 | .. versionadded:: 1.25 586 | 587 | Args: 588 | name (str): Cache key 589 | data (object): Data to cache 590 | session (bool, optional): Whether to scope the cache 591 | to the current session. 592 | 593 | ``name`` and ``data`` are the same as for the 594 | :meth:`~workflow.Workflow.cache_data` method on 595 | :class:`~workflow.Workflow`. 596 | 597 | If ``session`` is ``True``, then ``name`` is prefixed 598 | with :attr:`session_id`. 599 | 600 | """ 601 | if session: 602 | name = self._mk_session_name(name) 603 | 604 | return super(Workflow3, self).cache_data(name, data) 605 | 606 | def cached_data(self, name, data_func=None, max_age=60, session=False): 607 | """Cache API with session-scoped expiry. 608 | 609 | .. versionadded:: 1.25 610 | 611 | Args: 612 | name (str): Cache key 613 | data_func (callable): Callable that returns fresh data. It 614 | is called if the cache has expired or doesn't exist. 615 | max_age (int): Maximum allowable age of cache in seconds. 616 | session (bool, optional): Whether to scope the cache 617 | to the current session. 618 | 619 | ``name``, ``data_func`` and ``max_age`` are the same as for the 620 | :meth:`~workflow.Workflow.cached_data` method on 621 | :class:`~workflow.Workflow`. 622 | 623 | If ``session`` is ``True``, then ``name`` is prefixed 624 | with :attr:`session_id`. 625 | 626 | """ 627 | if session: 628 | name = self._mk_session_name(name) 629 | 630 | return super(Workflow3, self).cached_data(name, data_func, max_age) 631 | 632 | def clear_session_cache(self, current=False): 633 | """Remove session data from the cache. 634 | 635 | .. versionadded:: 1.25 636 | .. versionchanged:: 1.27 637 | 638 | By default, data belonging to the current session won't be 639 | deleted. Set ``current=True`` to also clear current session. 640 | 641 | Args: 642 | current (bool, optional): If ``True``, also remove data for 643 | current session. 644 | 645 | """ 646 | def _is_session_file(filename): 647 | if current: 648 | return filename.startswith('_wfsess-') 649 | return filename.startswith('_wfsess-') \ 650 | and not filename.startswith(self._session_prefix) 651 | 652 | self.clear_cache(_is_session_file) 653 | 654 | @property 655 | def obj(self): 656 | """Feedback formatted for JSON serialization. 657 | 658 | Returns: 659 | dict: Data suitable for Alfred 3 feedback. 660 | 661 | """ 662 | items = [] 663 | for item in self._items: 664 | items.append(item.obj) 665 | 666 | o = {'items': items} 667 | if self.variables: 668 | o['variables'] = self.variables 669 | if self.rerun: 670 | o['rerun'] = self.rerun 671 | return o 672 | 673 | def send_feedback(self): 674 | """Print stored items to console/Alfred as JSON.""" 675 | json.dump(self.obj, sys.stdout) 676 | sys.stdout.flush() 677 | --------------------------------------------------------------------------------