def get_text(self): if 'input' in self.opts: if self.opts['input'] == 'stdin': import sys text = sys.stdin.read() elif self.opts['input'] == 'clipboard': text = \ SelectionClipboard.get_text() \ or Clipboard.get_text() else: raise AssertionError('Unknown input type: %s' % self.opts['input']) else: text = self.opts.get('text') if text and 'encoding' in self.opts: if self.opts['encoding'] == 'base64': import base64 text = base64.b64decode(text).decode('UTF-8') elif self.opts['encoding'] == 'url': from zim.parsing import url_decode, URL_ENCODE_DATA text = url_decode(text, mode=URL_ENCODE_DATA) else: raise AssertionError('Unknown encoding: %s' % self.opts['encoding']) assert isinstance(text, str), '%r is not decoded' % text return text
def get_text(self): if 'input' in self.opts: if self.opts['input'] == 'stdin': import sys text = sys.stdin.read() elif self.opts['input'] == 'clipboard': text = \ SelectionClipboard.get_text() \ or Clipboard.get_text() else: raise AssertionError, 'Unknown input type: %s' % self.opts['input'] else: text = self.opts.get('text') if text and 'encoding' in self.opts: if self.opts['encoding'] == 'base64': import base64 text = base64.b64decode(text) elif self.opts['encoding'] == 'url': from zim.parsing import url_decode, URL_ENCODE_DATA text = url_decode(text, mode=URL_ENCODE_DATA) else: raise AssertionError, 'Unknown encoding: %s' % self.opts['encoding'] if text and not isinstance(text, unicode): text = text.decode('utf-8') return text
def decode_urls(self): """Calls decode_url() on all links that contain urls""" for link in self.getiterator("link"): href = link.attrib["href"] if is_url_re.match(href): link.attrib["href"] = url_decode(href) if link.text == href: link.text = link.attrib["href"]
def decode_urls(self, mode=URL_ENCODE_READABLE): '''Calls decode_url() on all links that contain urls. See zim.parsing for details. Modifies the parse tree. ''' for link in self._etree.getiterator('link'): href = link.attrib['href'] if href and is_url_re.match(href): link.attrib['href'] = url_decode(href, mode=mode) if link.text == href: link.text = link.attrib['href']
def decode_urls(self, mode=URL_ENCODE_READABLE): '''Calls decode_url() on all links that contain urls. See zim.parsing for details. Modifies the parse tree. ''' for link in self._etree.getiterator('link'): href = link.attrib['href'] if is_url_re.match(href): link.attrib['href'] = url_decode(href, mode=mode) if link.text == href: link.text = link.attrib['href']
def build_notebook(location): '''Create a L{Notebook} object for a file location Tries to automount file locations first if needed @param location: a L{FilePath} or a L{NotebookInfo} @returns: a L{Notebook} object and a L{Path} object or C{None} @raises FileNotFoundError: if file location does not exist and could not be mounted ''' uri = location.uri page = None # Decipher zim+file:// uris if uri.startswith('zim+file://'): uri = uri[4:] if '?' in uri: uri, page = uri.split('?', 1) page = url_decode(page) page = Path(page) # Automount if needed filepath = FilePath(uri) if not (filepath.exists() or filepath.__add__('zim.notebook').exists()): # The folder of a mount point can exist, so check for specific content mount_notebook(filepath) if not filepath.exists(): raise FileNotFoundError(filepath) # Figure out the notebook dir if filepath.isdir(): dir = Dir(uri) file = None else: file = File(uri) dir = file.dir if file and file.basename == 'notebook.zim': file = None else: parents = list(dir) parents.reverse() for parent in parents: if parent.file('notebook.zim').exists(): dir = parent break # Resolve the page for a file if file: path = file.relpath(dir) if '.' in path: path, _ = path.rsplit('.', 1) # remove extension path = path.replace('/', ':') page = Path(path) # And finally create the notebook notebook = Notebook.new_from_dir(dir) return notebook, page
def link_notebook(self, url): if url.startswith('zim+'): url = url[4:] if '?' in url: uri, path = url.split('?') # FIXME: code below is not robust because we don't know the # storage mode of linked notebook... path = url_decode(path) # was already encoded by interwiki_link() path = encode_filename(path).replace(' ', '_') return uri + '/' + url_encode(path) + '.txt' else: return url
def normalize_win32_share(path): if os.name == 'nt': if path.startswith('smb://'): # smb://host/share/.. -> \\host\share\.. path = path[4:].replace('/', '\\') path = url_decode(path) else: if path.startswith('\\\\'): # \\host\share\.. -> smb://host/share/.. path = 'smb:' + path.replace('\\', '/') path = url_encode(path) return path
def _link_notebook(self, link): if link.startswith('zim+'): link = link[4:] if '?' in link: link, path = link.split('?') # FIXME: code below is not robust because we don't know the # storage mode of linked notebook... path = url_decode(path) # was already encoded by interwiki_link() path = encode_filename(path).replace(' ', '_') return link + '/' + url_encode(path) + '.txt' else: return link
def _parse_uri(uri): # Spec is file:/// or file://host/ # But file:/ is sometimes used by non-compliant apps # Windows uses file:///C:/ which is compliant if uri.startswith('file:///'): uri = uri[7:] elif uri.startswith('file://localhost/'): uri = uri[16:] elif uri.startswith('file://'): assert False, 'Can not handle non-local file uris' elif uri.startswith('file:/'): uri = uri[5:] else: assert False, 'Not a file uri: %s' % uri return url_decode(uri)
def _split_file_url(url): scheme, path = url.replace('\\', '/').split(':/', 1) if scheme not in ('file', 'smb'): raise ValueError('Not a file URL: %s' % url) if path.startswith('/localhost/'): # exact 2 '/' before 'localhost' path = path[11:] isshare = False elif scheme == 'smb' or re.match('^/\w', path): # exact 2 '/' before 'localhost' isshare = True else: isshare = False # either 'file:/' or 'file:///' return url_decode(path).strip('/').split('/'), isshare
def normalize_win32_share(path): '''Translates paths for windows shares in the platform specific form. So on windows it translates C{smb://} URLs to C{\\host\share} form, and vice versa on all other platforms. Just returns the original path if it was already in the right form, or when it is not a path for a share drive. @param path: a filesystem path or URL @returns: the platform specific path or the original input path ''' if os.name == 'nt': if path.startswith('smb://'): # smb://host/share/.. -> \\host\share\.. path = path[4:].replace('/', '\\') path = url_decode(path) else: if path.startswith('\\\\'): # \\host\share\.. -> smb://host/share/.. path = 'smb:' + url_encode(path.replace('\\', '/')) return path
def parse_image_url(self, url): '''Parse urls style options for images like "foo.png?width=500" and returns a dict with the options. The base url will be in the dict as 'src'. ''' i = url.find('?') if i > 0: attrib = {'src': url[:i]} for option in url[i + 1:].split('&'): if option.find('=') == -1: logger.warn('Mal-formed options in "%s"', url) break k, v = option.split('=', 1) if k in ('width', 'height', 'type', 'href'): if len(v) > 0: value = url_decode(v, mode=URL_ENCODE_DATA) attrib[str(k)] = value # str to avoid unicode key else: logger.warn('Unknown attribute "%s" in "%s"', k, url) return attrib else: return {'src': url}
def parse_image_url(self, url): '''Parse urls style options for images like "foo.png?width=500" and returns a dict with the options. The base url will be in the dict as 'src'. ''' i = url.find('?') if i > 0: attrib = {'src': url[:i]} for option in url[i+1:].split('&'): if option.find('=') == -1: logger.warn('Mal-formed options in "%s"' , url) break k, v = option.split('=', 1) if k in ('width', 'height', 'type', 'href'): if len(v) > 0: value = url_decode(v, mode=URL_ENCODE_DATA) attrib[str(k)] = value # str to avoid unicode key else: logger.warn('Unknown attribute "%s" in "%s"', k, url) return attrib else: return {'src': url}
def main(*args): options = {} template_options = {} for arg in args: if arg.startswith('option:'): arg = arg[7:] dict = template_options else: dict = options if '=' in arg: key, value = arg.split('=', 1) dict[key] = value else: dict[arg] = True #~ print 'OPTIONS:', options, template_options if 'help' in options: print usagehelp return if 'notebook' in options: notebook, page = resolve_notebook(options['notebook']) else: notebook = None if 'append' in options: if options['append'].lower() == 'true': options['append'] = True else: options['append'] = False if 'input' in options: if options['input'] == 'stdin': import sys text = sys.stdin.read() elif options['input'] == 'clipboard': text = \ SelectionClipboard.get_text() \ or Clipboard.get_text() else: text = options.get('text') if text and options.get('encoding'): if options['encoding'] == 'base64': import base64 text = base64.b64decode(text) elif options['encoding'] == 'url': from zim.parsing import url_decode, URL_ENCODE_DATA text = url_decode(text, mode=URL_ENCODE_DATA) else: raise AssertionError, 'Unknown encoding: %s' % options['encoding'] if text and not isinstance(text, unicode): text = text.decode('utf-8') icon = data_file('zim.png').path gtk_window_set_default_icon() dialog = QuickNoteDialog(None, notebook, options.get('namespace'), options.get('basename'), options.get('append'), text, template_options, options.get('attachments') ) dialog.run()
def main(*args): options = {} template_options = {} for arg in args: if arg.startswith("option:"): arg = arg[7:] dict = template_options else: dict = options if "=" in arg: key, value = arg.split("=", 1) dict[key] = value else: dict[arg] = True # ~ print 'OPTIONS:', options, template_options if "help" in options: print usagehelp return if "notebook" in options: notebook, page = resolve_notebook(options["notebook"]) else: notebook = None if "append" in options: if options["append"].lower() == "true": options["append"] = True else: options["append"] = False if "input" in options: if options["input"] == "stdin": import sys text = sys.stdin.read() elif options["input"] == "clipboard": text = SelectionClipboard.get_text() or Clipboard.get_text() else: text = options.get("text") if text and options.get("encoding"): if options["encoding"] == "base64": import base64 text = base64.b64decode(text) elif options["encoding"] == "url": from zim.parsing import url_decode, URL_ENCODE_DATA text = url_decode(text, mode=URL_ENCODE_DATA) else: raise AssertionError, "Unknown encoding: %s" % options["encoding"] if text and not isinstance(text, unicode): text = text.decode("utf-8") icon = data_file("zim.png").path gtk_window_set_default_icon() dialog = QuickNoteDialog( None, notebook, options.get("namespace"), options.get("basename"), options.get("append"), text, template_options, options.get("attachments"), ) dialog.run()