def getTemplate(): # Get template path from previous wf step template = Tools.getEnv('template_path') notes_path = md.getNotesPath() default_template = getDefaultTemplate() return Tools.strJoin(notes_path, default_template) if template == str() else template
def getTargetFilePath(file_name): file_path = Tools.strJoin(p, file_name, ext) if os.path.isfile(file_path): new_file_name = Tools.strJoin( file_name, ' ', MyNotes.Search.getTodayDate(getDefaultDate())) file_path = Tools.strJoin(p, new_file_name, ext) return file_path
def _match(self, search_terms, content, operator): content = content.lower() content = Tools.strReplace(content, self.REPL_MAP) word_list = content.split(' ') word_list = [Tools.chop(w, '#') for w in word_list] search_terms = [s.lower().encode('unicode_escape') for s in search_terms] match = False matches = list() for st in search_terms: search_str = st.replace('*', str()) # search if search term contains a whitespace if ' ' in st: regexp = re.compile(r'({0})'.format(st), re.I) match = True if len(re.findall(regexp, content)) > 0 else False # search if wildcard search in the end elif st.endswith('*'): match_list = [x for x in word_list if x.startswith(search_str)] match = True if len(match_list) > 0 else False # search if wildcard search in front elif st.startswith('*'): match_list = [x for x in word_list if x.endswith(search_str)] match = True if len(match_list) > 0 else False # search if exact match is true elif self.exact_match: match = True if search_str in word_list else False # search with exact match is false else: match = True if search_str in str(word_list) else False matches.append(match) match = all(matches) if operator == 'AND' else any(matches) return match
def getTargetFilePath(file_name): file_path = Tools.strJoin(p, file_name, ext) if os.path.isfile(file_path): new_file_name = Tools.strJoin( file_name, ' ', MyNotes.Search.getTodayDate("%d.%m.%Y %H.%M")) file_path = Tools.strJoin(p, new_file_name, ext) return file_path
def __init__(self): """Workflow data represenative """ self.wf_directory = Tools.getEnv('alfred_preferences') + "/workflows" exclude_disabled = Tools.getEnv('exclude_disabled').lower() self.exclude_disabled = True if exclude_disabled == "true" else False self.workflows = self._get_workflows_list()
def getMediaFolder(): notes_path = Tools.getNotesPath() media_dir = Tools.settings('resourcesSubfolder', 'media') media_path = os.path.join(notes_path, media_dir) if not (os.path.exists(media_path)): os.mkdir(media_path) return media_path
def getUrlScheme(f): """ Gets the URL Scheme setup in Alfred Preferences Args: f(str): md file to add at the end of url scheme Returns: str: URL scheme """ url_scheme = Tools.getEnv('url_scheme') return Tools.strJoin(url_scheme, urllib.pathname2url(f))
def __init__(self): self.allowed_extensions = self._getAllowedExtensions() self.default_date_format = os.getenv('default_date_format') self.default_extension = self._getDefaultExtension() self.exact_match = True if os.getenv('exact_match') == 'True' else False self.path = Tools.getNotesPath() self.prefer_filename_to_title = True if os.getenv('prefer_filename_to_title') == 'True' else False self.prefer_zettel_id_links = True if os.getenv('prefer_zettel_id_links') == 'True' else False self.search_content = True if os.getenv('search_content') == 'True' else False self.search_yaml_tags_only = True if os.getenv('search_yaml_tags_only') == 'True' else False self.template_tag = os.getenv('template_tag') self.use_zettel_id = Tools.settings('isUsingIDForNewFiles', True) self.use_zettel_id_in_title = True if os.getenv('use_zettel_id_in_title') == 'True' else False
def getDefaultTemplate(): """ Read default template setting from environment variable :return: default template file name """ template = Tools.getEnv('default_template') return 'template.md' if template == str() else template
def getTargetFilePath(self, file_name): """ construct markdown file path Returns: str: markdown file path """ file_name = file_name.rstrip().lstrip() file_path = Tools.strJoin(self.path, file_name, self.extension) if os.path.isfile(file_path): new_file_name = Tools.strJoin( file_name, ' ', self.getTodayDate('%d-%m-%Y %H-%M-%S')) file_path = Tools.strJoin(self.path, new_file_name, self.extension) return file_path
def _markdownHeader(self): return "---\n" \ "Title: {title}\n" \ "Created: {date}\n" \ "Tags: #WebClip\n" \ "Url: {url}\n" \ "---\n".format(date=Tools.getTodayDate(), url=self.getMdUrl(), title=self.getTitle())
def getDefaultDate(): """ Read default date format from environment variable :return: default date format file name or default format """ d = Tools.getEnv('default_date_format') return "%d.%m.%Y %H.%M" if d == str() else d
def getTargetFilePath(self, file_name): file_name = file_name.rstrip().lstrip() file_path = os.path.join(self.path, file_name + self.default_extension) if os.path.isfile(file_path): new_file_name = Tools.increment(file_name) return self.getTargetFilePath(new_file_name) file_path = os.path.join(self.path, file_name + self.default_extension) return file_path
def get_cache_directory(): """Get Alfreds Cache Directory, if not existent the directory will be created Returns: str: Cache Directory """ target_dir = Tools.getEnv('alfred_workflow_cache') if not (os.path.isdir(target_dir)): os.mkdir(target_dir) return target_dir
def _create_evernote_note(self, notebook, filename): # Create the new note note = Types.Note() # Chop extension from filename and use it as note title note.title = Tools.chop(os.path.basename(filename), self.ext) note.notebookGuid = notebook.guid note.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' note.content += '<en-note>' md_content = self._get_md_content(filename) # Get Tag List from YAML Fonter tag_list = self._get_tag_list(md_content) # Remove YAML Fronter tags md_content = self._remove_yaml_fronter(md_content) # Read image links from MD file_list_in_md = self._get_images_in_md(md_content) # TODO: move to method file_hash_dict = dict() res = list() for f in file_list_in_md: file_path = os.path.join(self.notes_path, self._url_decode(f)) with open(file_path, 'rb') as the_file: image = the_file.read() md5 = hashlib.md5() md5.update(image) the_hash = md5.digest() data = Types.Data() data.size = len(image) data.bodyHash = the_hash data.body = image resource = Types.Resource() resource.mime = mimetypes.guess_type(file_path)[0] resource.data = data # Now, add the new Resource to the note's list of resources res.append(resource) hash_hex = binascii.hexlify(the_hash) file_hash_dict.update({f: hash_hex}) # Replace MD Link with ENML Link note.resources = res # Add Tag list from YAML note.tagNames = tag_list for md_link, hash_hex in file_hash_dict.items(): en_link = '<en-media type="image/png" hash="' + hash_hex + '"/>' md_content = self._exhange_image_links( md_content, md_link, en_link) enml = markdown2.markdown(md_content).encode('utf-8') note.content += self.remove_invalid_urls(enml) note.content += '</en-note>' return note
def getTemplate(self, template_path): """ Get template path from previous wf step, reads env variable Returns: str: path to template.md """ notes_path = self.path default_template = self.getDefaultTemplate() return Tools.strJoin( notes_path, default_template) if template_path == str() else template_path
def readTemplate(file_path, **kwargs): template_tag = Tools.getEnv('template_tag') if '#' not in template_tag or template_tag == str(): template_tag = '#Template' if os.path.exists(file_path): with open(file_path, "r") as f: content = f.read() else: content = fallback_content() content = content.replace(template_tag, '') for k, v in kwargs.iteritems(): content = content.replace('{' + k + '}', v) return content
def create_hint_file(wf_dir,content): target_dir = Tools.getEnv('alfred_workflow_cache') if not(os.path.isdir(target_dir)): os.mkdir(target_dir) spath = os.path.normpath(wf_dir).split(os.sep) wf_dir_name = ''.join([i for i in spath if str(i).startswith('user.workflow')]) if wf_dir_name != str(): target_file = target_dir + '/' + wf_dir_name + '.md' if os.path.isfile(target_file): os.remove(target_file) with open(target_file, "w+") as f: f.write(content) return target_file
def createNote(self): try: with open(self.note_path, "w+") as f: file_content = self.readTemplate( content=self.content, date=Tools.getTodayDate(), tags=self.tags, title=self.title, zettel_id=self.zettel_id, ) f.write(file_content) return self.note_path except Exception as e: sys.stderr.write(e)
def getTargetFilePath(self, file_name): """ construct markdown file path Returns: str: markdown file path """ file_name = file_name.rstrip().lstrip() # TODO: Delete # file_path = Tools.strJoin(self.path, file_name, self.extension) file_path = os.path.join(self.path, "{0}{1}".format(file_name, self.extension)) if os.path.isfile(file_path): new_file_name = Tools.strJoin( file_name, ' ', self.getTodayDate('%d-%m-%Y %H-%M-%S')) # TODO: Delete # file_path = Tools.strJoin(self.path, new_file_name, self.extension) file_path = os.path.join( self.path, "{0}{1}".format(new_file_name, self.extension)) return file_path
def write_config(key, val): value = Tools.normalize(val) Plist().setVariable(key, value)
quicklookurl=u"{0}/docs/{1}.md".format(workflow_dir, variable), subtitle=u"Value: {0} (\u21E7 for Help)".format(v_subtitle), title=variable, ) icon = 'icons/check.png' if value != str( ) else 'icons/question.png' items.setIcon(icon, 'image') items.addItem() def write_config(key, val): value = Tools.normalize(val) Plist().setVariable(key, value) query = Tools.getArgv(1) action_key_value = Tools.getEnv('action_key_value') [action, key, value] = action_key_value.split('|') if action_key_value != str() else [ str(), str(), str() ] workflow_dir = os.getcwd() query = Tools.getArgv(1) items = Items() if action == str(): print_config(query) elif action == 'selection': get_selection(key, query) else:
@staticmethod def console_log(msg): # Create a custom logger logger = logging.getLogger(__name__) # Create handlers c_handler = logging.StreamHandler() c_handler.setLevel(logging.WARN) # Create formatters and add it to handlers c_format = logging.Formatter('%(message)s') c_handler.setFormatter(c_format) # Add handlers to the logger logger.addHandler(c_handler) logger.warn(msg) auth_token = Tools.getEnv('evernote_auth_token') f_path = Tools.getArgv(1) # f_path = '/Users/jjung/Documents/Notes/test evernote import.md' if auth_token == str(): Tools.notify('Evernote authentication error', 'Set Evernote AuthToken in worfklow configuration!') sys.exit("Error") elif f_path != str(): p = EvernoteUpload(auth_token) note_app_link = p.upload_to_notebook(f_path, 'Inbox') if note_app_link is not str(): Tools.notify('Upload in progress', 'The Note will be opened once uploaded!') sys.stdout.write(note_app_link) else: Tools.notify("Something went wrong")
for query in files_to_delete: file_path, last_query = getFileQuery(query) if os.path.isfile(file_path) and file_path.endswith(ext): file_name = os.path.basename(file_path) # Search for links to other assets and delete each file parent = mn.getNotesPath() assetfile_links = getAssetsLinks(parent, file_path) is_assetfile_deleted = False for l in assetfile_links: # Avoid Markdown file removal if not (l.endswith(ext)): is_assetfile_deleted = rmFile(l) # Delete Assets Folder remove_ext = len(ext) assets_path = Tools.strJoin(file_path[:-remove_ext], ".assets") assets_path_legacy = Tools.strJoin(file_path[:-remove_ext]) is_asset_deleted = rmDir(assets_path) or rmDir( assets_path_legacy) or is_assetfile_deleted # Finally delete the MD File is_file_deleted = rmFile(file_path) # Create Notification Message if len(files_to_delete) == 1: return_text = '- MD Note DELETED' if is_file_deleted else "Cannot delete file: {0}".format( file_name) return_text += '\n- Assets DELETED' if is_asset_deleted else str() if len(files_to_delete) > 1: return_text = "{0} Notes and coresponding Assets deleted".format(
to_replace = ['/', '\\', ':', '|'] tmp = f.decode('utf-8').strip() for i in to_replace: tmp = tmp.replace(i, '-') return tmp.encode('utf-8') def writeMarkdown(md_content, md_path): with open(md_path, "w+") as f: f.write(md_content.encode('utf-8')) mn = MyNotes.Search() ext = mn.getNotesExtension() p = mn.getNotesPath() argv = Tools.getArgv(1) url = argv if argv.startswith( 'http://') or argv.startswith('https://') else str() # TODO: When HTML is not fetchable, the URL will be used. # Fix formatting from <url> to markdown url [title](url) if url: markdown = Markdown(url) today = markdown.getTodayDate(fmt="%d.%m.%Y") today_time = markdown.getTodayDate(fmt="%d-%m-%Y %H-%M") md = markdown.getMarkdownContent() file_name = parseFilename(markdown.getTitle()) if file_name == str(): file_name = Tools.strJoin('WebClip from ', today_time) fPath = mn.strJoin(p, file_name, ext)
def path_to_bookmarks(): user_dir = os.path.expanduser('~') bm = user_dir + BRAVE_BOOKMARKS bm_dev = user_dir + BRAVE_DEV_BOOKMARKS if os.path.isfile(bm): return bm elif os.path.isfile(bm_dev): return bm_dev def get_json_from_file(file): return json.load(codecs.open(file, 'r', 'utf-8-sig'))['roots'] wf = Items() query = Tools.getArgv(1) if Tools.getArgv(1) is not None else str() bookmarks_file = path_to_bookmarks() if bookmarks_file is not None: bm_json = get_json_from_file(bookmarks_file) bookmarks = get_all_urls(bm_json) for bm in bookmarks: name = bm.get('name') url = bm.get('url') if query == str() or query.lower() in name.lower(): wf.setItem(title=name, subtitle=url, arg=url, quicklookurl=url) wf.addItem() if wf.getItemsLengths() == 0: wf.setItem(title='No Bookmark found!', subtitle='Search \"%s\" in Google...' % query,
#!/usr/bin/python # -*- coding: utf-8 -*- from Alfred import Items, Tools from MyNotes import Search query = Tools.getArgv(1) bmt = Tools.getEnv('bookmark_tag') bookmark_tag = bmt if bmt.startswith('#') else '#' + bmt search_terms = '{0}&{1}'.format(bookmark_tag, query) if query else bookmark_tag notes = Search() search_terms, _ = notes.get_search_config(search_terms) matches = notes.url_search(search_terms) alf = Items() if matches: for m in matches: note_title = m.get('title') note_path = m.get('path') links = m.get('links') for l in links: url_title = l.get('url_title') url = l.get('url') # subtitle = '%s > %s' % (url_title, url) if url_title != url else url subtitle = 'NOTE: {0} URL: {1}...'.format(note_title, url[:30]) alf.setItem( title=url_title, subtitle=subtitle, arg=url,
#!/usr/bin/python from Alfred import Items, Tools target_dir = Tools.getEnv('directory') wf = Items() # Back Item wf.setItem(title="BACK", subtitle="Back to List", arg='{0}|{1}'.format(target_dir, "BACK")) wf.setIcon(m_path="back.png", m_type="image") wf.addItem() # Purge Dir Item wf.setItem(title="Purge Directory", subtitle='Purge "{}"'.format(target_dir), arg='{0}|{1}'.format(target_dir, "PURGE")) wf.setIcon(m_path="purge.png", m_type="image") wf.addItem() # Delete Item wf.setItem(title="Remove Folder", subtitle='Remove "{}" from configuration'.format(target_dir), arg='{0}|{1}'.format(target_dir, "DELETE")) wf.setIcon(m_path="delete.png", m_type="image") wf.addItem() wf.write()
#!/usr/bin/env python # encoding: utf-8 from Alfred import Items, Tools from Notes import Notes, Search items = Items() notes = Notes() search = Search() zettel_id = Tools.getZettelId() query = Tools.getArgv(1) query_alt = u"{0} {1}".format(zettel_id, query) zettel_action = u"\u2318 Add Zettel ID" paste_action = u"\u2325 Paste clipboard" quicklook_action = u"\u21E7 Quicklook" if notes.useZettelId(): query_alt = query query = u"{0} {1}".format(zettel_id, query_alt) zettel_action = u"\u2318 Remove Zettel ID" items.setItem( arg=u"{0}||".format(query), subtitle=u"\"{0}\" ({1}, {2})".format(query, zettel_action, paste_action), title="Create note", ) items.addMod( arg=u"{0}||".format(query_alt), key="cmd", subtitle=u"\"{0}\" ({1})".format(query_alt, paste_action), )
#!/usr/bin/python import json import os from Alfred import Items, Tools # 1Password Cache Dir CACHE_BASE_DIR = "Library/Containers/com.agilebits.onepassword7/Data/Library/Caches/Metadata/1Password" user_dir = os.path.expanduser('~') pass_lib = os.path.join(user_dir, CACHE_BASE_DIR) query = Tools.getArgv(1) vaults = Tools.getEnv('vaultNames').split(',') def get_passwords(pass_lib): """ Get all Password items stored in 1Password Args: pass_lib (str): Path to 1Password libraries including user roort Returns: list(dict): list of dictonaries contain all Passwords """ passwords = list() for r, d, f in os.walk(pass_lib): for file in f: file_path = os.path.join(r, file) with open(file_path, 'r') as content: