repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
rossant/ipymd | ipymd/core/format_manager.py | FormatManager.create_writer | def create_writer(self, name, *args, **kwargs):
"""Create a new writer instance for a given format."""
self._check_format(name)
return self._formats[name]['writer'](*args, **kwargs) | python | def create_writer(self, name, *args, **kwargs):
"""Create a new writer instance for a given format."""
self._check_format(name)
return self._formats[name]['writer'](*args, **kwargs) | Create a new writer instance for a given format. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L208-L211 |
rossant/ipymd | ipymd/core/format_manager.py | FormatManager.convert | def convert(self,
contents_or_path,
from_=None,
to=None,
reader=None,
writer=None,
from_kwargs=None,
to_kwargs=None,
):
"""Convert contents between supported formats.
Parameters
----------
contents : str
The contents to convert from.
from_ : str or None
The name of the source format. If None, this is the
ipymd_cells format.
to : str or None
The name of the target format. If None, this is the
ipymd_cells format.
reader : a Reader instance or None
writer : a Writer instance or None
from_kwargs : dict
Optional keyword arguments to pass to the reader instance.
to_kwargs : dict
Optional keyword arguments to pass to the writer instance.
"""
# Load the file if 'contents_or_path' is a path.
if _is_path(contents_or_path):
contents = self.load(contents_or_path, from_)
else:
contents = contents_or_path
if from_kwargs is None:
from_kwargs = {}
if to_kwargs is None:
to_kwargs = {}
if reader is None:
reader = (self.create_reader(from_, **from_kwargs)
if from_ is not None else None)
if writer is None:
writer = (self.create_writer(to, **to_kwargs)
if to is not None else None)
if reader is not None:
# Convert from the source format to ipymd cells.
cells = [cell for cell in reader.read(contents)]
else:
# If no reader is specified, 'contents' is assumed to already be
# a list of ipymd cells.
cells = contents
notebook_metadata = [cell for cell in cells
if cell["cell_type"] == "notebook_metadata"]
if writer is not None:
if notebook_metadata:
[cells.remove(cell) for cell in notebook_metadata]
notebook_metadata = self.clean_meta(
notebook_metadata[0]["metadata"]
)
if hasattr(writer, "write_notebook_metadata"):
writer.write_notebook_metadata(notebook_metadata)
else:
print("{} does not support notebook metadata, "
"dropping metadata: {}".format(
writer,
notebook_metadata))
# Convert from ipymd cells to the target format.
for cell in cells:
meta = self.clean_cell_meta(cell.get("metadata", {}))
if not meta:
cell.pop("metadata", None)
writer.write(cell)
return writer.contents
else:
# If no writer is specified, the output is supposed to be
# a list of ipymd cells.
return cells | python | def convert(self,
contents_or_path,
from_=None,
to=None,
reader=None,
writer=None,
from_kwargs=None,
to_kwargs=None,
):
"""Convert contents between supported formats.
Parameters
----------
contents : str
The contents to convert from.
from_ : str or None
The name of the source format. If None, this is the
ipymd_cells format.
to : str or None
The name of the target format. If None, this is the
ipymd_cells format.
reader : a Reader instance or None
writer : a Writer instance or None
from_kwargs : dict
Optional keyword arguments to pass to the reader instance.
to_kwargs : dict
Optional keyword arguments to pass to the writer instance.
"""
# Load the file if 'contents_or_path' is a path.
if _is_path(contents_or_path):
contents = self.load(contents_or_path, from_)
else:
contents = contents_or_path
if from_kwargs is None:
from_kwargs = {}
if to_kwargs is None:
to_kwargs = {}
if reader is None:
reader = (self.create_reader(from_, **from_kwargs)
if from_ is not None else None)
if writer is None:
writer = (self.create_writer(to, **to_kwargs)
if to is not None else None)
if reader is not None:
# Convert from the source format to ipymd cells.
cells = [cell for cell in reader.read(contents)]
else:
# If no reader is specified, 'contents' is assumed to already be
# a list of ipymd cells.
cells = contents
notebook_metadata = [cell for cell in cells
if cell["cell_type"] == "notebook_metadata"]
if writer is not None:
if notebook_metadata:
[cells.remove(cell) for cell in notebook_metadata]
notebook_metadata = self.clean_meta(
notebook_metadata[0]["metadata"]
)
if hasattr(writer, "write_notebook_metadata"):
writer.write_notebook_metadata(notebook_metadata)
else:
print("{} does not support notebook metadata, "
"dropping metadata: {}".format(
writer,
notebook_metadata))
# Convert from ipymd cells to the target format.
for cell in cells:
meta = self.clean_cell_meta(cell.get("metadata", {}))
if not meta:
cell.pop("metadata", None)
writer.write(cell)
return writer.contents
else:
# If no writer is specified, the output is supposed to be
# a list of ipymd cells.
return cells | Convert contents between supported formats.
Parameters
----------
contents : str
The contents to convert from.
from_ : str or None
The name of the source format. If None, this is the
ipymd_cells format.
to : str or None
The name of the target format. If None, this is the
ipymd_cells format.
reader : a Reader instance or None
writer : a Writer instance or None
from_kwargs : dict
Optional keyword arguments to pass to the reader instance.
to_kwargs : dict
Optional keyword arguments to pass to the writer instance. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L213-L299 |
rossant/ipymd | ipymd/core/format_manager.py | FormatManager.clean_meta | def clean_meta(self, meta):
"""Removes unwanted metadata
Parameters
----------
meta : dict
Notebook metadata.
"""
if not self.verbose_metadata:
default_kernel_name = (self.default_kernel_name or
self._km.kernel_name)
if (meta.get("kernelspec", {})
.get("name", None) == default_kernel_name):
del meta["kernelspec"]
meta.pop("language_info", None)
return meta | python | def clean_meta(self, meta):
"""Removes unwanted metadata
Parameters
----------
meta : dict
Notebook metadata.
"""
if not self.verbose_metadata:
default_kernel_name = (self.default_kernel_name or
self._km.kernel_name)
if (meta.get("kernelspec", {})
.get("name", None) == default_kernel_name):
del meta["kernelspec"]
meta.pop("language_info", None)
return meta | Removes unwanted metadata
Parameters
----------
meta : dict
Notebook metadata. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L301-L319 |
rossant/ipymd | ipymd/core/format_manager.py | FormatManager.clean_cell_meta | def clean_cell_meta(self, meta):
"""Remove cell metadata that matches the default cell metadata."""
for k, v in DEFAULT_CELL_METADATA.items():
if meta.get(k, None) == v:
meta.pop(k, None)
return meta | python | def clean_cell_meta(self, meta):
"""Remove cell metadata that matches the default cell metadata."""
for k, v in DEFAULT_CELL_METADATA.items():
if meta.get(k, None) == v:
meta.pop(k, None)
return meta | Remove cell metadata that matches the default cell metadata. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L321-L326 |
rossant/ipymd | ipymd/core/prompt.py | _starts_with_regex | def _starts_with_regex(line, regex):
"""Return whether a line starts with a regex or not."""
if not regex.startswith('^'):
regex = '^' + regex
reg = re.compile(regex)
return reg.match(line) | python | def _starts_with_regex(line, regex):
"""Return whether a line starts with a regex or not."""
if not regex.startswith('^'):
regex = '^' + regex
reg = re.compile(regex)
return reg.match(line) | Return whether a line starts with a regex or not. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/prompt.py#L37-L42 |
rossant/ipymd | ipymd/core/prompt.py | create_prompt | def create_prompt(prompt):
"""Create a prompt manager.
Parameters
----------
prompt : str or class driving from BasePromptManager
The prompt name ('python' or 'ipython') or a custom PromptManager
class.
"""
if prompt is None:
prompt = 'python'
if prompt == 'python':
prompt = PythonPromptManager
elif prompt == 'ipython':
prompt = IPythonPromptManager
# Instanciate the class.
if isinstance(prompt, BasePromptManager):
return prompt
else:
return prompt() | python | def create_prompt(prompt):
"""Create a prompt manager.
Parameters
----------
prompt : str or class driving from BasePromptManager
The prompt name ('python' or 'ipython') or a custom PromptManager
class.
"""
if prompt is None:
prompt = 'python'
if prompt == 'python':
prompt = PythonPromptManager
elif prompt == 'ipython':
prompt = IPythonPromptManager
# Instanciate the class.
if isinstance(prompt, BasePromptManager):
return prompt
else:
return prompt() | Create a prompt manager.
Parameters
----------
prompt : str or class driving from BasePromptManager
The prompt name ('python' or 'ipython') or a custom PromptManager
class. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/prompt.py#L231-L252 |
rossant/ipymd | ipymd/core/prompt.py | BasePromptManager.split_input_output | def split_input_output(self, text):
"""Split code into input lines and output lines, according to the
input and output prompt templates."""
lines = _to_lines(text)
i = 0
for line in lines:
if _starts_with_regex(line, self.input_prompt_regex):
i += 1
else:
break
return lines[:i], lines[i:] | python | def split_input_output(self, text):
"""Split code into input lines and output lines, according to the
input and output prompt templates."""
lines = _to_lines(text)
i = 0
for line in lines:
if _starts_with_regex(line, self.input_prompt_regex):
i += 1
else:
break
return lines[:i], lines[i:] | Split code into input lines and output lines, according to the
input and output prompt templates. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/prompt.py#L87-L97 |
rossant/ipymd | ipymd/core/contents_manager.py | IPymdContentsManager.get | def get(self, path, content=True, type=None, format=None):
""" Takes a path for an entity and returns its model
Parameters
----------
path : str
the API path that describes the relative path for the target
content : bool
Whether to include the contents in the reply
type : str, optional
The requested type - 'file', 'notebook', or 'directory'.
Will raise HTTPError 400 if the content doesn't match.
format : str, optional
The requested format for file contents. 'text' or 'base64'.
Ignored if this returns a notebook or directory model.
Returns
-------
model : dict
the contents model. If content=True, returns the contents
of the file or directory as well.
"""
path = path.strip('/')
# File extension of the chosen format.
file_extension = format_manager().file_extension(self.format)
if not self.exists(path):
raise web.HTTPError(404, u'No such file or directory: %s' % path)
os_path = self._get_os_path(path)
if os.path.isdir(os_path):
if type not in (None, 'directory'):
raise web.HTTPError(400,
u'%s is a directory, not a %s' % (path, type), reason='bad type')
model = self._dir_model(path, content=content)
elif type == 'notebook' or (type is None and
(path.endswith('.ipynb') or
path.endswith(file_extension))): # NEW
model = self._notebook_model(path, content=content)
else:
if type == 'directory':
raise web.HTTPError(400,
u'%s is not a directory', reason='bad type')
model = self._file_model(path, content=content, format=format)
return model | python | def get(self, path, content=True, type=None, format=None):
""" Takes a path for an entity and returns its model
Parameters
----------
path : str
the API path that describes the relative path for the target
content : bool
Whether to include the contents in the reply
type : str, optional
The requested type - 'file', 'notebook', or 'directory'.
Will raise HTTPError 400 if the content doesn't match.
format : str, optional
The requested format for file contents. 'text' or 'base64'.
Ignored if this returns a notebook or directory model.
Returns
-------
model : dict
the contents model. If content=True, returns the contents
of the file or directory as well.
"""
path = path.strip('/')
# File extension of the chosen format.
file_extension = format_manager().file_extension(self.format)
if not self.exists(path):
raise web.HTTPError(404, u'No such file or directory: %s' % path)
os_path = self._get_os_path(path)
if os.path.isdir(os_path):
if type not in (None, 'directory'):
raise web.HTTPError(400,
u'%s is a directory, not a %s' % (path, type), reason='bad type')
model = self._dir_model(path, content=content)
elif type == 'notebook' or (type is None and
(path.endswith('.ipynb') or
path.endswith(file_extension))): # NEW
model = self._notebook_model(path, content=content)
else:
if type == 'directory':
raise web.HTTPError(400,
u'%s is not a directory', reason='bad type')
model = self._file_model(path, content=content, format=format)
return model | Takes a path for an entity and returns its model
Parameters
----------
path : str
the API path that describes the relative path for the target
content : bool
Whether to include the contents in the reply
type : str, optional
The requested type - 'file', 'notebook', or 'directory'.
Will raise HTTPError 400 if the content doesn't match.
format : str, optional
The requested format for file contents. 'text' or 'base64'.
Ignored if this returns a notebook or directory model.
Returns
-------
model : dict
the contents model. If content=True, returns the contents
of the file or directory as well. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/contents_manager.py#L64-L107 |
rossant/ipymd | ipymd/core/contents_manager.py | IPymdContentsManager._read_notebook | def _read_notebook(self, os_path, as_version=4):
"""Read a notebook from an os path."""
with self.open(os_path, 'r', encoding='utf-8') as f:
try:
# NEW
file_ext = _file_extension(os_path)
if file_ext == '.ipynb':
return nbformat.read(f, as_version=as_version)
else:
return convert(os_path, from_=self.format, to='notebook')
except Exception as e:
raise HTTPError(
400,
u"Unreadable Notebook: %s %r" % (os_path, e),
) | python | def _read_notebook(self, os_path, as_version=4):
"""Read a notebook from an os path."""
with self.open(os_path, 'r', encoding='utf-8') as f:
try:
# NEW
file_ext = _file_extension(os_path)
if file_ext == '.ipynb':
return nbformat.read(f, as_version=as_version)
else:
return convert(os_path, from_=self.format, to='notebook')
except Exception as e:
raise HTTPError(
400,
u"Unreadable Notebook: %s %r" % (os_path, e),
) | Read a notebook from an os path. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/contents_manager.py#L110-L126 |
rossant/ipymd | ipymd/core/contents_manager.py | IPymdContentsManager.save | def save(self, model, path=''):
"""Save the file model and return the model with no content."""
path = path.strip('/')
if 'type' not in model:
raise web.HTTPError(400, u'No file type provided')
if 'content' not in model and model['type'] != 'directory':
raise web.HTTPError(400, u'No file content provided')
self.run_pre_save_hook(model=model, path=path)
os_path = self._get_os_path(path)
self.log.debug("Saving %s", os_path)
try:
if model['type'] == 'notebook':
# NEW
file_ext = _file_extension(os_path)
if file_ext == '.ipynb':
nb = nbformat.from_dict(model['content'])
self.check_and_sign(nb, path)
self._save_notebook(os_path, nb)
else:
contents = convert(model['content'],
from_='notebook',
to=self.format)
# Save a text file.
if (format_manager().file_type(self.format) in
('text', 'json')):
self._save_file(os_path, contents, 'text')
# Save to a binary file.
else:
format_manager().save(os_path, contents,
name=self.format,
overwrite=True)
# One checkpoint should always exist for notebooks.
if not self.checkpoints.list_checkpoints(path):
self.create_checkpoint(path)
elif model['type'] == 'file':
# Missing format will be handled internally by _save_file.
self._save_file(os_path, model['content'], model.get('format'))
elif model['type'] == 'directory':
self._save_directory(os_path, model, path)
else:
raise web.HTTPError(400, "Unhandled contents type: %s" % model['type'])
except web.HTTPError:
raise
except Exception as e:
self.log.error(u'Error while saving file: %s %s', path, e, exc_info=True)
raise web.HTTPError(500, u'Unexpected error while saving file: %s %s' % (path, e))
validation_message = None
if model['type'] == 'notebook':
self.validate_notebook_model(model)
validation_message = model.get('message', None)
model = self.get(path, content=False)
if validation_message:
model['message'] = validation_message
self.run_post_save_hook(model=model, os_path=os_path)
return model | python | def save(self, model, path=''):
"""Save the file model and return the model with no content."""
path = path.strip('/')
if 'type' not in model:
raise web.HTTPError(400, u'No file type provided')
if 'content' not in model and model['type'] != 'directory':
raise web.HTTPError(400, u'No file content provided')
self.run_pre_save_hook(model=model, path=path)
os_path = self._get_os_path(path)
self.log.debug("Saving %s", os_path)
try:
if model['type'] == 'notebook':
# NEW
file_ext = _file_extension(os_path)
if file_ext == '.ipynb':
nb = nbformat.from_dict(model['content'])
self.check_and_sign(nb, path)
self._save_notebook(os_path, nb)
else:
contents = convert(model['content'],
from_='notebook',
to=self.format)
# Save a text file.
if (format_manager().file_type(self.format) in
('text', 'json')):
self._save_file(os_path, contents, 'text')
# Save to a binary file.
else:
format_manager().save(os_path, contents,
name=self.format,
overwrite=True)
# One checkpoint should always exist for notebooks.
if not self.checkpoints.list_checkpoints(path):
self.create_checkpoint(path)
elif model['type'] == 'file':
# Missing format will be handled internally by _save_file.
self._save_file(os_path, model['content'], model.get('format'))
elif model['type'] == 'directory':
self._save_directory(os_path, model, path)
else:
raise web.HTTPError(400, "Unhandled contents type: %s" % model['type'])
except web.HTTPError:
raise
except Exception as e:
self.log.error(u'Error while saving file: %s %s', path, e, exc_info=True)
raise web.HTTPError(500, u'Unexpected error while saving file: %s %s' % (path, e))
validation_message = None
if model['type'] == 'notebook':
self.validate_notebook_model(model)
validation_message = model.get('message', None)
model = self.get(path, content=False)
if validation_message:
model['message'] = validation_message
self.run_post_save_hook(model=model, os_path=os_path)
return model | Save the file model and return the model with no content. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/contents_manager.py#L128-L193 |
rossant/ipymd | ipymd/formats/python.py | _split_python | def _split_python(python):
"""Split Python source into chunks.
Chunks are separated by at least two return lines. The break must not
be followed by a space. Also, long Python strings spanning several lines
are not splitted.
"""
python = _preprocess(python)
if not python:
return []
lexer = PythonSplitLexer()
lexer.read(python)
return lexer.chunks | python | def _split_python(python):
"""Split Python source into chunks.
Chunks are separated by at least two return lines. The break must not
be followed by a space. Also, long Python strings spanning several lines
are not splitted.
"""
python = _preprocess(python)
if not python:
return []
lexer = PythonSplitLexer()
lexer.read(python)
return lexer.chunks | Split Python source into chunks.
Chunks are separated by at least two return lines. The break must not
be followed by a space. Also, long Python strings spanning several lines
are not splitted. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/python.py#L86-L99 |
rossant/ipymd | ipymd/formats/python.py | _is_chunk_markdown | def _is_chunk_markdown(source):
"""Return whether a chunk contains Markdown contents."""
lines = source.splitlines()
if all(line.startswith('# ') for line in lines):
# The chunk is a Markdown *unless* it is commented Python code.
source = '\n'.join(line[2:] for line in lines
if not line[2:].startswith('#')) # skip headers
if not source:
return True
# Try to parse the chunk: if it fails, it is Markdown, otherwise,
# it is Python.
return not _is_python(source)
return False | python | def _is_chunk_markdown(source):
"""Return whether a chunk contains Markdown contents."""
lines = source.splitlines()
if all(line.startswith('# ') for line in lines):
# The chunk is a Markdown *unless* it is commented Python code.
source = '\n'.join(line[2:] for line in lines
if not line[2:].startswith('#')) # skip headers
if not source:
return True
# Try to parse the chunk: if it fails, it is Markdown, otherwise,
# it is Python.
return not _is_python(source)
return False | Return whether a chunk contains Markdown contents. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/python.py#L102-L114 |
rossant/ipymd | ipymd/formats/python.py | _add_hash | def _add_hash(source):
"""Add a leading hash '#' at the beginning of every line in the source."""
source = '\n'.join('# ' + line.rstrip()
for line in source.splitlines())
return source | python | def _add_hash(source):
"""Add a leading hash '#' at the beginning of every line in the source."""
source = '\n'.join('# ' + line.rstrip()
for line in source.splitlines())
return source | Add a leading hash '#' at the beginning of every line in the source. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/python.py#L122-L126 |
rossant/ipymd | ipymd/lib/markdown.py | _filter_markdown | def _filter_markdown(source, filters):
"""Only keep some Markdown headers from a Markdown string."""
lines = source.splitlines()
# Filters is a list of 'hN' strings where 1 <= N <= 6.
headers = [_replace_header_filter(filter) for filter in filters]
lines = [line for line in lines if line.startswith(tuple(headers))]
return '\n'.join(lines) | python | def _filter_markdown(source, filters):
"""Only keep some Markdown headers from a Markdown string."""
lines = source.splitlines()
# Filters is a list of 'hN' strings where 1 <= N <= 6.
headers = [_replace_header_filter(filter) for filter in filters]
lines = [line for line in lines if line.startswith(tuple(headers))]
return '\n'.join(lines) | Only keep some Markdown headers from a Markdown string. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/markdown.py#L647-L653 |
rossant/ipymd | ipymd/lib/markdown.py | BlockLexer.parse_lheading | def parse_lheading(self, m):
"""Parse setext heading."""
level = 1 if m.group(2) == '=' else 2
self.renderer.heading(m.group(1), level=level) | python | def parse_lheading(self, m):
"""Parse setext heading."""
level = 1 if m.group(2) == '=' else 2
self.renderer.heading(m.group(1), level=level) | Parse setext heading. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/markdown.py#L184-L187 |
rossant/ipymd | ipymd/lib/markdown.py | MarkdownWriter.ensure_newline | def ensure_newline(self, n):
"""Make sure there are 'n' line breaks at the end."""
assert n >= 0
text = self._output.getvalue().rstrip('\n')
if not text:
return
self._output = StringIO()
self._output.write(text)
self._output.write('\n' * n)
text = self._output.getvalue()
assert text[-n-1] != '\n'
assert text[-n:] == '\n' * n | python | def ensure_newline(self, n):
"""Make sure there are 'n' line breaks at the end."""
assert n >= 0
text = self._output.getvalue().rstrip('\n')
if not text:
return
self._output = StringIO()
self._output.write(text)
self._output.write('\n' * n)
text = self._output.getvalue()
assert text[-n-1] != '\n'
assert text[-n:] == '\n' * n | Make sure there are 'n' line breaks at the end. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/markdown.py#L560-L571 |
rossant/ipymd | ipymd/formats/markdown.py | BaseMarkdownReader._meta_from_regex | def _meta_from_regex(self, m):
"""Extract and parse YAML metadata from a meta match
Notebook metadata must appear at the beginning of the file and follows
the Jekyll front-matter convention of dashed delimiters:
---
some: yaml
---
Cell metadata follows the YAML spec of dashes and periods
---
some: yaml
...
Both must be followed by at least one blank line (\n\n).
"""
body = m.group('body')
is_notebook = m.group('sep_close') == '---'
if is_notebook:
# make it into a valid YAML object by stripping ---
body = body.strip()[:-3] + '...'
try:
if body:
return self._meta(yaml.safe_load(m.group('body')), is_notebook)
else:
return self._meta({'ipymd': {'empty_meta': True}}, is_notebook)
except Exception as err:
raise Exception(body, err) | python | def _meta_from_regex(self, m):
"""Extract and parse YAML metadata from a meta match
Notebook metadata must appear at the beginning of the file and follows
the Jekyll front-matter convention of dashed delimiters:
---
some: yaml
---
Cell metadata follows the YAML spec of dashes and periods
---
some: yaml
...
Both must be followed by at least one blank line (\n\n).
"""
body = m.group('body')
is_notebook = m.group('sep_close') == '---'
if is_notebook:
# make it into a valid YAML object by stripping ---
body = body.strip()[:-3] + '...'
try:
if body:
return self._meta(yaml.safe_load(m.group('body')), is_notebook)
else:
return self._meta({'ipymd': {'empty_meta': True}}, is_notebook)
except Exception as err:
raise Exception(body, err) | Extract and parse YAML metadata from a meta match
Notebook metadata must appear at the beginning of the file and follows
the Jekyll front-matter convention of dashed delimiters:
---
some: yaml
---
Cell metadata follows the YAML spec of dashes and periods
---
some: yaml
...
Both must be followed by at least one blank line (\n\n). | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/markdown.py#L77-L107 |
rossant/ipymd | ipymd/formats/markdown.py | MarkdownReader._code_cell | def _code_cell(self, source):
"""Split the source into input and output."""
input, output = self._prompt.to_cell(source)
return {'cell_type': 'code',
'input': input,
'output': output} | python | def _code_cell(self, source):
"""Split the source into input and output."""
input, output = self._prompt.to_cell(source)
return {'cell_type': 'code',
'input': input,
'output': output} | Split the source into input and output. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/markdown.py#L201-L206 |
rossant/ipymd | ipymd/utils/utils.py | _preprocess | def _preprocess(text, tab=4):
"""Normalize a text."""
text = re.sub(r'\r\n|\r', '\n', text)
text = text.replace('\t', ' ' * tab)
text = text.replace('\u00a0', ' ')
text = text.replace('\u2424', '\n')
pattern = re.compile(r'^ +$', re.M)
text = pattern.sub('', text)
text = _rstrip_lines(text)
return text | python | def _preprocess(text, tab=4):
"""Normalize a text."""
text = re.sub(r'\r\n|\r', '\n', text)
text = text.replace('\t', ' ' * tab)
text = text.replace('\u00a0', ' ')
text = text.replace('\u2424', '\n')
pattern = re.compile(r'^ +$', re.M)
text = pattern.sub('', text)
text = _rstrip_lines(text)
return text | Normalize a text. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/utils/utils.py#L37-L46 |
rossant/ipymd | ipymd/utils/utils.py | _diff | def _diff(text_0, text_1):
"""Return a diff between two strings."""
diff = difflib.ndiff(text_0.splitlines(), text_1.splitlines())
return _diff_removed_lines(diff) | python | def _diff(text_0, text_1):
"""Return a diff between two strings."""
diff = difflib.ndiff(text_0.splitlines(), text_1.splitlines())
return _diff_removed_lines(diff) | Return a diff between two strings. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/utils/utils.py#L95-L98 |
rossant/ipymd | ipymd/utils/utils.py | _write_json | def _write_json(file, contents):
"""Write a dict to a JSON file."""
with open(file, 'w') as f:
return json.dump(contents, f, indent=2, sort_keys=True) | python | def _write_json(file, contents):
"""Write a dict to a JSON file."""
with open(file, 'w') as f:
return json.dump(contents, f, indent=2, sort_keys=True) | Write a dict to a JSON file. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/utils/utils.py#L118-L121 |
rossant/ipymd | ipymd/lib/opendocument.py | _numbered_style | def _numbered_style():
"""Create a numbered list style."""
style = ListStyle(name='_numbered_list')
lls = ListLevelStyleNumber(level=1)
lls.setAttribute('displaylevels', 1)
lls.setAttribute('numsuffix', '. ')
lls.setAttribute('numformat', '1')
llp = ListLevelProperties()
llp.setAttribute('listlevelpositionandspacemode', 'label-alignment')
llla = ListLevelLabelAlignment(labelfollowedby='listtab')
llla.setAttribute('listtabstopposition', '1.27cm')
llla.setAttribute('textindent', '-0.635cm')
llla.setAttribute('marginleft', '1.27cm')
llp.addElement(llla)
# llp.setAttribute('spacebefore', '')
# llp.setAttribute('minlabelwidth', '')
lls.addElement(llp)
style.addElement(lls)
return style | python | def _numbered_style():
"""Create a numbered list style."""
style = ListStyle(name='_numbered_list')
lls = ListLevelStyleNumber(level=1)
lls.setAttribute('displaylevels', 1)
lls.setAttribute('numsuffix', '. ')
lls.setAttribute('numformat', '1')
llp = ListLevelProperties()
llp.setAttribute('listlevelpositionandspacemode', 'label-alignment')
llla = ListLevelLabelAlignment(labelfollowedby='listtab')
llla.setAttribute('listtabstopposition', '1.27cm')
llla.setAttribute('textindent', '-0.635cm')
llla.setAttribute('marginleft', '1.27cm')
llp.addElement(llla)
# llp.setAttribute('spacebefore', '')
# llp.setAttribute('minlabelwidth', '')
lls.addElement(llp)
style.addElement(lls)
return style | Create a numbered list style. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L119-L146 |
rossant/ipymd | ipymd/lib/opendocument.py | _create_style | def _create_style(name, family=None, **kwargs):
"""Helper function for creating a new style."""
if family == 'paragraph' and 'marginbottom' not in kwargs:
kwargs['marginbottom'] = '.5cm'
style = Style(name=name, family=family)
# Extract paragraph properties.
kwargs_par = {}
keys = sorted(kwargs.keys())
for k in keys:
if 'margin' in k:
kwargs_par[k] = kwargs.pop(k)
style.addElement(TextProperties(**kwargs))
if kwargs_par:
style.addElement(ParagraphProperties(**kwargs_par))
return style | python | def _create_style(name, family=None, **kwargs):
"""Helper function for creating a new style."""
if family == 'paragraph' and 'marginbottom' not in kwargs:
kwargs['marginbottom'] = '.5cm'
style = Style(name=name, family=family)
# Extract paragraph properties.
kwargs_par = {}
keys = sorted(kwargs.keys())
for k in keys:
if 'margin' in k:
kwargs_par[k] = kwargs.pop(k)
style.addElement(TextProperties(**kwargs))
if kwargs_par:
style.addElement(ParagraphProperties(**kwargs_par))
return style | Helper function for creating a new style. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L149-L163 |
rossant/ipymd | ipymd/lib/opendocument.py | default_styles | def default_styles():
"""Generate default ODF styles."""
styles = {}
def _add_style(name, **kwargs):
styles[name] = _create_style(name, **kwargs)
_add_style('heading-1',
family='paragraph',
fontsize='24pt',
fontweight='bold',
)
_add_style('heading-2',
family='paragraph',
fontsize='22pt',
fontweight='bold',
)
_add_style('heading-3',
family='paragraph',
fontsize='20pt',
fontweight='bold',
)
_add_style('heading-4',
family='paragraph',
fontsize='18pt',
fontweight='bold',
)
_add_style('heading-5',
family='paragraph',
fontsize='16pt',
fontweight='bold',
)
_add_style('heading-6',
family='paragraph',
fontsize='14pt',
fontweight='bold',
)
_add_style('normal-paragraph',
family='paragraph',
fontsize='12pt',
marginbottom='0.25cm',
)
_add_style('code',
family='paragraph',
fontsize='10pt',
fontweight='bold',
fontfamily='Courier New',
color='#555555',
)
_add_style('quote',
family='paragraph',
fontsize='12pt',
fontstyle='italic',
)
_add_style('list-paragraph',
family='paragraph',
fontsize='12pt',
marginbottom='.1cm',
)
_add_style('sublist-paragraph',
family='paragraph',
fontsize='12pt',
marginbottom='.1cm',
)
_add_style('numbered-list-paragraph',
family='paragraph',
fontsize='12pt',
marginbottom='.1cm',
)
_add_style('normal-text',
family='text',
fontsize='12pt',
)
_add_style('italic',
family='text',
fontstyle='italic',
fontsize='12pt',
)
_add_style('bold',
family='text',
fontweight='bold',
fontsize='12pt',
)
_add_style('url',
family='text',
fontsize='12pt',
fontweight='bold',
fontfamily='Courier',
)
_add_style('inline-code',
family='text',
fontsize='10pt',
fontweight='bold',
fontfamily='Courier New',
color='#555555',
)
styles['_numbered_list'] = _numbered_style()
return styles | python | def default_styles():
"""Generate default ODF styles."""
styles = {}
def _add_style(name, **kwargs):
styles[name] = _create_style(name, **kwargs)
_add_style('heading-1',
family='paragraph',
fontsize='24pt',
fontweight='bold',
)
_add_style('heading-2',
family='paragraph',
fontsize='22pt',
fontweight='bold',
)
_add_style('heading-3',
family='paragraph',
fontsize='20pt',
fontweight='bold',
)
_add_style('heading-4',
family='paragraph',
fontsize='18pt',
fontweight='bold',
)
_add_style('heading-5',
family='paragraph',
fontsize='16pt',
fontweight='bold',
)
_add_style('heading-6',
family='paragraph',
fontsize='14pt',
fontweight='bold',
)
_add_style('normal-paragraph',
family='paragraph',
fontsize='12pt',
marginbottom='0.25cm',
)
_add_style('code',
family='paragraph',
fontsize='10pt',
fontweight='bold',
fontfamily='Courier New',
color='#555555',
)
_add_style('quote',
family='paragraph',
fontsize='12pt',
fontstyle='italic',
)
_add_style('list-paragraph',
family='paragraph',
fontsize='12pt',
marginbottom='.1cm',
)
_add_style('sublist-paragraph',
family='paragraph',
fontsize='12pt',
marginbottom='.1cm',
)
_add_style('numbered-list-paragraph',
family='paragraph',
fontsize='12pt',
marginbottom='.1cm',
)
_add_style('normal-text',
family='text',
fontsize='12pt',
)
_add_style('italic',
family='text',
fontstyle='italic',
fontsize='12pt',
)
_add_style('bold',
family='text',
fontweight='bold',
fontsize='12pt',
)
_add_style('url',
family='text',
fontsize='12pt',
fontweight='bold',
fontfamily='Courier',
)
_add_style('inline-code',
family='text',
fontsize='10pt',
fontweight='bold',
fontfamily='Courier New',
color='#555555',
)
styles['_numbered_list'] = _numbered_style()
return styles | Generate default ODF styles. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L166-L267 |
rossant/ipymd | ipymd/lib/opendocument.py | load_styles | def load_styles(path_or_doc):
"""Return a dictionary of all styles contained in an ODF document."""
if isinstance(path_or_doc, string_types):
doc = load(path_or_doc)
else:
# Recover the OpenDocumentText instance.
if isinstance(path_or_doc, ODFDocument):
doc = path_or_doc._doc
else:
doc = path_or_doc
assert isinstance(doc, OpenDocument), doc
styles = {_style_name(style): style for style in doc.styles.childNodes}
return styles | python | def load_styles(path_or_doc):
"""Return a dictionary of all styles contained in an ODF document."""
if isinstance(path_or_doc, string_types):
doc = load(path_or_doc)
else:
# Recover the OpenDocumentText instance.
if isinstance(path_or_doc, ODFDocument):
doc = path_or_doc._doc
else:
doc = path_or_doc
assert isinstance(doc, OpenDocument), doc
styles = {_style_name(style): style for style in doc.styles.childNodes}
return styles | Return a dictionary of all styles contained in an ODF document. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L278-L290 |
rossant/ipymd | ipymd/lib/opendocument.py | _item_type | def _item_type(item):
"""Indicate to the ODF reader the type of the block or text."""
tag = item['tag']
style = item.get('style', None)
if tag == 'p':
if style is None or 'paragraph' in style:
return 'paragraph'
else:
return style
elif tag == 'span':
if style in (None, 'normal-text'):
return 'text'
elif style == 'url':
return 'link'
else:
return style
elif tag == 'h':
assert style is not None
return style
elif tag in ('list', 'list-item', 'line-break'):
if style == '_numbered_list':
return 'numbered-list'
else:
return tag
elif tag == 's':
return 'spaces'
raise Exception("The tag '{0}' with style '{1}' hasn't "
"been implemented.".format(tag, style)) | python | def _item_type(item):
"""Indicate to the ODF reader the type of the block or text."""
tag = item['tag']
style = item.get('style', None)
if tag == 'p':
if style is None or 'paragraph' in style:
return 'paragraph'
else:
return style
elif tag == 'span':
if style in (None, 'normal-text'):
return 'text'
elif style == 'url':
return 'link'
else:
return style
elif tag == 'h':
assert style is not None
return style
elif tag in ('list', 'list-item', 'line-break'):
if style == '_numbered_list':
return 'numbered-list'
else:
return tag
elif tag == 's':
return 'spaces'
raise Exception("The tag '{0}' with style '{1}' hasn't "
"been implemented.".format(tag, style)) | Indicate to the ODF reader the type of the block or text. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L742-L769 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument.add_styles | def add_styles(self, **styles):
"""Add ODF styles to the current document."""
for stylename in sorted(styles):
self._doc.styles.addElement(styles[stylename]) | python | def add_styles(self, **styles):
"""Add ODF styles to the current document."""
for stylename in sorted(styles):
self._doc.styles.addElement(styles[stylename]) | Add ODF styles to the current document. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L358-L361 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument._add_element | def _add_element(self, cls, **kwargs):
"""Add an element."""
# Convert stylename strings to actual style elements.
kwargs = self._replace_stylename(kwargs)
el = cls(**kwargs)
self._doc.text.addElement(el) | python | def _add_element(self, cls, **kwargs):
"""Add an element."""
# Convert stylename strings to actual style elements.
kwargs = self._replace_stylename(kwargs)
el = cls(**kwargs)
self._doc.text.addElement(el) | Add an element. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L421-L426 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument._style_name | def _style_name(self, el):
"""Return the style name of an element."""
if el.attributes is None:
return None
style_field = ('urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'style-name')
name = el.attributes.get(style_field, None)
if not name:
return None
return self._get_style_name(name) | python | def _style_name(self, el):
"""Return the style name of an element."""
if el.attributes is None:
return None
style_field = ('urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'style-name')
name = el.attributes.get(style_field, None)
if not name:
return None
return self._get_style_name(name) | Return the style name of an element. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L428-L437 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument.start_container | def start_container(self, cls, **kwargs):
"""Append a new container."""
# Convert stylename strings to actual style elements.
kwargs = self._replace_stylename(kwargs)
# Create the container.
container = cls(**kwargs)
self._containers.append(container) | python | def start_container(self, cls, **kwargs):
"""Append a new container."""
# Convert stylename strings to actual style elements.
kwargs = self._replace_stylename(kwargs)
# Create the container.
container = cls(**kwargs)
self._containers.append(container) | Append a new container. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L449-L455 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument.end_container | def end_container(self, cancel=None):
"""Finishes and registers the currently-active container, unless
'cancel' is True."""
if not self._containers:
return
container = self._containers.pop()
if len(self._containers) >= 1:
parent = self._containers[-1]
else:
parent = self._doc.text
if not cancel:
parent.addElement(container) | python | def end_container(self, cancel=None):
"""Finishes and registers the currently-active container, unless
'cancel' is True."""
if not self._containers:
return
container = self._containers.pop()
if len(self._containers) >= 1:
parent = self._containers[-1]
else:
parent = self._doc.text
if not cancel:
parent.addElement(container) | Finishes and registers the currently-active container, unless
'cancel' is True. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L457-L468 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument.container | def container(self, cls, **kwargs):
"""Container context manager."""
self.start_container(cls, **kwargs)
yield
self.end_container() | python | def container(self, cls, **kwargs):
"""Container context manager."""
self.start_container(cls, **kwargs)
yield
self.end_container() | Container context manager. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L471-L475 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument.start_paragraph | def start_paragraph(self, stylename=None):
"""Start a new paragraph."""
# Use the next paragraph style if one was set.
if stylename is None:
stylename = self._next_p_style or 'normal-paragraph'
self.start_container(P, stylename=stylename) | python | def start_paragraph(self, stylename=None):
"""Start a new paragraph."""
# Use the next paragraph style if one was set.
if stylename is None:
stylename = self._next_p_style or 'normal-paragraph'
self.start_container(P, stylename=stylename) | Start a new paragraph. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L477-L482 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument.require_paragraph | def require_paragraph(self):
"""Create a new paragraph unless the currently-active container
is already a paragraph."""
if self._containers and _is_paragraph(self._containers[-1]):
return False
else:
self.start_paragraph()
return True | python | def require_paragraph(self):
"""Create a new paragraph unless the currently-active container
is already a paragraph."""
if self._containers and _is_paragraph(self._containers[-1]):
return False
else:
self.start_paragraph()
return True | Create a new paragraph unless the currently-active container
is already a paragraph. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L491-L498 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument._code_line | def _code_line(self, line):
"""Add a code line."""
assert self._containers
container = self._containers[-1]
# Handle extra spaces.
text = line
while text:
if text.startswith(' '):
r = re.match(r'(^ +)', text)
n = len(r.group(1))
container.addElement(S(c=n))
text = text[n:]
elif ' ' in text:
assert not text.startswith(' ')
i = text.index(' ')
container.addElement(Span(text=text[:i]))
text = text[i:]
else:
container.addElement(Span(text=text))
text = '' | python | def _code_line(self, line):
"""Add a code line."""
assert self._containers
container = self._containers[-1]
# Handle extra spaces.
text = line
while text:
if text.startswith(' '):
r = re.match(r'(^ +)', text)
n = len(r.group(1))
container.addElement(S(c=n))
text = text[n:]
elif ' ' in text:
assert not text.startswith(' ')
i = text.index(' ')
container.addElement(Span(text=text[:i]))
text = text[i:]
else:
container.addElement(Span(text=text))
text = '' | Add a code line. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L507-L526 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument.code | def code(self, text, lang=None):
"""Add a code block."""
# WARNING: lang is discarded currently.
with self.paragraph(stylename='code'):
lines = text.splitlines()
for line in lines[:-1]:
self._code_line(line)
self.linebreak()
self._code_line(lines[-1]) | python | def code(self, text, lang=None):
"""Add a code block."""
# WARNING: lang is discarded currently.
with self.paragraph(stylename='code'):
lines = text.splitlines()
for line in lines[:-1]:
self._code_line(line)
self.linebreak()
self._code_line(lines[-1]) | Add a code block. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L528-L536 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument.start_numbered_list | def start_numbered_list(self):
"""Start a numbered list."""
self._ordered = True
self.start_container(List, stylename='_numbered_list')
self.set_next_paragraph_style('numbered-list-paragraph'
if self._item_level <= 0
else 'sublist-paragraph') | python | def start_numbered_list(self):
"""Start a numbered list."""
self._ordered = True
self.start_container(List, stylename='_numbered_list')
self.set_next_paragraph_style('numbered-list-paragraph'
if self._item_level <= 0
else 'sublist-paragraph') | Start a numbered list. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L558-L564 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument.start_list | def start_list(self):
"""Start a list."""
self._ordered = False
self.start_container(List)
self.set_next_paragraph_style('list-paragraph'
if self._item_level <= 0
else 'sublist-paragraph') | python | def start_list(self):
"""Start a list."""
self._ordered = False
self.start_container(List)
self.set_next_paragraph_style('list-paragraph'
if self._item_level <= 0
else 'sublist-paragraph') | Start a list. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L572-L578 |
rossant/ipymd | ipymd/lib/opendocument.py | ODFDocument.text | def text(self, text, stylename=None):
"""Add text within the current container."""
assert self._containers
container = self._containers[-1]
if stylename is not None:
stylename = self._get_style_name(stylename)
container.addElement(Span(stylename=stylename, text=text))
else:
container.addElement(Span(text=text)) | python | def text(self, text, stylename=None):
"""Add text within the current container."""
assert self._containers
container = self._containers[-1]
if stylename is not None:
stylename = self._get_style_name(stylename)
container.addElement(Span(stylename=stylename, text=text))
else:
container.addElement(Span(text=text)) | Add text within the current container. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/lib/opendocument.py#L617-L625 |
rossant/ipymd | ipymd/formats/notebook.py | _cell_output | def _cell_output(cell):
"""Return the output of an ipynb cell."""
outputs = cell.get('outputs', [])
# Add stdout.
stdout = ('\n'.join(_ensure_string(output.get('text', ''))
for output in outputs)).rstrip()
# Add text output.
text_outputs = []
for output in outputs:
out = output.get('data', {}).get('text/plain', [])
out = _ensure_string(out)
# HACK: skip <matplotlib ...> outputs.
if out.startswith('<matplotlib'):
continue
text_outputs.append(out)
return stdout + '\n'.join(text_outputs).rstrip() | python | def _cell_output(cell):
"""Return the output of an ipynb cell."""
outputs = cell.get('outputs', [])
# Add stdout.
stdout = ('\n'.join(_ensure_string(output.get('text', ''))
for output in outputs)).rstrip()
# Add text output.
text_outputs = []
for output in outputs:
out = output.get('data', {}).get('text/plain', [])
out = _ensure_string(out)
# HACK: skip <matplotlib ...> outputs.
if out.startswith('<matplotlib'):
continue
text_outputs.append(out)
return stdout + '\n'.join(text_outputs).rstrip() | Return the output of an ipynb cell. | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/notebook.py#L33-L48 |
mk-fg/pretty-yaml | pyaml/__init__.py | dump_add_vspacing | def dump_add_vspacing(buff, vspacing):
'Post-processing to add some nice-ish spacing for deeper map/list levels.'
if isinstance(vspacing, int):
vspacing = ['\n']*(vspacing+1)
buff.seek(0)
result = list()
for line in buff:
level = 0
line = line.decode('utf-8')
result.append(line)
if ':' in line or re.search(r'---(\s*$|\s)', line):
while line.startswith(' '):
level, line = level + 1, line[2:]
if len(vspacing) > level and len(result) != 1:
vspace = vspacing[level]
result.insert( -1, vspace
if not isinstance(vspace, int) else '\n'*vspace )
buff.seek(0), buff.truncate()
buff.write(''.join(result).encode('utf-8')) | python | def dump_add_vspacing(buff, vspacing):
'Post-processing to add some nice-ish spacing for deeper map/list levels.'
if isinstance(vspacing, int):
vspacing = ['\n']*(vspacing+1)
buff.seek(0)
result = list()
for line in buff:
level = 0
line = line.decode('utf-8')
result.append(line)
if ':' in line or re.search(r'---(\s*$|\s)', line):
while line.startswith(' '):
level, line = level + 1, line[2:]
if len(vspacing) > level and len(result) != 1:
vspace = vspacing[level]
result.insert( -1, vspace
if not isinstance(vspace, int) else '\n'*vspace )
buff.seek(0), buff.truncate()
buff.write(''.join(result).encode('utf-8')) | Post-processing to add some nice-ish spacing for deeper map/list levels. | https://github.com/mk-fg/pretty-yaml/blob/a7f087124ad26f032357127614c87050fabb3de6/pyaml/__init__.py#L156-L174 |
happyleavesaoc/python-firetv | firetv/__init__.py | FireTV._dump | def _dump(self, service, grep=None):
"""Perform a service dump.
:param service: Service to dump.
:param grep: Grep for this string.
:returns: Dump, optionally grepped.
"""
if grep:
return self.adb_shell('dumpsys {0} | grep "{1}"'.format(service, grep))
return self.adb_shell('dumpsys {0}'.format(service)) | python | def _dump(self, service, grep=None):
"""Perform a service dump.
:param service: Service to dump.
:param grep: Grep for this string.
:returns: Dump, optionally grepped.
"""
if grep:
return self.adb_shell('dumpsys {0} | grep "{1}"'.format(service, grep))
return self.adb_shell('dumpsys {0}'.format(service)) | Perform a service dump.
:param service: Service to dump.
:param grep: Grep for this string.
:returns: Dump, optionally grepped. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L226-L235 |
happyleavesaoc/python-firetv | firetv/__init__.py | FireTV._dump_has | def _dump_has(self, service, grep, search):
"""Check if a dump has particular content.
:param service: Service to dump.
:param grep: Grep for this string.
:param search: Check for this substring.
:returns: Found or not.
"""
dump_grep = self._dump(service, grep=grep)
if not dump_grep:
return False
return dump_grep.strip().find(search) > -1 | python | def _dump_has(self, service, grep, search):
"""Check if a dump has particular content.
:param service: Service to dump.
:param grep: Grep for this string.
:param search: Check for this substring.
:returns: Found or not.
"""
dump_grep = self._dump(service, grep=grep)
if not dump_grep:
return False
return dump_grep.strip().find(search) > -1 | Check if a dump has particular content.
:param service: Service to dump.
:param grep: Grep for this string.
:param search: Check for this substring.
:returns: Found or not. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L237-L250 |
happyleavesaoc/python-firetv | firetv/__init__.py | FireTV._ps | def _ps(self, search=''):
"""Perform a ps command with optional filtering.
:param search: Check for this substring.
:returns: List of matching fields
"""
if not self.available:
return
result = []
ps = self.adb_streaming_shell('ps')
try:
for bad_line in ps:
# The splitting of the StreamingShell doesn't always work
# this is to ensure that we get only one line
for line in bad_line.splitlines():
if search in line:
result.append(line.strip().rsplit(' ', 1)[-1])
return result
except InvalidChecksumError as e:
print(e)
self.connect()
raise IOError | python | def _ps(self, search=''):
"""Perform a ps command with optional filtering.
:param search: Check for this substring.
:returns: List of matching fields
"""
if not self.available:
return
result = []
ps = self.adb_streaming_shell('ps')
try:
for bad_line in ps:
# The splitting of the StreamingShell doesn't always work
# this is to ensure that we get only one line
for line in bad_line.splitlines():
if search in line:
result.append(line.strip().rsplit(' ', 1)[-1])
return result
except InvalidChecksumError as e:
print(e)
self.connect()
raise IOError | Perform a ps command with optional filtering.
:param search: Check for this substring.
:returns: List of matching fields | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L259-L280 |
happyleavesaoc/python-firetv | firetv/__init__.py | FireTV.connect | def connect(self, always_log_errors=True):
"""Connect to an Amazon Fire TV device.
Will attempt to establish ADB connection to the given host.
Failure sets state to UNKNOWN and disables sending actions.
:returns: True if successful, False otherwise
"""
self._adb_lock.acquire(**LOCK_KWARGS)
try:
if not self.adb_server_ip:
# python-adb
try:
if self.adbkey:
signer = Signer(self.adbkey)
# Connect to the device
self._adb = adb_commands.AdbCommands().ConnectDevice(serial=self.host, rsa_keys=[signer], default_timeout_ms=9000)
else:
self._adb = adb_commands.AdbCommands().ConnectDevice(serial=self.host, default_timeout_ms=9000)
# ADB connection successfully established
self._available = True
except socket_error as serr:
if self._available or always_log_errors:
if serr.strerror is None:
serr.strerror = "Timed out trying to connect to ADB device."
logging.warning("Couldn't connect to host: %s, error: %s", self.host, serr.strerror)
# ADB connection attempt failed
self._adb = None
self._available = False
finally:
return self._available
else:
# pure-python-adb
try:
self._adb_client = AdbClient(host=self.adb_server_ip, port=self.adb_server_port)
self._adb_device = self._adb_client.device(self.host)
self._available = bool(self._adb_device)
except:
self._available = False
finally:
return self._available
finally:
self._adb_lock.release() | python | def connect(self, always_log_errors=True):
"""Connect to an Amazon Fire TV device.
Will attempt to establish ADB connection to the given host.
Failure sets state to UNKNOWN and disables sending actions.
:returns: True if successful, False otherwise
"""
self._adb_lock.acquire(**LOCK_KWARGS)
try:
if not self.adb_server_ip:
# python-adb
try:
if self.adbkey:
signer = Signer(self.adbkey)
# Connect to the device
self._adb = adb_commands.AdbCommands().ConnectDevice(serial=self.host, rsa_keys=[signer], default_timeout_ms=9000)
else:
self._adb = adb_commands.AdbCommands().ConnectDevice(serial=self.host, default_timeout_ms=9000)
# ADB connection successfully established
self._available = True
except socket_error as serr:
if self._available or always_log_errors:
if serr.strerror is None:
serr.strerror = "Timed out trying to connect to ADB device."
logging.warning("Couldn't connect to host: %s, error: %s", self.host, serr.strerror)
# ADB connection attempt failed
self._adb = None
self._available = False
finally:
return self._available
else:
# pure-python-adb
try:
self._adb_client = AdbClient(host=self.adb_server_ip, port=self.adb_server_port)
self._adb_device = self._adb_client.device(self.host)
self._available = bool(self._adb_device)
except:
self._available = False
finally:
return self._available
finally:
self._adb_lock.release() | Connect to an Amazon Fire TV device.
Will attempt to establish ADB connection to the given host.
Failure sets state to UNKNOWN and disables sending actions.
:returns: True if successful, False otherwise | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L299-L350 |
happyleavesaoc/python-firetv | firetv/__init__.py | FireTV.update | def update(self, get_running_apps=True):
"""Get the state of the device, the current app, and the running apps.
:param get_running_apps: whether or not to get the ``running_apps`` property
:return state: the state of the device
:return current_app: the current app
:return running_apps: the running apps
"""
# The `screen_on`, `awake`, `wake_lock_size`, `current_app`, and `running_apps` properties.
screen_on, awake, wake_lock_size, _current_app, running_apps = self.get_properties(get_running_apps=get_running_apps, lazy=True)
# Check if device is off.
if not screen_on:
state = STATE_OFF
current_app = None
running_apps = None
# Check if screen saver is on.
elif not awake:
state = STATE_IDLE
current_app = None
running_apps = None
else:
# Get the current app.
if isinstance(_current_app, dict) and 'package' in _current_app:
current_app = _current_app['package']
else:
current_app = None
# Get the running apps.
if running_apps is None and current_app:
running_apps = [current_app]
# Get the state.
# TODO: determine the state differently based on the `current_app`.
if current_app in [PACKAGE_LAUNCHER, PACKAGE_SETTINGS]:
state = STATE_STANDBY
# Amazon Video
elif current_app == AMAZON_VIDEO:
if wake_lock_size == 5:
state = STATE_PLAYING
else:
# wake_lock_size == 2
state = STATE_PAUSED
# Netflix
elif current_app == NETFLIX:
if wake_lock_size > 3:
state = STATE_PLAYING
else:
state = STATE_PAUSED
# Check if `wake_lock_size` is 1 (device is playing).
elif wake_lock_size == 1:
state = STATE_PLAYING
# Otherwise, device is paused.
else:
state = STATE_PAUSED
return state, current_app, running_apps | python | def update(self, get_running_apps=True):
"""Get the state of the device, the current app, and the running apps.
:param get_running_apps: whether or not to get the ``running_apps`` property
:return state: the state of the device
:return current_app: the current app
:return running_apps: the running apps
"""
# The `screen_on`, `awake`, `wake_lock_size`, `current_app`, and `running_apps` properties.
screen_on, awake, wake_lock_size, _current_app, running_apps = self.get_properties(get_running_apps=get_running_apps, lazy=True)
# Check if device is off.
if not screen_on:
state = STATE_OFF
current_app = None
running_apps = None
# Check if screen saver is on.
elif not awake:
state = STATE_IDLE
current_app = None
running_apps = None
else:
# Get the current app.
if isinstance(_current_app, dict) and 'package' in _current_app:
current_app = _current_app['package']
else:
current_app = None
# Get the running apps.
if running_apps is None and current_app:
running_apps = [current_app]
# Get the state.
# TODO: determine the state differently based on the `current_app`.
if current_app in [PACKAGE_LAUNCHER, PACKAGE_SETTINGS]:
state = STATE_STANDBY
# Amazon Video
elif current_app == AMAZON_VIDEO:
if wake_lock_size == 5:
state = STATE_PLAYING
else:
# wake_lock_size == 2
state = STATE_PAUSED
# Netflix
elif current_app == NETFLIX:
if wake_lock_size > 3:
state = STATE_PLAYING
else:
state = STATE_PAUSED
# Check if `wake_lock_size` is 1 (device is playing).
elif wake_lock_size == 1:
state = STATE_PLAYING
# Otherwise, device is paused.
else:
state = STATE_PAUSED
return state, current_app, running_apps | Get the state of the device, the current app, and the running apps.
:param get_running_apps: whether or not to get the ``running_apps`` property
:return state: the state of the device
:return current_app: the current app
:return running_apps: the running apps | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L357-L419 |
happyleavesaoc/python-firetv | firetv/__init__.py | FireTV.app_state | def app_state(self, app):
"""Informs if application is running."""
if not self.available or not self.screen_on:
return STATE_OFF
if self.current_app["package"] == app:
return STATE_ON
return STATE_OFF | python | def app_state(self, app):
"""Informs if application is running."""
if not self.available or not self.screen_on:
return STATE_OFF
if self.current_app["package"] == app:
return STATE_ON
return STATE_OFF | Informs if application is running. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L426-L432 |
happyleavesaoc/python-firetv | firetv/__init__.py | FireTV.state | def state(self):
"""Compute and return the device state.
:returns: Device state.
"""
# Check if device is disconnected.
if not self.available:
return STATE_UNKNOWN
# Check if device is off.
if not self.screen_on:
return STATE_OFF
# Check if screen saver is on.
if not self.awake:
return STATE_IDLE
# Check if the launcher is active.
if self.launcher or self.settings:
return STATE_STANDBY
# Check for a wake lock (device is playing).
if self.wake_lock:
return STATE_PLAYING
# Otherwise, device is paused.
return STATE_PAUSED | python | def state(self):
"""Compute and return the device state.
:returns: Device state.
"""
# Check if device is disconnected.
if not self.available:
return STATE_UNKNOWN
# Check if device is off.
if not self.screen_on:
return STATE_OFF
# Check if screen saver is on.
if not self.awake:
return STATE_IDLE
# Check if the launcher is active.
if self.launcher or self.settings:
return STATE_STANDBY
# Check for a wake lock (device is playing).
if self.wake_lock:
return STATE_PLAYING
# Otherwise, device is paused.
return STATE_PAUSED | Compute and return the device state.
:returns: Device state. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L448-L469 |
happyleavesaoc/python-firetv | firetv/__init__.py | FireTV.available | def available(self):
"""Check whether the ADB connection is intact."""
if not self.adb_server_ip:
# python-adb
return bool(self._adb)
# pure-python-adb
try:
# make sure the server is available
adb_devices = self._adb_client.devices()
# make sure the device is available
try:
# case 1: the device is currently available
if any([self.host in dev.get_serial_no() for dev in adb_devices]):
if not self._available:
self._available = True
return True
# case 2: the device is not currently available
if self._available:
logging.error('ADB server is not connected to the device.')
self._available = False
return False
except RuntimeError:
if self._available:
logging.error('ADB device is unavailable; encountered an error when searching for device.')
self._available = False
return False
except RuntimeError:
if self._available:
logging.error('ADB server is unavailable.')
self._available = False
return False | python | def available(self):
"""Check whether the ADB connection is intact."""
if not self.adb_server_ip:
# python-adb
return bool(self._adb)
# pure-python-adb
try:
# make sure the server is available
adb_devices = self._adb_client.devices()
# make sure the device is available
try:
# case 1: the device is currently available
if any([self.host in dev.get_serial_no() for dev in adb_devices]):
if not self._available:
self._available = True
return True
# case 2: the device is not currently available
if self._available:
logging.error('ADB server is not connected to the device.')
self._available = False
return False
except RuntimeError:
if self._available:
logging.error('ADB device is unavailable; encountered an error when searching for device.')
self._available = False
return False
except RuntimeError:
if self._available:
logging.error('ADB server is unavailable.')
self._available = False
return False | Check whether the ADB connection is intact. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L472-L507 |
happyleavesaoc/python-firetv | firetv/__init__.py | FireTV.running_apps | def running_apps(self):
"""Return a list of running user applications."""
ps = self.adb_shell(RUNNING_APPS_CMD)
if ps:
return [line.strip().rsplit(' ', 1)[-1] for line in ps.splitlines() if line.strip()]
return [] | python | def running_apps(self):
"""Return a list of running user applications."""
ps = self.adb_shell(RUNNING_APPS_CMD)
if ps:
return [line.strip().rsplit(' ', 1)[-1] for line in ps.splitlines() if line.strip()]
return [] | Return a list of running user applications. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L510-L515 |
happyleavesaoc/python-firetv | firetv/__init__.py | FireTV.current_app | def current_app(self):
"""Return the current app."""
current_focus = self.adb_shell(CURRENT_APP_CMD)
if current_focus is None:
return None
current_focus = current_focus.replace("\r", "")
matches = WINDOW_REGEX.search(current_focus)
# case 1: current app was successfully found
if matches:
(pkg, activity) = matches.group("package", "activity")
return {"package": pkg, "activity": activity}
# case 2: current app could not be found
logging.warning("Couldn't get current app, reply was %s", current_focus)
return None | python | def current_app(self):
"""Return the current app."""
current_focus = self.adb_shell(CURRENT_APP_CMD)
if current_focus is None:
return None
current_focus = current_focus.replace("\r", "")
matches = WINDOW_REGEX.search(current_focus)
# case 1: current app was successfully found
if matches:
(pkg, activity) = matches.group("package", "activity")
return {"package": pkg, "activity": activity}
# case 2: current app could not be found
logging.warning("Couldn't get current app, reply was %s", current_focus)
return None | Return the current app. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L518-L534 |
happyleavesaoc/python-firetv | firetv/__init__.py | FireTV.wake_lock_size | def wake_lock_size(self):
"""Get the size of the current wake lock."""
output = self.adb_shell(WAKE_LOCK_SIZE_CMD)
if not output:
return None
return int(output.split("=")[1].strip()) | python | def wake_lock_size(self):
"""Get the size of the current wake lock."""
output = self.adb_shell(WAKE_LOCK_SIZE_CMD)
if not output:
return None
return int(output.split("=")[1].strip()) | Get the size of the current wake lock. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L552-L557 |
happyleavesaoc/python-firetv | firetv/__init__.py | FireTV.get_properties | def get_properties(self, get_running_apps=True, lazy=False):
"""Get the ``screen_on``, ``awake``, ``wake_lock_size``, ``current_app``, and ``running_apps`` properties."""
if get_running_apps:
output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
WAKE_LOCK_SIZE_CMD + " && " +
CURRENT_APP_CMD + " && " +
RUNNING_APPS_CMD)
else:
output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
WAKE_LOCK_SIZE_CMD + " && " +
CURRENT_APP_CMD)
# ADB command was unsuccessful
if output is None:
return None, None, None, None, None
# `screen_on` property
if not output:
return False, False, -1, None, None
screen_on = output[0] == '1'
# `awake` property
if len(output) < 2:
return screen_on, False, -1, None, None
awake = output[1] == '1'
lines = output.strip().splitlines()
# `wake_lock_size` property
if len(lines[0]) < 3:
return screen_on, awake, -1, None, None
wake_lock_size = int(lines[0].split("=")[1].strip())
# `current_app` property
if len(lines) < 2:
return screen_on, awake, wake_lock_size, None, None
matches = WINDOW_REGEX.search(lines[1])
if matches:
# case 1: current app was successfully found
(pkg, activity) = matches.group("package", "activity")
current_app = {"package": pkg, "activity": activity}
else:
# case 2: current app could not be found
current_app = None
# `running_apps` property
if not get_running_apps or len(lines) < 3:
return screen_on, awake, wake_lock_size, current_app, None
running_apps = [line.strip().rsplit(' ', 1)[-1] for line in lines[2:] if line.strip()]
return screen_on, awake, wake_lock_size, current_app, running_apps | python | def get_properties(self, get_running_apps=True, lazy=False):
"""Get the ``screen_on``, ``awake``, ``wake_lock_size``, ``current_app``, and ``running_apps`` properties."""
if get_running_apps:
output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
WAKE_LOCK_SIZE_CMD + " && " +
CURRENT_APP_CMD + " && " +
RUNNING_APPS_CMD)
else:
output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
WAKE_LOCK_SIZE_CMD + " && " +
CURRENT_APP_CMD)
# ADB command was unsuccessful
if output is None:
return None, None, None, None, None
# `screen_on` property
if not output:
return False, False, -1, None, None
screen_on = output[0] == '1'
# `awake` property
if len(output) < 2:
return screen_on, False, -1, None, None
awake = output[1] == '1'
lines = output.strip().splitlines()
# `wake_lock_size` property
if len(lines[0]) < 3:
return screen_on, awake, -1, None, None
wake_lock_size = int(lines[0].split("=")[1].strip())
# `current_app` property
if len(lines) < 2:
return screen_on, awake, wake_lock_size, None, None
matches = WINDOW_REGEX.search(lines[1])
if matches:
# case 1: current app was successfully found
(pkg, activity) = matches.group("package", "activity")
current_app = {"package": pkg, "activity": activity}
else:
# case 2: current app could not be found
current_app = None
# `running_apps` property
if not get_running_apps or len(lines) < 3:
return screen_on, awake, wake_lock_size, current_app, None
running_apps = [line.strip().rsplit(' ', 1)[-1] for line in lines[2:] if line.strip()]
return screen_on, awake, wake_lock_size, current_app, running_apps | Get the ``screen_on``, ``awake``, ``wake_lock_size``, ``current_app``, and ``running_apps`` properties. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__init__.py#L569-L623 |
happyleavesaoc/python-firetv | firetv/__main__.py | is_valid_device_id | def is_valid_device_id(device_id):
""" Check if device identifier is valid.
A valid device identifier contains only ascii word characters or dashes.
:param device_id: Device identifier
:returns: Valid or not.
"""
valid = valid_device_id.match(device_id)
if not valid:
logging.error("A valid device identifier contains "
"only ascii word characters or dashes. "
"Device '%s' not added.", device_id)
return valid | python | def is_valid_device_id(device_id):
""" Check if device identifier is valid.
A valid device identifier contains only ascii word characters or dashes.
:param device_id: Device identifier
:returns: Valid or not.
"""
valid = valid_device_id.match(device_id)
if not valid:
logging.error("A valid device identifier contains "
"only ascii word characters or dashes. "
"Device '%s' not added.", device_id)
return valid | Check if device identifier is valid.
A valid device identifier contains only ascii word characters or dashes.
:param device_id: Device identifier
:returns: Valid or not. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L50-L63 |
happyleavesaoc/python-firetv | firetv/__main__.py | add | def add(device_id, host, adbkey='', adb_server_ip='', adb_server_port=5037):
""" Add a device.
Creates FireTV instance associated with device identifier.
:param device_id: Device identifier.
:param host: Host in <address>:<port> format.
:param adbkey: The path to the "adbkey" file
:param adb_server_ip: the IP address for the ADB server
:param adb_server_port: the port for the ADB server
:returns: Added successfully or not.
"""
valid = is_valid_device_id(device_id) and is_valid_host(host)
if valid:
devices[device_id] = FireTV(str(host), str(adbkey), str(adb_server_ip), str(adb_server_port))
return valid | python | def add(device_id, host, adbkey='', adb_server_ip='', adb_server_port=5037):
""" Add a device.
Creates FireTV instance associated with device identifier.
:param device_id: Device identifier.
:param host: Host in <address>:<port> format.
:param adbkey: The path to the "adbkey" file
:param adb_server_ip: the IP address for the ADB server
:param adb_server_port: the port for the ADB server
:returns: Added successfully or not.
"""
valid = is_valid_device_id(device_id) and is_valid_host(host)
if valid:
devices[device_id] = FireTV(str(host), str(adbkey), str(adb_server_ip), str(adb_server_port))
return valid | Add a device.
Creates FireTV instance associated with device identifier.
:param device_id: Device identifier.
:param host: Host in <address>:<port> format.
:param adbkey: The path to the "adbkey" file
:param adb_server_ip: the IP address for the ADB server
:param adb_server_port: the port for the ADB server
:returns: Added successfully or not. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L78-L93 |
happyleavesaoc/python-firetv | firetv/__main__.py | add_device | def add_device():
""" Add a device via HTTP POST.
POST JSON in the following format ::
{
"device_id": "<your_device_id>",
"host": "<address>:<port>",
"adbkey": "<path to the adbkey file>"
}
"""
req = request.get_json()
success = False
if 'device_id' in req and 'host' in req:
success = add(req['device_id'], req['host'], req.get('adbkey', ''), req.get('adb_server_ip', ''), req.get('adb_server_port', 5037))
return jsonify(success=success) | python | def add_device():
""" Add a device via HTTP POST.
POST JSON in the following format ::
{
"device_id": "<your_device_id>",
"host": "<address>:<port>",
"adbkey": "<path to the adbkey file>"
}
"""
req = request.get_json()
success = False
if 'device_id' in req and 'host' in req:
success = add(req['device_id'], req['host'], req.get('adbkey', ''), req.get('adb_server_ip', ''), req.get('adb_server_port', 5037))
return jsonify(success=success) | Add a device via HTTP POST.
POST JSON in the following format ::
{
"device_id": "<your_device_id>",
"host": "<address>:<port>",
"adbkey": "<path to the adbkey file>"
} | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L97-L113 |
happyleavesaoc/python-firetv | firetv/__main__.py | list_devices | def list_devices():
""" List devices via HTTP GET. """
output = {}
for device_id, device in devices.items():
output[device_id] = {
'host': device.host,
'state': device.state
}
return jsonify(devices=output) | python | def list_devices():
""" List devices via HTTP GET. """
output = {}
for device_id, device in devices.items():
output[device_id] = {
'host': device.host,
'state': device.state
}
return jsonify(devices=output) | List devices via HTTP GET. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L117-L125 |
happyleavesaoc/python-firetv | firetv/__main__.py | device_state | def device_state(device_id):
""" Get device state via HTTP GET. """
if device_id not in devices:
return jsonify(success=False)
return jsonify(state=devices[device_id].state) | python | def device_state(device_id):
""" Get device state via HTTP GET. """
if device_id not in devices:
return jsonify(success=False)
return jsonify(state=devices[device_id].state) | Get device state via HTTP GET. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L129-L133 |
happyleavesaoc/python-firetv | firetv/__main__.py | current_app | def current_app(device_id):
""" Get currently running app. """
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
current = devices[device_id].current_app
if current is None:
abort(404)
return jsonify(current_app=current) | python | def current_app(device_id):
""" Get currently running app. """
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
current = devices[device_id].current_app
if current is None:
abort(404)
return jsonify(current_app=current) | Get currently running app. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L137-L148 |
happyleavesaoc/python-firetv | firetv/__main__.py | running_apps | def running_apps(device_id):
""" Get running apps via HTTP GET. """
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
return jsonify(running_apps=devices[device_id].running_apps) | python | def running_apps(device_id):
""" Get running apps via HTTP GET. """
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
return jsonify(running_apps=devices[device_id].running_apps) | Get running apps via HTTP GET. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L152-L158 |
happyleavesaoc/python-firetv | firetv/__main__.py | get_app_state | def get_app_state(device_id, app_id):
""" Get the state of the requested app """
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
app_state = devices[device_id].app_state(app_id)
return jsonify(state=app_state, status=app_state) | python | def get_app_state(device_id, app_id):
""" Get the state of the requested app """
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
app_state = devices[device_id].app_state(app_id)
return jsonify(state=app_state, status=app_state) | Get the state of the requested app | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L162-L171 |
happyleavesaoc/python-firetv | firetv/__main__.py | device_action | def device_action(device_id, action_id):
""" Initiate device action via HTTP GET. """
success = False
if device_id in devices:
input_cmd = getattr(devices[device_id], action_id, None)
if callable(input_cmd):
input_cmd()
success = True
return jsonify(success=success) | python | def device_action(device_id, action_id):
""" Initiate device action via HTTP GET. """
success = False
if device_id in devices:
input_cmd = getattr(devices[device_id], action_id, None)
if callable(input_cmd):
input_cmd()
success = True
return jsonify(success=success) | Initiate device action via HTTP GET. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L180-L188 |
happyleavesaoc/python-firetv | firetv/__main__.py | app_start | def app_start(device_id, app_id):
""" Starts an app with corresponding package name"""
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
success = devices[device_id].launch_app(app_id)
return jsonify(success=success) | python | def app_start(device_id, app_id):
""" Starts an app with corresponding package name"""
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
success = devices[device_id].launch_app(app_id)
return jsonify(success=success) | Starts an app with corresponding package name | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L192-L202 |
happyleavesaoc/python-firetv | firetv/__main__.py | app_stop | def app_stop(device_id, app_id):
""" stops an app with corresponding package name"""
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
success = devices[device_id].stop_app(app_id)
return jsonify(success=success) | python | def app_stop(device_id, app_id):
""" stops an app with corresponding package name"""
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
success = devices[device_id].stop_app(app_id)
return jsonify(success=success) | stops an app with corresponding package name | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L206-L216 |
happyleavesaoc/python-firetv | firetv/__main__.py | device_connect | def device_connect(device_id):
""" Force a connection attempt via HTTP GET. """
success = False
if device_id in devices:
devices[device_id].connect()
success = True
return jsonify(success=success) | python | def device_connect(device_id):
""" Force a connection attempt via HTTP GET. """
success = False
if device_id in devices:
devices[device_id].connect()
success = True
return jsonify(success=success) | Force a connection attempt via HTTP GET. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L220-L226 |
happyleavesaoc/python-firetv | firetv/__main__.py | _parse_config | def _parse_config(config_file_path):
""" Parse Config File from yaml file. """
config_file = open(config_file_path, 'r')
config = yaml.load(config_file)
config_file.close()
return config | python | def _parse_config(config_file_path):
""" Parse Config File from yaml file. """
config_file = open(config_file_path, 'r')
config = yaml.load(config_file)
config_file.close()
return config | Parse Config File from yaml file. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L229-L234 |
happyleavesaoc/python-firetv | firetv/__main__.py | _add_devices_from_config | def _add_devices_from_config(args):
""" Add devices from config. """
config = _parse_config(args.config)
for device in config['devices']:
if args.default:
if device == "default":
raise ValueError('devicename "default" in config is not allowed if default param is set')
if config['devices'][device]['host'] == args.default:
raise ValueError('host set in default param must not be defined in config')
add(device, config['devices'][device]['host'], config['devices'][device].get('adbkey', ''),
config['devices'][device].get('adb_server_ip', ''), config['devices'][device].get('adb_server_port', 5037)) | python | def _add_devices_from_config(args):
""" Add devices from config. """
config = _parse_config(args.config)
for device in config['devices']:
if args.default:
if device == "default":
raise ValueError('devicename "default" in config is not allowed if default param is set')
if config['devices'][device]['host'] == args.default:
raise ValueError('host set in default param must not be defined in config')
add(device, config['devices'][device]['host'], config['devices'][device].get('adbkey', ''),
config['devices'][device].get('adb_server_ip', ''), config['devices'][device].get('adb_server_port', 5037)) | Add devices from config. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L237-L247 |
happyleavesaoc/python-firetv | firetv/__main__.py | main | def main():
""" Set up the server. """
parser = argparse.ArgumentParser(description='AFTV Server')
parser.add_argument('-p', '--port', type=int, help='listen port', default=5556)
parser.add_argument('-d', '--default', help='default Amazon Fire TV host', nargs='?')
parser.add_argument('-c', '--config', type=str, help='Path to config file')
args = parser.parse_args()
if args.config:
_add_devices_from_config(args)
if args.default and not add('default', args.default):
exit('invalid hostname')
app.run(host='0.0.0.0', port=args.port) | python | def main():
""" Set up the server. """
parser = argparse.ArgumentParser(description='AFTV Server')
parser.add_argument('-p', '--port', type=int, help='listen port', default=5556)
parser.add_argument('-d', '--default', help='default Amazon Fire TV host', nargs='?')
parser.add_argument('-c', '--config', type=str, help='Path to config file')
args = parser.parse_args()
if args.config:
_add_devices_from_config(args)
if args.default and not add('default', args.default):
exit('invalid hostname')
app.run(host='0.0.0.0', port=args.port) | Set up the server. | https://github.com/happyleavesaoc/python-firetv/blob/3dd953376c0d5af502e775ae14ed0afe03224781/firetv/__main__.py#L250-L263 |
areebbeigh/profanityfilter | profanityfilter/profanityfilter.py | ProfanityFilter._load_words | def _load_words(self):
"""Loads the list of profane words from file."""
with open(self._words_file, 'r') as f:
self._censor_list = [line.strip() for line in f.readlines()] | python | def _load_words(self):
"""Loads the list of profane words from file."""
with open(self._words_file, 'r') as f:
self._censor_list = [line.strip() for line in f.readlines()] | Loads the list of profane words from file. | https://github.com/areebbeigh/profanityfilter/blob/f7e1c1bb1b7aea401e0d09219610cc690acd5476/profanityfilter/profanityfilter.py#L43-L46 |
areebbeigh/profanityfilter | profanityfilter/profanityfilter.py | ProfanityFilter.set_censor | def set_censor(self, character):
"""Replaces the original censor character '*' with ``character``."""
# TODO: what if character isn't str()-able?
if isinstance(character, int):
character = str(character)
self._censor_char = character | python | def set_censor(self, character):
"""Replaces the original censor character '*' with ``character``."""
# TODO: what if character isn't str()-able?
if isinstance(character, int):
character = str(character)
self._censor_char = character | Replaces the original censor character '*' with ``character``. | https://github.com/areebbeigh/profanityfilter/blob/f7e1c1bb1b7aea401e0d09219610cc690acd5476/profanityfilter/profanityfilter.py#L60-L65 |
areebbeigh/profanityfilter | profanityfilter/profanityfilter.py | ProfanityFilter.get_profane_words | def get_profane_words(self):
"""Returns all profane words currently in use."""
profane_words = []
if self._custom_censor_list:
profane_words = [w for w in self._custom_censor_list] # Previous versions of Python don't have list.copy()
else:
profane_words = [w for w in self._censor_list]
profane_words.extend(self._extra_censor_list)
profane_words.extend([inflection.pluralize(word) for word in profane_words])
profane_words = list(set(profane_words))
# We sort the list based on decreasing word length so that words like
# 'fu' aren't substituted before 'fuck' if no_word_boundaries = true
profane_words.sort(key=len)
profane_words.reverse()
return profane_words | python | def get_profane_words(self):
"""Returns all profane words currently in use."""
profane_words = []
if self._custom_censor_list:
profane_words = [w for w in self._custom_censor_list] # Previous versions of Python don't have list.copy()
else:
profane_words = [w for w in self._censor_list]
profane_words.extend(self._extra_censor_list)
profane_words.extend([inflection.pluralize(word) for word in profane_words])
profane_words = list(set(profane_words))
# We sort the list based on decreasing word length so that words like
# 'fu' aren't substituted before 'fuck' if no_word_boundaries = true
profane_words.sort(key=len)
profane_words.reverse()
return profane_words | Returns all profane words currently in use. | https://github.com/areebbeigh/profanityfilter/blob/f7e1c1bb1b7aea401e0d09219610cc690acd5476/profanityfilter/profanityfilter.py#L79-L97 |
areebbeigh/profanityfilter | profanityfilter/profanityfilter.py | ProfanityFilter.censor | def censor(self, input_text):
"""Returns input_text with any profane words censored."""
bad_words = self.get_profane_words()
res = input_text
for word in bad_words:
# Apply word boundaries to the bad word
regex_string = r'{0}' if self._no_word_boundaries else r'\b{0}\b'
regex_string = regex_string.format(word)
regex = re.compile(regex_string, re.IGNORECASE)
res = regex.sub(self._censor_char * len(word), res)
return res | python | def censor(self, input_text):
"""Returns input_text with any profane words censored."""
bad_words = self.get_profane_words()
res = input_text
for word in bad_words:
# Apply word boundaries to the bad word
regex_string = r'{0}' if self._no_word_boundaries else r'\b{0}\b'
regex_string = regex_string.format(word)
regex = re.compile(regex_string, re.IGNORECASE)
res = regex.sub(self._censor_char * len(word), res)
return res | Returns input_text with any profane words censored. | https://github.com/areebbeigh/profanityfilter/blob/f7e1c1bb1b7aea401e0d09219610cc690acd5476/profanityfilter/profanityfilter.py#L105-L117 |
jborean93/smbprotocol | smbprotocol/ioctl.py | SMB2NetworkInterfaceInfo.unpack_multiple | def unpack_multiple(data):
"""
Get's a list of SMB2NetworkInterfaceInfo messages from the byte value
passed in. This is the raw buffer value that is set on the
SMB2IOCTLResponse message.
:param data: bytes of the messages
:return: List of SMB2NetworkInterfaceInfo messages
"""
chunks = []
while data:
info = SMB2NetworkInterfaceInfo()
data = info.unpack(data)
chunks.append(info)
return chunks | python | def unpack_multiple(data):
"""
Get's a list of SMB2NetworkInterfaceInfo messages from the byte value
passed in. This is the raw buffer value that is set on the
SMB2IOCTLResponse message.
:param data: bytes of the messages
:return: List of SMB2NetworkInterfaceInfo messages
"""
chunks = []
while data:
info = SMB2NetworkInterfaceInfo()
data = info.unpack(data)
chunks.append(info)
return chunks | Get's a list of SMB2NetworkInterfaceInfo messages from the byte value
passed in. This is the raw buffer value that is set on the
SMB2IOCTLResponse message.
:param data: bytes of the messages
:return: List of SMB2NetworkInterfaceInfo messages | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/ioctl.py#L419-L434 |
jborean93/smbprotocol | smbprotocol/create_contexts.py | CreateContextName.get_response_structure | def get_response_structure(name):
"""
Returns the response structure for a know list of create context
responses.
:param name: The constant value above
:return: The response structure or None if unknown
"""
return {
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST:
SMB2CreateDurableHandleResponse(),
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT:
SMB2CreateDurableHandleReconnect(),
CreateContextName.SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST:
SMB2CreateQueryMaximalAccessResponse(),
CreateContextName.SMB2_CREATE_REQUEST_LEASE:
SMB2CreateResponseLease(),
CreateContextName.SMB2_CREATE_QUERY_ON_DISK_ID:
SMB2CreateQueryOnDiskIDResponse(),
CreateContextName.SMB2_CREATE_REQUEST_LEASE_V2:
SMB2CreateResponseLeaseV2(),
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2:
SMB2CreateDurableHandleResponseV2(),
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2:
SMB2CreateDurableHandleReconnectV2,
CreateContextName.SMB2_CREATE_APP_INSTANCE_ID:
SMB2CreateAppInstanceId(),
CreateContextName.SMB2_CREATE_APP_INSTANCE_VERSION:
SMB2CreateAppInstanceVersion()
}.get(name, None) | python | def get_response_structure(name):
"""
Returns the response structure for a know list of create context
responses.
:param name: The constant value above
:return: The response structure or None if unknown
"""
return {
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST:
SMB2CreateDurableHandleResponse(),
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT:
SMB2CreateDurableHandleReconnect(),
CreateContextName.SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST:
SMB2CreateQueryMaximalAccessResponse(),
CreateContextName.SMB2_CREATE_REQUEST_LEASE:
SMB2CreateResponseLease(),
CreateContextName.SMB2_CREATE_QUERY_ON_DISK_ID:
SMB2CreateQueryOnDiskIDResponse(),
CreateContextName.SMB2_CREATE_REQUEST_LEASE_V2:
SMB2CreateResponseLeaseV2(),
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2:
SMB2CreateDurableHandleResponseV2(),
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2:
SMB2CreateDurableHandleReconnectV2,
CreateContextName.SMB2_CREATE_APP_INSTANCE_ID:
SMB2CreateAppInstanceId(),
CreateContextName.SMB2_CREATE_APP_INSTANCE_VERSION:
SMB2CreateAppInstanceVersion()
}.get(name, None) | Returns the response structure for a know list of create context
responses.
:param name: The constant value above
:return: The response structure or None if unknown | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/create_contexts.py#L41-L71 |
jborean93/smbprotocol | smbprotocol/create_contexts.py | SMB2CreateContextRequest.get_context_data | def get_context_data(self):
"""
Get the buffer_data value of a context response and try to convert it
to the relevant structure based on the buffer_name used. If it is an
unknown structure then the raw bytes are returned.
:return: relevant Structure of buffer_data or bytes if unknown name
"""
buffer_name = self['buffer_name'].get_value()
structure = CreateContextName.get_response_structure(buffer_name)
if structure:
structure.unpack(self['buffer_data'].get_value())
return structure
else:
# unknown structure, just return the raw bytes
return self['buffer_data'].get_value() | python | def get_context_data(self):
"""
Get the buffer_data value of a context response and try to convert it
to the relevant structure based on the buffer_name used. If it is an
unknown structure then the raw bytes are returned.
:return: relevant Structure of buffer_data or bytes if unknown name
"""
buffer_name = self['buffer_name'].get_value()
structure = CreateContextName.get_response_structure(buffer_name)
if structure:
structure.unpack(self['buffer_data'].get_value())
return structure
else:
# unknown structure, just return the raw bytes
return self['buffer_data'].get_value() | Get the buffer_data value of a context response and try to convert it
to the relevant structure based on the buffer_name used. If it is an
unknown structure then the raw bytes are returned.
:return: relevant Structure of buffer_data or bytes if unknown name | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/create_contexts.py#L210-L225 |
jborean93/smbprotocol | smbprotocol/create_contexts.py | SMB2CreateEABuffer.pack_multiple | def pack_multiple(messages):
"""
Converts a list of SMB2CreateEABuffer structures and packs them as a
bytes object used when setting to the SMB2CreateContextRequest
buffer_data field. This should be used as it would calculate the
correct next_entry_offset field value for each buffer entry.
:param messages: List of SMB2CreateEABuffer structures
:return: bytes object that is set on the SMB2CreateContextRequest
buffer_data field.
"""
data = b""
msg_count = len(messages)
for i, msg in enumerate(messages):
if i == msg_count - 1:
msg['next_entry_offset'] = 0
else:
# because the end padding val won't be populated if the entry
# offset is 0, we set to 1 so the len calc is correct
msg['next_entry_offset'] = 1
msg['next_entry_offset'] = len(msg)
data += msg.pack()
return data | python | def pack_multiple(messages):
"""
Converts a list of SMB2CreateEABuffer structures and packs them as a
bytes object used when setting to the SMB2CreateContextRequest
buffer_data field. This should be used as it would calculate the
correct next_entry_offset field value for each buffer entry.
:param messages: List of SMB2CreateEABuffer structures
:return: bytes object that is set on the SMB2CreateContextRequest
buffer_data field.
"""
data = b""
msg_count = len(messages)
for i, msg in enumerate(messages):
if i == msg_count - 1:
msg['next_entry_offset'] = 0
else:
# because the end padding val won't be populated if the entry
# offset is 0, we set to 1 so the len calc is correct
msg['next_entry_offset'] = 1
msg['next_entry_offset'] = len(msg)
data += msg.pack()
return data | Converts a list of SMB2CreateEABuffer structures and packs them as a
bytes object used when setting to the SMB2CreateContextRequest
buffer_data field. This should be used as it would calculate the
correct next_entry_offset field value for each buffer entry.
:param messages: List of SMB2CreateEABuffer structures
:return: bytes object that is set on the SMB2CreateContextRequest
buffer_data field. | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/create_contexts.py#L303-L326 |
jborean93/smbprotocol | smbprotocol/exceptions.py | SMB2SymbolicLinkErrorResponse.set_name | def set_name(self, print_name, substitute_name):
"""
Set's the path_buffer and print/substitute name length of the message
with the values passed in. These values should be a string and not a
byte string as it is encoded in this function.
:param print_name: The print name string to set
:param substitute_name: The substitute name string to set
"""
print_bytes = print_name.encode('utf-16-le')
sub_bytes = substitute_name.encode('utf-16-le')
path_buffer = print_bytes + sub_bytes
self['print_name_offset'].set_value(0)
self['print_name_length'].set_value(len(print_bytes))
self['substitute_name_offset'].set_value(len(print_bytes))
self['substitute_name_length'].set_value(len(sub_bytes))
self['path_buffer'].set_value(path_buffer) | python | def set_name(self, print_name, substitute_name):
"""
Set's the path_buffer and print/substitute name length of the message
with the values passed in. These values should be a string and not a
byte string as it is encoded in this function.
:param print_name: The print name string to set
:param substitute_name: The substitute name string to set
"""
print_bytes = print_name.encode('utf-16-le')
sub_bytes = substitute_name.encode('utf-16-le')
path_buffer = print_bytes + sub_bytes
self['print_name_offset'].set_value(0)
self['print_name_length'].set_value(len(print_bytes))
self['substitute_name_offset'].set_value(len(print_bytes))
self['substitute_name_length'].set_value(len(sub_bytes))
self['path_buffer'].set_value(path_buffer) | Set's the path_buffer and print/substitute name length of the message
with the values passed in. These values should be a string and not a
byte string as it is encoded in this function.
:param print_name: The print name string to set
:param substitute_name: The substitute name string to set | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/exceptions.py#L325-L342 |
jborean93/smbprotocol | smbprotocol/tree.py | TreeConnect.connect | def connect(self, require_secure_negotiate=True):
"""
Connect to the share.
:param require_secure_negotiate: For Dialects 3.0 and 3.0.2, will
verify the negotiation parameters with the server to prevent
SMB downgrade attacks
"""
log.info("Session: %s - Creating connection to share %s"
% (self.session.username, self.share_name))
utf_share_name = self.share_name.encode('utf-16-le')
connect = SMB2TreeConnectRequest()
connect['buffer'] = utf_share_name
log.info("Session: %s - Sending Tree Connect message"
% self.session.username)
log.debug(str(connect))
request = self.session.connection.send(connect,
sid=self.session.session_id)
log.info("Session: %s - Receiving Tree Connect response"
% self.session.username)
response = self.session.connection.receive(request)
tree_response = SMB2TreeConnectResponse()
tree_response.unpack(response['data'].get_value())
log.debug(str(tree_response))
# https://msdn.microsoft.com/en-us/library/cc246687.aspx
self.tree_connect_id = response['tree_id'].get_value()
log.info("Session: %s - Created tree connection with ID %d"
% (self.session.username, self.tree_connect_id))
self._connected = True
self.session.tree_connect_table[self.tree_connect_id] = self
capabilities = tree_response['capabilities']
self.is_dfs_share = capabilities.has_flag(
ShareCapabilities.SMB2_SHARE_CAP_DFS)
self.is_ca_share = capabilities.has_flag(
ShareCapabilities.SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
dialect = self.session.connection.dialect
if dialect >= Dialects.SMB_3_0_0 and \
self.session.connection.supports_encryption:
self.encrypt_data = tree_response['share_flags'].has_flag(
ShareFlags.SMB2_SHAREFLAG_ENCRYPT_DATA)
self.is_scaleout_share = capabilities.has_flag(
ShareCapabilities.SMB2_SHARE_CAP_SCALEOUT)
# secure negotiate is only valid for SMB 3 dialects before 3.1.1
if dialect < Dialects.SMB_3_1_1 and require_secure_negotiate:
self._verify_dialect_negotiate() | python | def connect(self, require_secure_negotiate=True):
"""
Connect to the share.
:param require_secure_negotiate: For Dialects 3.0 and 3.0.2, will
verify the negotiation parameters with the server to prevent
SMB downgrade attacks
"""
log.info("Session: %s - Creating connection to share %s"
% (self.session.username, self.share_name))
utf_share_name = self.share_name.encode('utf-16-le')
connect = SMB2TreeConnectRequest()
connect['buffer'] = utf_share_name
log.info("Session: %s - Sending Tree Connect message"
% self.session.username)
log.debug(str(connect))
request = self.session.connection.send(connect,
sid=self.session.session_id)
log.info("Session: %s - Receiving Tree Connect response"
% self.session.username)
response = self.session.connection.receive(request)
tree_response = SMB2TreeConnectResponse()
tree_response.unpack(response['data'].get_value())
log.debug(str(tree_response))
# https://msdn.microsoft.com/en-us/library/cc246687.aspx
self.tree_connect_id = response['tree_id'].get_value()
log.info("Session: %s - Created tree connection with ID %d"
% (self.session.username, self.tree_connect_id))
self._connected = True
self.session.tree_connect_table[self.tree_connect_id] = self
capabilities = tree_response['capabilities']
self.is_dfs_share = capabilities.has_flag(
ShareCapabilities.SMB2_SHARE_CAP_DFS)
self.is_ca_share = capabilities.has_flag(
ShareCapabilities.SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
dialect = self.session.connection.dialect
if dialect >= Dialects.SMB_3_0_0 and \
self.session.connection.supports_encryption:
self.encrypt_data = tree_response['share_flags'].has_flag(
ShareFlags.SMB2_SHAREFLAG_ENCRYPT_DATA)
self.is_scaleout_share = capabilities.has_flag(
ShareCapabilities.SMB2_SHARE_CAP_SCALEOUT)
# secure negotiate is only valid for SMB 3 dialects before 3.1.1
if dialect < Dialects.SMB_3_1_1 and require_secure_negotiate:
self._verify_dialect_negotiate() | Connect to the share.
:param require_secure_negotiate: For Dialects 3.0 and 3.0.2, will
verify the negotiation parameters with the server to prevent
SMB downgrade attacks | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/tree.py#L197-L248 |
jborean93/smbprotocol | smbprotocol/tree.py | TreeConnect.disconnect | def disconnect(self):
"""
Disconnects the tree connection.
"""
if not self._connected:
return
log.info("Session: %s, Tree: %s - Disconnecting from Tree Connect"
% (self.session.username, self.share_name))
req = SMB2TreeDisconnect()
log.info("Session: %s, Tree: %s - Sending Tree Disconnect message"
% (self.session.username, self.share_name))
log.debug(str(req))
request = self.session.connection.send(req,
sid=self.session.session_id,
tid=self.tree_connect_id)
log.info("Session: %s, Tree: %s - Receiving Tree Disconnect response"
% (self.session.username, self.share_name))
res = self.session.connection.receive(request)
res_disconnect = SMB2TreeDisconnect()
res_disconnect.unpack(res['data'].get_value())
log.debug(str(res_disconnect))
self._connected = False
del self.session.tree_connect_table[self.tree_connect_id] | python | def disconnect(self):
"""
Disconnects the tree connection.
"""
if not self._connected:
return
log.info("Session: %s, Tree: %s - Disconnecting from Tree Connect"
% (self.session.username, self.share_name))
req = SMB2TreeDisconnect()
log.info("Session: %s, Tree: %s - Sending Tree Disconnect message"
% (self.session.username, self.share_name))
log.debug(str(req))
request = self.session.connection.send(req,
sid=self.session.session_id,
tid=self.tree_connect_id)
log.info("Session: %s, Tree: %s - Receiving Tree Disconnect response"
% (self.session.username, self.share_name))
res = self.session.connection.receive(request)
res_disconnect = SMB2TreeDisconnect()
res_disconnect.unpack(res['data'].get_value())
log.debug(str(res_disconnect))
self._connected = False
del self.session.tree_connect_table[self.tree_connect_id] | Disconnects the tree connection. | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/tree.py#L250-L275 |
jborean93/smbprotocol | smbprotocol/connection.py | Connection.connect | def connect(self, dialect=None, timeout=60):
"""
Will connect to the target server and negotiate the capabilities
with the client. Once setup, the client MUST call the disconnect()
function to close the listener thread. This function will populate
various connection properties that denote the capabilities of the
server.
:param dialect: If specified, forces the dialect that is negotiated
with the server, if not set, then the newest dialect supported by
the server is used up to SMB 3.1.1
:param timeout: The timeout in seconds to wait for the initial
negotiation process to complete
"""
log.info("Setting up transport connection")
self.transport.connect()
log.info("Starting negotiation with SMB server")
smb_response = self._send_smb2_negotiate(dialect, timeout)
log.info("Negotiated dialect: %s"
% str(smb_response['dialect_revision']))
self.dialect = smb_response['dialect_revision'].get_value()
self.max_transact_size = smb_response['max_transact_size'].get_value()
self.max_read_size = smb_response['max_read_size'].get_value()
self.max_write_size = smb_response['max_write_size'].get_value()
self.server_guid = smb_response['server_guid'].get_value()
self.gss_negotiate_token = smb_response['buffer'].get_value()
if not self.require_signing and \
smb_response['security_mode'].has_flag(
SecurityMode.SMB2_NEGOTIATE_SIGNING_REQUIRED):
self.require_signing = True
log.info("Connection require signing: %s" % self.require_signing)
capabilities = smb_response['capabilities']
# SMB 2.1
if self.dialect >= Dialects.SMB_2_1_0:
self.supports_file_leasing = \
capabilities.has_flag(Capabilities.SMB2_GLOBAL_CAP_LEASING)
self.supports_multi_credit = \
capabilities.has_flag(Capabilities.SMB2_GLOBAL_CAP_LARGE_MTU)
# SMB 3.x
if self.dialect >= Dialects.SMB_3_0_0:
self.supports_directory_leasing = capabilities.has_flag(
Capabilities.SMB2_GLOBAL_CAP_DIRECTORY_LEASING)
self.supports_multi_channel = capabilities.has_flag(
Capabilities.SMB2_GLOBAL_CAP_MULTI_CHANNEL)
# TODO: SMB2_GLOBAL_CAP_PERSISTENT_HANDLES
self.supports_persistent_handles = False
self.supports_encryption = capabilities.has_flag(
Capabilities.SMB2_GLOBAL_CAP_ENCRYPTION) \
and self.dialect < Dialects.SMB_3_1_1
self.server_capabilities = capabilities
self.server_security_mode = \
smb_response['security_mode'].get_value()
# TODO: Check/add server to server_list in Client Page 203
# SMB 3.1
if self.dialect >= Dialects.SMB_3_1_1:
for context in smb_response['negotiate_context_list']:
if context['context_type'].get_value() == \
NegotiateContextType.SMB2_ENCRYPTION_CAPABILITIES:
cipher_id = context['data']['ciphers'][0]
self.cipher_id = Ciphers.get_cipher(cipher_id)
self.supports_encryption = self.cipher_id != 0
else:
hash_id = context['data']['hash_algorithms'][0]
self.preauth_integrity_hash_id = \
HashAlgorithms.get_algorithm(hash_id) | python | def connect(self, dialect=None, timeout=60):
"""
Will connect to the target server and negotiate the capabilities
with the client. Once setup, the client MUST call the disconnect()
function to close the listener thread. This function will populate
various connection properties that denote the capabilities of the
server.
:param dialect: If specified, forces the dialect that is negotiated
with the server, if not set, then the newest dialect supported by
the server is used up to SMB 3.1.1
:param timeout: The timeout in seconds to wait for the initial
negotiation process to complete
"""
log.info("Setting up transport connection")
self.transport.connect()
log.info("Starting negotiation with SMB server")
smb_response = self._send_smb2_negotiate(dialect, timeout)
log.info("Negotiated dialect: %s"
% str(smb_response['dialect_revision']))
self.dialect = smb_response['dialect_revision'].get_value()
self.max_transact_size = smb_response['max_transact_size'].get_value()
self.max_read_size = smb_response['max_read_size'].get_value()
self.max_write_size = smb_response['max_write_size'].get_value()
self.server_guid = smb_response['server_guid'].get_value()
self.gss_negotiate_token = smb_response['buffer'].get_value()
if not self.require_signing and \
smb_response['security_mode'].has_flag(
SecurityMode.SMB2_NEGOTIATE_SIGNING_REQUIRED):
self.require_signing = True
log.info("Connection require signing: %s" % self.require_signing)
capabilities = smb_response['capabilities']
# SMB 2.1
if self.dialect >= Dialects.SMB_2_1_0:
self.supports_file_leasing = \
capabilities.has_flag(Capabilities.SMB2_GLOBAL_CAP_LEASING)
self.supports_multi_credit = \
capabilities.has_flag(Capabilities.SMB2_GLOBAL_CAP_LARGE_MTU)
# SMB 3.x
if self.dialect >= Dialects.SMB_3_0_0:
self.supports_directory_leasing = capabilities.has_flag(
Capabilities.SMB2_GLOBAL_CAP_DIRECTORY_LEASING)
self.supports_multi_channel = capabilities.has_flag(
Capabilities.SMB2_GLOBAL_CAP_MULTI_CHANNEL)
# TODO: SMB2_GLOBAL_CAP_PERSISTENT_HANDLES
self.supports_persistent_handles = False
self.supports_encryption = capabilities.has_flag(
Capabilities.SMB2_GLOBAL_CAP_ENCRYPTION) \
and self.dialect < Dialects.SMB_3_1_1
self.server_capabilities = capabilities
self.server_security_mode = \
smb_response['security_mode'].get_value()
# TODO: Check/add server to server_list in Client Page 203
# SMB 3.1
if self.dialect >= Dialects.SMB_3_1_1:
for context in smb_response['negotiate_context_list']:
if context['context_type'].get_value() == \
NegotiateContextType.SMB2_ENCRYPTION_CAPABILITIES:
cipher_id = context['data']['ciphers'][0]
self.cipher_id = Ciphers.get_cipher(cipher_id)
self.supports_encryption = self.cipher_id != 0
else:
hash_id = context['data']['hash_algorithms'][0]
self.preauth_integrity_hash_id = \
HashAlgorithms.get_algorithm(hash_id) | Will connect to the target server and negotiate the capabilities
with the client. Once setup, the client MUST call the disconnect()
function to close the listener thread. This function will populate
various connection properties that denote the capabilities of the
server.
:param dialect: If specified, forces the dialect that is negotiated
with the server, if not set, then the newest dialect supported by
the server is used up to SMB 3.1.1
:param timeout: The timeout in seconds to wait for the initial
negotiation process to complete | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L820-L891 |
jborean93/smbprotocol | smbprotocol/connection.py | Connection.disconnect | def disconnect(self, close=True):
"""
Closes the connection as well as logs off any of the
Disconnects the TCP connection and shuts down the socket listener
running in a thread.
:param close: Will close all sessions in the connection as well as the
tree connections of each session.
"""
if close:
for session in list(self.session_table.values()):
session.disconnect(True)
log.info("Disconnecting transport connection")
self.transport.disconnect() | python | def disconnect(self, close=True):
"""
Closes the connection as well as logs off any of the
Disconnects the TCP connection and shuts down the socket listener
running in a thread.
:param close: Will close all sessions in the connection as well as the
tree connections of each session.
"""
if close:
for session in list(self.session_table.values()):
session.disconnect(True)
log.info("Disconnecting transport connection")
self.transport.disconnect() | Closes the connection as well as logs off any of the
Disconnects the TCP connection and shuts down the socket listener
running in a thread.
:param close: Will close all sessions in the connection as well as the
tree connections of each session. | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L893-L907 |
jborean93/smbprotocol | smbprotocol/connection.py | Connection.send | def send(self, message, sid=None, tid=None, credit_request=None):
"""
Will send a message to the server that is passed in. The final
unencrypted header is returned to the function that called this.
:param message: An SMB message structure to send
:param sid: A session_id that the message is sent for
:param tid: A tree_id object that the message is sent for
:param credit_request: Specifies extra credits to be requested with the
SMB header
:return: Request of the message that was sent
"""
header = self._generate_packet_header(message, sid, tid,
credit_request)
# get the actual Session and TreeConnect object instead of the IDs
session = self.session_table.get(sid, None) if sid else None
tree = None
if tid and session:
if tid not in session.tree_connect_table.keys():
error_msg = "Cannot find Tree with the ID %d in the session " \
"tree table" % tid
raise smbprotocol.exceptions.SMBException(error_msg)
tree = session.tree_connect_table[tid]
if session and session.signing_required and session.signing_key:
self._sign(header, session)
request = Request(header)
self.outstanding_requests[header['message_id'].get_value()] = request
send_data = header.pack()
if (session and session.encrypt_data) or (tree and tree.encrypt_data):
send_data = self._encrypt(send_data, session)
self.transport.send(send_data)
return request | python | def send(self, message, sid=None, tid=None, credit_request=None):
"""
Will send a message to the server that is passed in. The final
unencrypted header is returned to the function that called this.
:param message: An SMB message structure to send
:param sid: A session_id that the message is sent for
:param tid: A tree_id object that the message is sent for
:param credit_request: Specifies extra credits to be requested with the
SMB header
:return: Request of the message that was sent
"""
header = self._generate_packet_header(message, sid, tid,
credit_request)
# get the actual Session and TreeConnect object instead of the IDs
session = self.session_table.get(sid, None) if sid else None
tree = None
if tid and session:
if tid not in session.tree_connect_table.keys():
error_msg = "Cannot find Tree with the ID %d in the session " \
"tree table" % tid
raise smbprotocol.exceptions.SMBException(error_msg)
tree = session.tree_connect_table[tid]
if session and session.signing_required and session.signing_key:
self._sign(header, session)
request = Request(header)
self.outstanding_requests[header['message_id'].get_value()] = request
send_data = header.pack()
if (session and session.encrypt_data) or (tree and tree.encrypt_data):
send_data = self._encrypt(send_data, session)
self.transport.send(send_data)
return request | Will send a message to the server that is passed in. The final
unencrypted header is returned to the function that called this.
:param message: An SMB message structure to send
:param sid: A session_id that the message is sent for
:param tid: A tree_id object that the message is sent for
:param credit_request: Specifies extra credits to be requested with the
SMB header
:return: Request of the message that was sent | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L909-L946 |
jborean93/smbprotocol | smbprotocol/connection.py | Connection.send_compound | def send_compound(self, messages, sid, tid, related=False):
"""
Sends multiple messages within 1 TCP request, will fail if the size
of the total length exceeds the maximum of the transport max.
:param messages: A list of messages to send to the server
:param sid: The session_id that the request is sent for
:param tid: A tree_id object that the message is sent for
:return: List<Request> for each request that was sent, each entry in
the list is in the same order of the message list that was passed
in
"""
send_data = b""
session = self.session_table[sid]
tree = session.tree_connect_table[tid]
requests = []
total_requests = len(messages)
for i, message in enumerate(messages):
if i == total_requests - 1:
next_command = 0
padding = b""
else:
msg_length = 64 + len(message)
# each compound message must start at the 8-byte boundary
mod = msg_length % 8
padding_length = 8 - mod if mod > 0 else 0
padding = b"\x00" * padding_length
next_command = msg_length + padding_length
header = self._generate_packet_header(message, sid, tid, None)
header['next_command'] = next_command
if i != 0 and related:
header['session_id'] = b"\xff" * 8
header['tree_id'] = b"\xff" * 4
header['flags'].set_flag(
Smb2Flags.SMB2_FLAGS_RELATED_OPERATIONS
)
if session.signing_required and session.signing_key:
self._sign(header, session, padding=padding)
send_data += header.pack() + padding
request = Request(header)
requests.append(request)
self.outstanding_requests[header['message_id'].get_value()] = \
request
if session.encrypt_data or tree.encrypt_data:
send_data = self._encrypt(send_data, session)
self.transport.send(send_data)
return requests | python | def send_compound(self, messages, sid, tid, related=False):
"""
Sends multiple messages within 1 TCP request, will fail if the size
of the total length exceeds the maximum of the transport max.
:param messages: A list of messages to send to the server
:param sid: The session_id that the request is sent for
:param tid: A tree_id object that the message is sent for
:return: List<Request> for each request that was sent, each entry in
the list is in the same order of the message list that was passed
in
"""
send_data = b""
session = self.session_table[sid]
tree = session.tree_connect_table[tid]
requests = []
total_requests = len(messages)
for i, message in enumerate(messages):
if i == total_requests - 1:
next_command = 0
padding = b""
else:
msg_length = 64 + len(message)
# each compound message must start at the 8-byte boundary
mod = msg_length % 8
padding_length = 8 - mod if mod > 0 else 0
padding = b"\x00" * padding_length
next_command = msg_length + padding_length
header = self._generate_packet_header(message, sid, tid, None)
header['next_command'] = next_command
if i != 0 and related:
header['session_id'] = b"\xff" * 8
header['tree_id'] = b"\xff" * 4
header['flags'].set_flag(
Smb2Flags.SMB2_FLAGS_RELATED_OPERATIONS
)
if session.signing_required and session.signing_key:
self._sign(header, session, padding=padding)
send_data += header.pack() + padding
request = Request(header)
requests.append(request)
self.outstanding_requests[header['message_id'].get_value()] = \
request
if session.encrypt_data or tree.encrypt_data:
send_data = self._encrypt(send_data, session)
self.transport.send(send_data)
return requests | Sends multiple messages within 1 TCP request, will fail if the size
of the total length exceeds the maximum of the transport max.
:param messages: A list of messages to send to the server
:param sid: The session_id that the request is sent for
:param tid: A tree_id object that the message is sent for
:return: List<Request> for each request that was sent, each entry in
the list is in the same order of the message list that was passed
in | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L948-L1002 |
jborean93/smbprotocol | smbprotocol/connection.py | Connection.receive | def receive(self, request, wait=True, timeout=None):
"""
Polls the message buffer of the TCP connection and waits until a valid
message is received based on the message_id passed in.
:param request: The Request object to wait get the response for
:param wait: Wait for the final response in the case of a
STATUS_PENDING response, the pending response is returned in the
case of wait=False
:param timeout: Set a timeout used while waiting for a response from
the server
:return: SMB2HeaderResponse of the received message
"""
start_time = time.time()
# check if we have received a response
while True:
self._flush_message_buffer()
status = request.response['status'].get_value() if \
request.response else None
if status is not None and (wait and
status != NtStatus.STATUS_PENDING):
break
current_time = time.time() - start_time
if timeout and (current_time > timeout):
error_msg = "Connection timeout of %d seconds exceeded while" \
" waiting for a response from the server" \
% timeout
raise smbprotocol.exceptions.SMBException(error_msg)
response = request.response
status = response['status'].get_value()
if status not in [NtStatus.STATUS_SUCCESS, NtStatus.STATUS_PENDING]:
raise smbprotocol.exceptions.SMBResponseException(response, status)
# now we have a retrieval request for the response, we can delete
# the request from the outstanding requests
message_id = request.message['message_id'].get_value()
del self.outstanding_requests[message_id]
return response | python | def receive(self, request, wait=True, timeout=None):
"""
Polls the message buffer of the TCP connection and waits until a valid
message is received based on the message_id passed in.
:param request: The Request object to wait get the response for
:param wait: Wait for the final response in the case of a
STATUS_PENDING response, the pending response is returned in the
case of wait=False
:param timeout: Set a timeout used while waiting for a response from
the server
:return: SMB2HeaderResponse of the received message
"""
start_time = time.time()
# check if we have received a response
while True:
self._flush_message_buffer()
status = request.response['status'].get_value() if \
request.response else None
if status is not None and (wait and
status != NtStatus.STATUS_PENDING):
break
current_time = time.time() - start_time
if timeout and (current_time > timeout):
error_msg = "Connection timeout of %d seconds exceeded while" \
" waiting for a response from the server" \
% timeout
raise smbprotocol.exceptions.SMBException(error_msg)
response = request.response
status = response['status'].get_value()
if status not in [NtStatus.STATUS_SUCCESS, NtStatus.STATUS_PENDING]:
raise smbprotocol.exceptions.SMBResponseException(response, status)
# now we have a retrieval request for the response, we can delete
# the request from the outstanding requests
message_id = request.message['message_id'].get_value()
del self.outstanding_requests[message_id]
return response | Polls the message buffer of the TCP connection and waits until a valid
message is received based on the message_id passed in.
:param request: The Request object to wait get the response for
:param wait: Wait for the final response in the case of a
STATUS_PENDING response, the pending response is returned in the
case of wait=False
:param timeout: Set a timeout used while waiting for a response from
the server
:return: SMB2HeaderResponse of the received message | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1004-L1044 |
jborean93/smbprotocol | smbprotocol/connection.py | Connection.echo | def echo(self, sid=0, timeout=60, credit_request=1):
"""
Sends an SMB2 Echo request to the server. This can be used to request
more credits from the server with the credit_request param.
On a Samba server, the sid can be 0 but for a Windows SMB Server, the
sid of an authenticated session must be passed into this function or
else the socket will close.
:param sid: When talking to a Windows host this must be populated with
a valid session_id from a negotiated session
:param timeout: The timeout in seconds to wait for the Echo Response
:param credit_request: The number of credits to request
:return: the credits that were granted by the server
"""
log.info("Sending Echo request with a timeout of %d and credit "
"request of %d" % (timeout, credit_request))
echo_msg = SMB2Echo()
log.debug(str(echo_msg))
req = self.send(echo_msg, sid=sid, credit_request=credit_request)
log.info("Receiving Echo response")
response = self.receive(req, timeout=timeout)
log.info("Credits granted from the server echo response: %d"
% response['credit_response'].get_value())
echo_resp = SMB2Echo()
echo_resp.unpack(response['data'].get_value())
log.debug(str(echo_resp))
return response['credit_response'].get_value() | python | def echo(self, sid=0, timeout=60, credit_request=1):
"""
Sends an SMB2 Echo request to the server. This can be used to request
more credits from the server with the credit_request param.
On a Samba server, the sid can be 0 but for a Windows SMB Server, the
sid of an authenticated session must be passed into this function or
else the socket will close.
:param sid: When talking to a Windows host this must be populated with
a valid session_id from a negotiated session
:param timeout: The timeout in seconds to wait for the Echo Response
:param credit_request: The number of credits to request
:return: the credits that were granted by the server
"""
log.info("Sending Echo request with a timeout of %d and credit "
"request of %d" % (timeout, credit_request))
echo_msg = SMB2Echo()
log.debug(str(echo_msg))
req = self.send(echo_msg, sid=sid, credit_request=credit_request)
log.info("Receiving Echo response")
response = self.receive(req, timeout=timeout)
log.info("Credits granted from the server echo response: %d"
% response['credit_response'].get_value())
echo_resp = SMB2Echo()
echo_resp.unpack(response['data'].get_value())
log.debug(str(echo_resp))
return response['credit_response'].get_value() | Sends an SMB2 Echo request to the server. This can be used to request
more credits from the server with the credit_request param.
On a Samba server, the sid can be 0 but for a Windows SMB Server, the
sid of an authenticated session must be passed into this function or
else the socket will close.
:param sid: When talking to a Windows host this must be populated with
a valid session_id from a negotiated session
:param timeout: The timeout in seconds to wait for the Echo Response
:param credit_request: The number of credits to request
:return: the credits that were granted by the server | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1046-L1076 |
jborean93/smbprotocol | smbprotocol/connection.py | Connection._flush_message_buffer | def _flush_message_buffer(self):
"""
Loops through the transport message_buffer until there are no messages
left in the queue. Each response is assigned to the Request object
based on the message_id which are then available in
self.outstanding_requests
"""
while True:
message_bytes = self.transport.receive()
# there were no messages receives, so break from the loop
if message_bytes is None:
break
# check if the message is encrypted and decrypt if necessary
if message_bytes[:4] == b"\xfdSMB":
message = SMB2TransformHeader()
message.unpack(message_bytes)
message_bytes = self._decrypt(message)
# now retrieve message(s) from response
is_last = False
session_id = None
while not is_last:
next_command = struct.unpack("<L", message_bytes[20:24])[0]
header_length = \
next_command if next_command != 0 else len(message_bytes)
header_bytes = message_bytes[:header_length]
message = SMB2HeaderResponse()
message.unpack(header_bytes)
flags = message['flags']
if not flags.has_flag(Smb2Flags.SMB2_FLAGS_RELATED_OPERATIONS):
session_id = message['session_id'].get_value()
self._verify(message, session_id)
message_id = message['message_id'].get_value()
request = self.outstanding_requests.get(message_id, None)
if not request:
error_msg = "Received response with an unknown message " \
"ID: %d" % message_id
raise smbprotocol.exceptions.SMBException(error_msg)
# add the upper credit limit based on the credits granted by
# the server
credit_response = message['credit_response'].get_value()
self.sequence_window['high'] += \
credit_response if credit_response > 0 else 1
request.response = message
self.outstanding_requests[message_id] = request
message_bytes = message_bytes[header_length:]
is_last = next_command == 0 | python | def _flush_message_buffer(self):
"""
Loops through the transport message_buffer until there are no messages
left in the queue. Each response is assigned to the Request object
based on the message_id which are then available in
self.outstanding_requests
"""
while True:
message_bytes = self.transport.receive()
# there were no messages receives, so break from the loop
if message_bytes is None:
break
# check if the message is encrypted and decrypt if necessary
if message_bytes[:4] == b"\xfdSMB":
message = SMB2TransformHeader()
message.unpack(message_bytes)
message_bytes = self._decrypt(message)
# now retrieve message(s) from response
is_last = False
session_id = None
while not is_last:
next_command = struct.unpack("<L", message_bytes[20:24])[0]
header_length = \
next_command if next_command != 0 else len(message_bytes)
header_bytes = message_bytes[:header_length]
message = SMB2HeaderResponse()
message.unpack(header_bytes)
flags = message['flags']
if not flags.has_flag(Smb2Flags.SMB2_FLAGS_RELATED_OPERATIONS):
session_id = message['session_id'].get_value()
self._verify(message, session_id)
message_id = message['message_id'].get_value()
request = self.outstanding_requests.get(message_id, None)
if not request:
error_msg = "Received response with an unknown message " \
"ID: %d" % message_id
raise smbprotocol.exceptions.SMBException(error_msg)
# add the upper credit limit based on the credits granted by
# the server
credit_response = message['credit_response'].get_value()
self.sequence_window['high'] += \
credit_response if credit_response > 0 else 1
request.response = message
self.outstanding_requests[message_id] = request
message_bytes = message_bytes[header_length:]
is_last = next_command == 0 | Loops through the transport message_buffer until there are no messages
left in the queue. Each response is assigned to the Request object
based on the message_id which are then available in
self.outstanding_requests | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1120-L1173 |
jborean93/smbprotocol | smbprotocol/connection.py | Connection._calculate_credit_charge | def _calculate_credit_charge(self, message):
"""
Calculates the credit charge for a request based on the command. If
connection.supports_multi_credit is not True then the credit charge
isn't valid so it returns 0.
The credit charge is the number of credits that are required for
sending/receiving data over 64 kilobytes, in the existing messages only
the Read, Write, Query Directory or IOCTL commands will end in this
scenario and each require their own calculation to get the proper
value. The generic formula for calculating the credit charge is
https://msdn.microsoft.com/en-us/library/dn529312.aspx
(max(SendPayloadSize, Expected ResponsePayloadSize) - 1) / 65536 + 1
:param message: The message being sent
:return: The credit charge to set on the header
"""
credit_size = 65536
if not self.supports_multi_credit:
credit_charge = 0
elif message.COMMAND == Commands.SMB2_READ:
max_size = message['length'].get_value() + \
message['read_channel_info_length'].get_value() - 1
credit_charge = math.ceil(max_size / credit_size)
elif message.COMMAND == Commands.SMB2_WRITE:
max_size = message['length'].get_value() + \
message['write_channel_info_length'].get_value() - 1
credit_charge = math.ceil(max_size / credit_size)
elif message.COMMAND == Commands.SMB2_IOCTL:
max_in_size = len(message['buffer'])
max_out_size = message['max_output_response'].get_value()
max_size = max(max_in_size, max_out_size) - 1
credit_charge = math.ceil(max_size / credit_size)
elif message.COMMAND == Commands.SMB2_QUERY_DIRECTORY:
max_in_size = len(message['buffer'])
max_out_size = message['output_buffer_length'].get_value()
max_size = max(max_in_size, max_out_size) - 1
credit_charge = math.ceil(max_size / credit_size)
else:
credit_charge = 1
# python 2 returns a float where we need an integer
return int(credit_charge) | python | def _calculate_credit_charge(self, message):
"""
Calculates the credit charge for a request based on the command. If
connection.supports_multi_credit is not True then the credit charge
isn't valid so it returns 0.
The credit charge is the number of credits that are required for
sending/receiving data over 64 kilobytes, in the existing messages only
the Read, Write, Query Directory or IOCTL commands will end in this
scenario and each require their own calculation to get the proper
value. The generic formula for calculating the credit charge is
https://msdn.microsoft.com/en-us/library/dn529312.aspx
(max(SendPayloadSize, Expected ResponsePayloadSize) - 1) / 65536 + 1
:param message: The message being sent
:return: The credit charge to set on the header
"""
credit_size = 65536
if not self.supports_multi_credit:
credit_charge = 0
elif message.COMMAND == Commands.SMB2_READ:
max_size = message['length'].get_value() + \
message['read_channel_info_length'].get_value() - 1
credit_charge = math.ceil(max_size / credit_size)
elif message.COMMAND == Commands.SMB2_WRITE:
max_size = message['length'].get_value() + \
message['write_channel_info_length'].get_value() - 1
credit_charge = math.ceil(max_size / credit_size)
elif message.COMMAND == Commands.SMB2_IOCTL:
max_in_size = len(message['buffer'])
max_out_size = message['max_output_response'].get_value()
max_size = max(max_in_size, max_out_size) - 1
credit_charge = math.ceil(max_size / credit_size)
elif message.COMMAND == Commands.SMB2_QUERY_DIRECTORY:
max_in_size = len(message['buffer'])
max_out_size = message['output_buffer_length'].get_value()
max_size = max(max_in_size, max_out_size) - 1
credit_charge = math.ceil(max_size / credit_size)
else:
credit_charge = 1
# python 2 returns a float where we need an integer
return int(credit_charge) | Calculates the credit charge for a request based on the command. If
connection.supports_multi_credit is not True then the credit charge
isn't valid so it returns 0.
The credit charge is the number of credits that are required for
sending/receiving data over 64 kilobytes, in the existing messages only
the Read, Write, Query Directory or IOCTL commands will end in this
scenario and each require their own calculation to get the proper
value. The generic formula for calculating the credit charge is
https://msdn.microsoft.com/en-us/library/dn529312.aspx
(max(SendPayloadSize, Expected ResponsePayloadSize) - 1) / 65536 + 1
:param message: The message being sent
:return: The credit charge to set on the header | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/connection.py#L1364-L1408 |
jborean93/smbprotocol | smbprotocol/session.py | Session.disconnect | def disconnect(self, close=True):
"""
Logs off the session
:param close: Will close all tree connects in a session
"""
if not self._connected:
# already disconnected so let's return
return
if close:
for open in list(self.open_table.values()):
open.close(False)
for tree in list(self.tree_connect_table.values()):
tree.disconnect()
log.info("Session: %s - Logging off of SMB Session" % self.username)
logoff = SMB2Logoff()
log.info("Session: %s - Sending Logoff message" % self.username)
log.debug(str(logoff))
request = self.connection.send(logoff, sid=self.session_id)
log.info("Session: %s - Receiving Logoff response" % self.username)
res = self.connection.receive(request)
res_logoff = SMB2Logoff()
res_logoff.unpack(res['data'].get_value())
log.debug(str(res_logoff))
self._connected = False
del self.connection.session_table[self.session_id] | python | def disconnect(self, close=True):
"""
Logs off the session
:param close: Will close all tree connects in a session
"""
if not self._connected:
# already disconnected so let's return
return
if close:
for open in list(self.open_table.values()):
open.close(False)
for tree in list(self.tree_connect_table.values()):
tree.disconnect()
log.info("Session: %s - Logging off of SMB Session" % self.username)
logoff = SMB2Logoff()
log.info("Session: %s - Sending Logoff message" % self.username)
log.debug(str(logoff))
request = self.connection.send(logoff, sid=self.session_id)
log.info("Session: %s - Receiving Logoff response" % self.username)
res = self.connection.receive(request)
res_logoff = SMB2Logoff()
res_logoff.unpack(res['data'].get_value())
log.debug(str(res_logoff))
self._connected = False
del self.connection.session_table[self.session_id] | Logs off the session
:param close: Will close all tree connects in a session | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/session.py#L344-L373 |
jborean93/smbprotocol | smbprotocol/session.py | Session._smb3kdf | def _smb3kdf(self, ki, label, context):
"""
See SMB 3.x key derivation function
https://blogs.msdn.microsoft.com/openspecification/2017/05/26/smb-2-and-smb-3-security-in-windows-10-the-anatomy-of-signing-and-cryptographic-keys/
:param ki: The session key is the KDK used as an input to the KDF
:param label: The purpose of this derived key as bytes string
:param context: The context information of this derived key as bytes
string
:return: Key derived by the KDF as specified by [SP800-108] 5.1
"""
kdf = KBKDFHMAC(
algorithm=hashes.SHA256(),
mode=Mode.CounterMode,
length=16,
rlen=4,
llen=4,
location=CounterLocation.BeforeFixed,
label=label,
context=context,
fixed=None,
backend=default_backend()
)
return kdf.derive(ki) | python | def _smb3kdf(self, ki, label, context):
"""
See SMB 3.x key derivation function
https://blogs.msdn.microsoft.com/openspecification/2017/05/26/smb-2-and-smb-3-security-in-windows-10-the-anatomy-of-signing-and-cryptographic-keys/
:param ki: The session key is the KDK used as an input to the KDF
:param label: The purpose of this derived key as bytes string
:param context: The context information of this derived key as bytes
string
:return: Key derived by the KDF as specified by [SP800-108] 5.1
"""
kdf = KBKDFHMAC(
algorithm=hashes.SHA256(),
mode=Mode.CounterMode,
length=16,
rlen=4,
llen=4,
location=CounterLocation.BeforeFixed,
label=label,
context=context,
fixed=None,
backend=default_backend()
)
return kdf.derive(ki) | See SMB 3.x key derivation function
https://blogs.msdn.microsoft.com/openspecification/2017/05/26/smb-2-and-smb-3-security-in-windows-10-the-anatomy-of-signing-and-cryptographic-keys/
:param ki: The session key is the KDK used as an input to the KDF
:param label: The purpose of this derived key as bytes string
:param context: The context information of this derived key as bytes
string
:return: Key derived by the KDF as specified by [SP800-108] 5.1 | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/session.py#L429-L452 |
jborean93/smbprotocol | smbprotocol/structure.py | Field.pack | def pack(self):
"""
Packs the field value into a byte string so it can be sent to the
server.
:param structure: The message structure class object
:return: A byte string of the packed field's value
"""
value = self._get_calculated_value(self.value)
packed_value = self._pack_value(value)
size = self._get_calculated_size(self.size, packed_value)
if len(packed_value) != size:
raise ValueError("Invalid packed data length for field %s of %d "
"does not fit field size of %d"
% (self.name, len(packed_value), size))
return packed_value | python | def pack(self):
"""
Packs the field value into a byte string so it can be sent to the
server.
:param structure: The message structure class object
:return: A byte string of the packed field's value
"""
value = self._get_calculated_value(self.value)
packed_value = self._pack_value(value)
size = self._get_calculated_size(self.size, packed_value)
if len(packed_value) != size:
raise ValueError("Invalid packed data length for field %s of %d "
"does not fit field size of %d"
% (self.name, len(packed_value), size))
return packed_value | Packs the field value into a byte string so it can be sent to the
server.
:param structure: The message structure class object
:return: A byte string of the packed field's value | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L164-L180 |
jborean93/smbprotocol | smbprotocol/structure.py | Field.set_value | def set_value(self, value):
"""
Parses, and sets the value attribute for the field.
:param value: The value to be parsed and set, the allowed input types
vary depending on the Field used
"""
parsed_value = self._parse_value(value)
self.value = parsed_value | python | def set_value(self, value):
"""
Parses, and sets the value attribute for the field.
:param value: The value to be parsed and set, the allowed input types
vary depending on the Field used
"""
parsed_value = self._parse_value(value)
self.value = parsed_value | Parses, and sets the value attribute for the field.
:param value: The value to be parsed and set, the allowed input types
vary depending on the Field used | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L192-L200 |
jborean93/smbprotocol | smbprotocol/structure.py | Field.unpack | def unpack(self, data):
"""
Takes in a byte string and set's the field value based on field
definition.
:param structure: The message structure class object
:param data: The byte string of the data to unpack
:return: The remaining data for subsequent fields
"""
size = self._get_calculated_size(self.size, data)
self.set_value(data[0:size])
return data[len(self):] | python | def unpack(self, data):
"""
Takes in a byte string and set's the field value based on field
definition.
:param structure: The message structure class object
:param data: The byte string of the data to unpack
:return: The remaining data for subsequent fields
"""
size = self._get_calculated_size(self.size, data)
self.set_value(data[0:size])
return data[len(self):] | Takes in a byte string and set's the field value based on field
definition.
:param structure: The message structure class object
:param data: The byte string of the data to unpack
:return: The remaining data for subsequent fields | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L202-L213 |
jborean93/smbprotocol | smbprotocol/structure.py | Field._get_calculated_value | def _get_calculated_value(self, value):
"""
Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value
"""
if isinstance(value, types.LambdaType):
expanded_value = value(self.structure)
return self._get_calculated_value(expanded_value)
else:
# perform one final parsing of the value in case lambda value
# returned a different type
return self._parse_value(value) | python | def _get_calculated_value(self, value):
"""
Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value
"""
if isinstance(value, types.LambdaType):
expanded_value = value(self.structure)
return self._get_calculated_value(expanded_value)
else:
# perform one final parsing of the value in case lambda value
# returned a different type
return self._parse_value(value) | Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L258-L272 |
jborean93/smbprotocol | smbprotocol/structure.py | Field._get_calculated_size | def _get_calculated_size(self, size, data):
"""
Get's the final size of the field and runs the lambda functions
recursively until a final size is derived. If size is None then it
will just return the length of the data as it is assumed it is the
final field (None should only be set on size for the final field).
:param size: The size to calculate/expand
:param data: The data that the size is being calculated for
:return: The final size
"""
# if the size is derived from a lambda function, run it now; otherwise
# return the value we passed in or the length of the data if the size
# is None (last field value)
if size is None:
return len(data)
elif isinstance(size, types.LambdaType):
expanded_size = size(self.structure)
return self._get_calculated_size(expanded_size, data)
else:
return size | python | def _get_calculated_size(self, size, data):
"""
Get's the final size of the field and runs the lambda functions
recursively until a final size is derived. If size is None then it
will just return the length of the data as it is assumed it is the
final field (None should only be set on size for the final field).
:param size: The size to calculate/expand
:param data: The data that the size is being calculated for
:return: The final size
"""
# if the size is derived from a lambda function, run it now; otherwise
# return the value we passed in or the length of the data if the size
# is None (last field value)
if size is None:
return len(data)
elif isinstance(size, types.LambdaType):
expanded_size = size(self.structure)
return self._get_calculated_size(expanded_size, data)
else:
return size | Get's the final size of the field and runs the lambda functions
recursively until a final size is derived. If size is None then it
will just return the length of the data as it is assumed it is the
final field (None should only be set on size for the final field).
:param size: The size to calculate/expand
:param data: The data that the size is being calculated for
:return: The final size | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L274-L294 |
jborean93/smbprotocol | smbprotocol/structure.py | Field._get_struct_format | def _get_struct_format(self, size):
"""
Get's the format specified for use in struct. This is only designed
for 1, 2, 4, or 8 byte values and will throw an exception if it is
anything else.
:param size: The size as an int
:return: The struct format specifier for the size specified
"""
if isinstance(size, types.LambdaType):
size = size(self.structure)
struct_format = {
1: 'B',
2: 'H',
4: 'L',
8: 'Q'
}
if size not in struct_format.keys():
raise InvalidFieldDefinition("Cannot struct format of size %s"
% size)
return struct_format[size] | python | def _get_struct_format(self, size):
"""
Get's the format specified for use in struct. This is only designed
for 1, 2, 4, or 8 byte values and will throw an exception if it is
anything else.
:param size: The size as an int
:return: The struct format specifier for the size specified
"""
if isinstance(size, types.LambdaType):
size = size(self.structure)
struct_format = {
1: 'B',
2: 'H',
4: 'L',
8: 'Q'
}
if size not in struct_format.keys():
raise InvalidFieldDefinition("Cannot struct format of size %s"
% size)
return struct_format[size] | Get's the format specified for use in struct. This is only designed
for 1, 2, 4, or 8 byte values and will throw an exception if it is
anything else.
:param size: The size as an int
:return: The struct format specifier for the size specified | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/structure.py#L296-L317 |
jborean93/smbprotocol | smbprotocol/open.py | SMB2QueryDirectoryRequest.unpack_response | def unpack_response(file_information_class, buffer):
"""
Pass in the buffer value from the response object to unpack it and
return a list of query response structures for the request.
:param buffer: The raw bytes value of the SMB2QueryDirectoryResponse
buffer field.
:return: List of query_info.* structures based on the
FileInformationClass used in the initial query request.
"""
structs = smbprotocol.query_info
resp_structure = {
FileInformationClass.FILE_DIRECTORY_INFORMATION:
structs.FileDirectoryInformation,
FileInformationClass.FILE_NAMES_INFORMATION:
structs.FileNamesInformation,
FileInformationClass.FILE_BOTH_DIRECTORY_INFORMATION:
structs.FileBothDirectoryInformation,
FileInformationClass.FILE_ID_BOTH_DIRECTORY_INFORMATION:
structs.FileIdBothDirectoryInformation,
FileInformationClass.FILE_FULL_DIRECTORY_INFORMATION:
structs.FileFullDirectoryInformation,
FileInformationClass.FILE_ID_FULL_DIRECTORY_INFORMATION:
structs.FileIdFullDirectoryInformation,
}[file_information_class]
query_results = []
current_offset = 0
is_next = True
while is_next:
result = resp_structure()
result.unpack(buffer[current_offset:])
query_results.append(result)
current_offset += result['next_entry_offset'].get_value()
is_next = result['next_entry_offset'].get_value() != 0
return query_results | python | def unpack_response(file_information_class, buffer):
"""
Pass in the buffer value from the response object to unpack it and
return a list of query response structures for the request.
:param buffer: The raw bytes value of the SMB2QueryDirectoryResponse
buffer field.
:return: List of query_info.* structures based on the
FileInformationClass used in the initial query request.
"""
structs = smbprotocol.query_info
resp_structure = {
FileInformationClass.FILE_DIRECTORY_INFORMATION:
structs.FileDirectoryInformation,
FileInformationClass.FILE_NAMES_INFORMATION:
structs.FileNamesInformation,
FileInformationClass.FILE_BOTH_DIRECTORY_INFORMATION:
structs.FileBothDirectoryInformation,
FileInformationClass.FILE_ID_BOTH_DIRECTORY_INFORMATION:
structs.FileIdBothDirectoryInformation,
FileInformationClass.FILE_FULL_DIRECTORY_INFORMATION:
structs.FileFullDirectoryInformation,
FileInformationClass.FILE_ID_FULL_DIRECTORY_INFORMATION:
structs.FileIdFullDirectoryInformation,
}[file_information_class]
query_results = []
current_offset = 0
is_next = True
while is_next:
result = resp_structure()
result.unpack(buffer[current_offset:])
query_results.append(result)
current_offset += result['next_entry_offset'].get_value()
is_next = result['next_entry_offset'].get_value() != 0
return query_results | Pass in the buffer value from the response object to unpack it and
return a list of query response structures for the request.
:param buffer: The raw bytes value of the SMB2QueryDirectoryResponse
buffer field.
:return: List of query_info.* structures based on the
FileInformationClass used in the initial query request. | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/open.py#L804-L840 |
jborean93/smbprotocol | smbprotocol/open.py | Open.create | def create(self, impersonation_level, desired_access, file_attributes,
share_access, create_disposition, create_options,
create_contexts=None, send=True):
"""
This will open the file based on the input parameters supplied. Any
file open should also be called with Open.close() when it is finished.
More details on how each option affects the open process can be found
here https://msdn.microsoft.com/en-us/library/cc246502.aspx.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2CreateRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param impersonation_level: (ImpersonationLevel) The type of
impersonation level that is issuing the create request.
:param desired_access: The level of access that is required of the
open. FilePipePrinterAccessMask or DirectoryAccessMask should be
used depending on the type of file being opened.
:param file_attributes: (FileAttributes) attributes to set on the file
being opened, this usually is for opens that creates a file.
:param share_access: (ShareAccess) Specifies the sharing mode for the
open.
:param create_disposition: (CreateDisposition) Defines the action the
server MUST take if the file already exists.
:param create_options: (CreateOptions) Specifies the options to be
applied when creating or opening the file.
:param create_contexts: (List<SMB2CreateContextRequest>) List of
context request values to be applied to the create.
Create Contexts are used to encode additional flags and attributes when
opening files. More details on create context request values can be
found here https://msdn.microsoft.com/en-us/library/cc246504.aspx.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: List of context response values or None if there are no
context response values. If the context response value is not known
to smbprotocol then the list value would be raw bytes otherwise
it is a Structure defined in create_contexts.py
"""
create = SMB2CreateRequest()
create['impersonation_level'] = impersonation_level
create['desired_access'] = desired_access
create['file_attributes'] = file_attributes
create['share_access'] = share_access
create['create_disposition'] = create_disposition
create['create_options'] = create_options
if self.file_name == "":
create['buffer_path'] = b"\x00\x00"
else:
create['buffer_path'] = self.file_name.encode('utf-16-le')
if create_contexts:
create['buffer_contexts'] = smbprotocol.create_contexts.\
SMB2CreateContextRequest.pack_multiple(create_contexts)
if self.connection.dialect >= Dialects.SMB_3_0_0:
self.desired_access = desired_access
self.share_mode = share_access
self.create_options = create_options
self.file_attributes = file_attributes
self.create_disposition = create_disposition
if not send:
return create, self._create_response
log.info("Session: %s, Tree Connect: %s - sending SMB2 Create Request "
"for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(create))
request = self.connection.send(create,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._create_response(request) | python | def create(self, impersonation_level, desired_access, file_attributes,
share_access, create_disposition, create_options,
create_contexts=None, send=True):
"""
This will open the file based on the input parameters supplied. Any
file open should also be called with Open.close() when it is finished.
More details on how each option affects the open process can be found
here https://msdn.microsoft.com/en-us/library/cc246502.aspx.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2CreateRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param impersonation_level: (ImpersonationLevel) The type of
impersonation level that is issuing the create request.
:param desired_access: The level of access that is required of the
open. FilePipePrinterAccessMask or DirectoryAccessMask should be
used depending on the type of file being opened.
:param file_attributes: (FileAttributes) attributes to set on the file
being opened, this usually is for opens that creates a file.
:param share_access: (ShareAccess) Specifies the sharing mode for the
open.
:param create_disposition: (CreateDisposition) Defines the action the
server MUST take if the file already exists.
:param create_options: (CreateOptions) Specifies the options to be
applied when creating or opening the file.
:param create_contexts: (List<SMB2CreateContextRequest>) List of
context request values to be applied to the create.
Create Contexts are used to encode additional flags and attributes when
opening files. More details on create context request values can be
found here https://msdn.microsoft.com/en-us/library/cc246504.aspx.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: List of context response values or None if there are no
context response values. If the context response value is not known
to smbprotocol then the list value would be raw bytes otherwise
it is a Structure defined in create_contexts.py
"""
create = SMB2CreateRequest()
create['impersonation_level'] = impersonation_level
create['desired_access'] = desired_access
create['file_attributes'] = file_attributes
create['share_access'] = share_access
create['create_disposition'] = create_disposition
create['create_options'] = create_options
if self.file_name == "":
create['buffer_path'] = b"\x00\x00"
else:
create['buffer_path'] = self.file_name.encode('utf-16-le')
if create_contexts:
create['buffer_contexts'] = smbprotocol.create_contexts.\
SMB2CreateContextRequest.pack_multiple(create_contexts)
if self.connection.dialect >= Dialects.SMB_3_0_0:
self.desired_access = desired_access
self.share_mode = share_access
self.create_options = create_options
self.file_attributes = file_attributes
self.create_disposition = create_disposition
if not send:
return create, self._create_response
log.info("Session: %s, Tree Connect: %s - sending SMB2 Create Request "
"for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(create))
request = self.connection.send(create,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._create_response(request) | This will open the file based on the input parameters supplied. Any
file open should also be called with Open.close() when it is finished.
More details on how each option affects the open process can be found
here https://msdn.microsoft.com/en-us/library/cc246502.aspx.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2CreateRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param impersonation_level: (ImpersonationLevel) The type of
impersonation level that is issuing the create request.
:param desired_access: The level of access that is required of the
open. FilePipePrinterAccessMask or DirectoryAccessMask should be
used depending on the type of file being opened.
:param file_attributes: (FileAttributes) attributes to set on the file
being opened, this usually is for opens that creates a file.
:param share_access: (ShareAccess) Specifies the sharing mode for the
open.
:param create_disposition: (CreateDisposition) Defines the action the
server MUST take if the file already exists.
:param create_options: (CreateOptions) Specifies the options to be
applied when creating or opening the file.
:param create_contexts: (List<SMB2CreateContextRequest>) List of
context request values to be applied to the create.
Create Contexts are used to encode additional flags and attributes when
opening files. More details on create context request values can be
found here https://msdn.microsoft.com/en-us/library/cc246504.aspx.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: List of context response values or None if there are no
context response values. If the context response value is not known
to smbprotocol then the list value would be raw bytes otherwise
it is a Structure defined in create_contexts.py | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/open.py#L934-L1012 |
jborean93/smbprotocol | smbprotocol/open.py | Open.read | def read(self, offset, length, min_length=0, unbuffered=False, wait=True,
send=True):
"""
Reads from an opened file or pipe
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2ReadRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param offset: The offset to start the read of the file.
:param length: The number of bytes to read from the offset.
:param min_length: The minimum number of bytes to be read for a
successful operation.
:param unbuffered: Whether to the server should cache the read data at
intermediate layers, only value for SMB 3.0.2 or newer
:param wait: If send=True, whether to wait for a response if
STATUS_PENDING was received from the server or fail.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: A byte string of the bytes read
"""
if length > self.connection.max_read_size:
raise SMBException("The requested read length %d is greater than "
"the maximum negotiated read size %d"
% (length, self.connection.max_read_size))
read = SMB2ReadRequest()
read['length'] = length
read['offset'] = offset
read['minimum_count'] = min_length
read['file_id'] = self.file_id
read['padding'] = b"\x50"
if unbuffered:
if self.connection.dialect < Dialects.SMB_3_0_2:
raise SMBUnsupportedFeature(self.connection.dialect,
Dialects.SMB_3_0_2,
"SMB2_READFLAG_READ_UNBUFFERED",
True)
read['flags'].set_flag(ReadFlags.SMB2_READFLAG_READ_UNBUFFERED)
if not send:
return read, self._read_response
log.info("Session: %s, Tree Connect ID: %s - sending SMB2 Read "
"Request for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(read))
request = self.connection.send(read,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._read_response(request, wait) | python | def read(self, offset, length, min_length=0, unbuffered=False, wait=True,
send=True):
"""
Reads from an opened file or pipe
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2ReadRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param offset: The offset to start the read of the file.
:param length: The number of bytes to read from the offset.
:param min_length: The minimum number of bytes to be read for a
successful operation.
:param unbuffered: Whether to the server should cache the read data at
intermediate layers, only value for SMB 3.0.2 or newer
:param wait: If send=True, whether to wait for a response if
STATUS_PENDING was received from the server or fail.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: A byte string of the bytes read
"""
if length > self.connection.max_read_size:
raise SMBException("The requested read length %d is greater than "
"the maximum negotiated read size %d"
% (length, self.connection.max_read_size))
read = SMB2ReadRequest()
read['length'] = length
read['offset'] = offset
read['minimum_count'] = min_length
read['file_id'] = self.file_id
read['padding'] = b"\x50"
if unbuffered:
if self.connection.dialect < Dialects.SMB_3_0_2:
raise SMBUnsupportedFeature(self.connection.dialect,
Dialects.SMB_3_0_2,
"SMB2_READFLAG_READ_UNBUFFERED",
True)
read['flags'].set_flag(ReadFlags.SMB2_READFLAG_READ_UNBUFFERED)
if not send:
return read, self._read_response
log.info("Session: %s, Tree Connect ID: %s - sending SMB2 Read "
"Request for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(read))
request = self.connection.send(read,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._read_response(request, wait) | Reads from an opened file or pipe
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2ReadRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param offset: The offset to start the read of the file.
:param length: The number of bytes to read from the offset.
:param min_length: The minimum number of bytes to be read for a
successful operation.
:param unbuffered: Whether to the server should cache the read data at
intermediate layers, only value for SMB 3.0.2 or newer
:param wait: If send=True, whether to wait for a response if
STATUS_PENDING was received from the server or fail.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: A byte string of the bytes read | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/open.py#L1047-L1101 |
jborean93/smbprotocol | smbprotocol/open.py | Open.write | def write(self, data, offset=0, write_through=False, unbuffered=False,
wait=True, send=True):
"""
Writes data to an opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMBWriteRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param data: The bytes data to write.
:param offset: The offset in the file to write the bytes at
:param write_through: Whether written data is persisted to the
underlying storage, not valid for SMB 2.0.2.
:param unbuffered: Whether to the server should cache the write data at
intermediate layers, only value for SMB 3.0.2 or newer
:param wait: If send=True, whether to wait for a response if
STATUS_PENDING was received from the server or fail.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: The number of bytes written
"""
data_len = len(data)
if data_len > self.connection.max_write_size:
raise SMBException("The requested write length %d is greater than "
"the maximum negotiated write size %d"
% (data_len, self.connection.max_write_size))
write = SMB2WriteRequest()
write['length'] = len(data)
write['offset'] = offset
write['file_id'] = self.file_id
write['buffer'] = data
if write_through:
if self.connection.dialect < Dialects.SMB_2_1_0:
raise SMBUnsupportedFeature(self.connection.dialect,
Dialects.SMB_2_1_0,
"SMB2_WRITEFLAG_WRITE_THROUGH",
True)
write['flags'].set_flag(WriteFlags.SMB2_WRITEFLAG_WRITE_THROUGH)
if unbuffered:
if self.connection.dialect < Dialects.SMB_3_0_2:
raise SMBUnsupportedFeature(self.connection.dialect,
Dialects.SMB_3_0_2,
"SMB2_WRITEFLAG_WRITE_UNBUFFERED",
True)
write['flags'].set_flag(WriteFlags.SMB2_WRITEFLAG_WRITE_UNBUFFERED)
if not send:
return write, self._write_response
log.info("Session: %s, Tree Connect: %s - sending SMB2 Write Request "
"for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(write))
request = self.connection.send(write,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._write_response(request, wait) | python | def write(self, data, offset=0, write_through=False, unbuffered=False,
wait=True, send=True):
"""
Writes data to an opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMBWriteRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param data: The bytes data to write.
:param offset: The offset in the file to write the bytes at
:param write_through: Whether written data is persisted to the
underlying storage, not valid for SMB 2.0.2.
:param unbuffered: Whether to the server should cache the write data at
intermediate layers, only value for SMB 3.0.2 or newer
:param wait: If send=True, whether to wait for a response if
STATUS_PENDING was received from the server or fail.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: The number of bytes written
"""
data_len = len(data)
if data_len > self.connection.max_write_size:
raise SMBException("The requested write length %d is greater than "
"the maximum negotiated write size %d"
% (data_len, self.connection.max_write_size))
write = SMB2WriteRequest()
write['length'] = len(data)
write['offset'] = offset
write['file_id'] = self.file_id
write['buffer'] = data
if write_through:
if self.connection.dialect < Dialects.SMB_2_1_0:
raise SMBUnsupportedFeature(self.connection.dialect,
Dialects.SMB_2_1_0,
"SMB2_WRITEFLAG_WRITE_THROUGH",
True)
write['flags'].set_flag(WriteFlags.SMB2_WRITEFLAG_WRITE_THROUGH)
if unbuffered:
if self.connection.dialect < Dialects.SMB_3_0_2:
raise SMBUnsupportedFeature(self.connection.dialect,
Dialects.SMB_3_0_2,
"SMB2_WRITEFLAG_WRITE_UNBUFFERED",
True)
write['flags'].set_flag(WriteFlags.SMB2_WRITEFLAG_WRITE_UNBUFFERED)
if not send:
return write, self._write_response
log.info("Session: %s, Tree Connect: %s - sending SMB2 Write Request "
"for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(write))
request = self.connection.send(write,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._write_response(request, wait) | Writes data to an opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMBWriteRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param data: The bytes data to write.
:param offset: The offset in the file to write the bytes at
:param write_through: Whether written data is persisted to the
underlying storage, not valid for SMB 2.0.2.
:param unbuffered: Whether to the server should cache the write data at
intermediate layers, only value for SMB 3.0.2 or newer
:param wait: If send=True, whether to wait for a response if
STATUS_PENDING was received from the server or fail.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: The number of bytes written | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/open.py#L1114-L1176 |
jborean93/smbprotocol | smbprotocol/open.py | Open.flush | def flush(self, send=True):
"""
A command sent by the client to request that a server flush all cached
file information for the opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2FlushRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: The SMB2FlushResponse received from the server
"""
flush = SMB2FlushRequest()
flush['file_id'] = self.file_id
if not send:
return flush, self._flush_response
log.info("Session: %s, Tree Connect: %s - sending SMB2 Flush Request "
"for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(flush))
request = self.connection.send(flush,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._flush_response(request) | python | def flush(self, send=True):
"""
A command sent by the client to request that a server flush all cached
file information for the opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2FlushRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: The SMB2FlushResponse received from the server
"""
flush = SMB2FlushRequest()
flush['file_id'] = self.file_id
if not send:
return flush, self._flush_response
log.info("Session: %s, Tree Connect: %s - sending SMB2 Flush Request "
"for file %s" % (self.tree_connect.session.username,
self.tree_connect.share_name,
self.file_name))
log.debug(str(flush))
request = self.connection.send(flush,
self.tree_connect.session.session_id,
self.tree_connect.tree_connect_id)
return self._flush_response(request) | A command sent by the client to request that a server flush all cached
file information for the opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2FlushRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passing in the
Request that was used to sent it out of band.
:param send: Whether to send the request in the same call or return the
message to the caller and the unpack function
:return: The SMB2FlushResponse received from the server | https://github.com/jborean93/smbprotocol/blob/d8eb00fbc824f97d0f4946e3f768c5e6c723499a/smbprotocol/open.py#L1189-L1218 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.