Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _getNextArticleBatch(self):
eventUri = self.queryParams["eventUri"]
# move to the next page to download
self._articlePage += 1
# if we have already obtained all pages, then exit
if self._totalPages != None and self._articl... | [
"download next batch of events based on the event uris in the uri list"
] |
Please provide a description of the function:def initWithArticleUriList(uriList):
q = QueryArticles()
assert isinstance(uriList, list), "uriList has to be a list of strings that represent article uris"
q.queryParams = { "action": "getArticles", "articleUri": uriList }
return q | [
"\n instead of making a query, provide a list of article URIs manually, and then produce the desired results on top of them\n "
] |
Please provide a description of the function:def initWithArticleUriWgtList(uriWgtList):
q = QueryArticles()
assert isinstance(uriWgtList, list), "uriList has to be a list of strings that represent article uris"
q.queryParams = { "action": "getArticles", "articleUriWgtList": ",".join(uri... | [
"\n instead of making a query, provide a list of article URIs manually, and then produce the desired results on top of them\n "
] |
Please provide a description of the function:def initWithComplexQuery(query):
q = QueryArticles()
# provided an instance of ComplexArticleQuery
if isinstance(query, ComplexArticleQuery):
q._setVal("query", json.dumps(query.getQuery()))
# provided query as a string co... | [
"\n create a query using a complex article query\n "
] |
Please provide a description of the function:def initWithArticleUriList(uriList):
q = QueryArticlesIter()
assert isinstance(uriList, list), "uriList has to be a list of strings that represent article uris"
q.queryParams = { "action": "getArticles", "articleUri": uriList }
return... | [
"\n instead of making a query, provide a list of article URIs manually, and then produce the desired results on top of them\n "
] |
Please provide a description of the function:def _getNextArticleBatch(self):
# try to get more uris, if none
self._articlePage += 1
# if we have already obtained all pages, then exit
if self._totalPages != None and self._articlePage > self._totalPages:
return
... | [
"download next batch of articles based on the article uris in the uri list"
] |
Please provide a description of the function:def initWithEventUriList(uriList):
q = QueryEvents()
assert isinstance(uriList, list), "uriList has to be a list of strings that represent event uris"
q.queryParams = { "action": "getEvents", "eventUriList": ",".join(uriList) }
return... | [
"\n Set a custom list of event uris. The results will be then computed on this list - no query will be done (all conditions will be ignored).\n "
] |
Please provide a description of the function:def initWithEventUriWgtList(uriWgtList):
q = QueryEvents()
assert isinstance(uriWgtList, list), "uriWgtList has to be a list of strings that represent event uris with their weights"
q.queryParams = { "action": "getEvents", "eventUriWgtList": ... | [
"\n Set a custom list of event uris. The results will be then computed on this list - no query will be done (all conditions will be ignored).\n "
] |
Please provide a description of the function:def initWithComplexQuery(query):
q = QueryEvents()
# provided an instance of ComplexEventQuery
if isinstance(query, ComplexEventQuery):
q._setVal("query", json.dumps(query.getQuery()))
# provided query as a string containi... | [
"\n create a query using a complex event query\n "
] |
Please provide a description of the function:def count(self, eventRegistry):
self.setRequestedResult(RequestEventsInfo())
res = eventRegistry.execQuery(self)
if "error" in res:
print(res["error"])
count = res.get("events", {}).get("totalResults", 0)
return co... | [
"\n return the number of events that match the criteria\n "
] |
Please provide a description of the function:def _getNextEventBatch(self):
self._eventPage += 1
# if we have already obtained all pages, then exit
if self._totalPages != None and self._eventPage > self._totalPages:
return
self.setRequestedResult(RequestEventsInfo(pag... | [
"download next batch of events based on the event uris in the uri list"
] |
Please provide a description of the function:def _setFlag(self, name, val, defVal):
if not hasattr(self, "flags"):
self.flags = {}
if val != defVal:
self.flags[name] = val | [
"set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal"
] |
Please provide a description of the function:def _setVal(self, name, val, defVal = None):
if val == defVal:
return
if not hasattr(self, "vals"):
self.vals = {}
self.vals[name] = val | [
"set value of name to val in case the val != defVal"
] |
Please provide a description of the function:def _getVals(self, prefix = ""):
if not hasattr(self, "vals"):
self.vals = {}
dict = {}
for key in list(self.vals.keys()):
# if no prefix then lower the first letter
if prefix == "":
newkey ... | [
"\n return the values in the vals dict\n in case prefix is \"\", change the first letter of the name to lowercase, otherwise use prefix+name as the new name\n "
] |
Please provide a description of the function:def loadFromFile(fileName):
assert os.path.exists(fileName), "File " + fileName + " does not exist"
conf = json.load(open(fileName))
return ReturnInfo(
articleInfo=ArticleInfoFlags(**conf.get("articleInfo", {})),
event... | [
"\n load the configuration for the ReturnInfo from a fileName\n @param fileName: filename that contains the json configuration to use in the ReturnInfo\n "
] |
Please provide a description of the function:def getConf(self):
conf = {
"articleInfo": self.articleInfo._getFlags().copy(),
"eventInfo": self.eventInfo._getFlags().copy(),
"sourceInfo": self.sourceInfo._getFlags().copy(),
"categoryInfo": self.categoryIn... | [
"\n return configuration in a json object that stores properties set by each *InfoFlags class\n "
] |
Please provide a description of the function:def loadTopicPageFromER(self, uri):
params = {
"action": "getTopicPageJson",
"includeConceptDescription": True,
"includeTopicPageDefinition": True,
"includeTopicPageOwner": True,
"uri": uri
... | [
"\n load an existing topic page from Event Registry based on the topic page URI\n @param uri: uri of the topic page saved in your Event Registry account\n "
] |
Please provide a description of the function:def loadTopicPageFromFile(self, fname):
assert os.path.exists(fname)
f = open(fname, "r", encoding="utf-8")
self.topicPage = json.load(f) | [
"\n load topic page from an existing file\n "
] |
Please provide a description of the function:def saveTopicPageDefinitionToFile(self, fname):
open(fname, "w", encoding="utf-8").write(json.dumps(self.topicPage, indent = 4, sort_keys = True)) | [
"\n save the topic page definition to a file\n "
] |
Please provide a description of the function:def setArticleThreshold(self, value):
assert isinstance(value, int)
assert value >= 0
self.topicPage["articleTreshWgt"] = value | [
"\n what is the minimum total weight that an article has to have in order to get it among the results?\n @param value: threshold to use\n "
] |
Please provide a description of the function:def setEventThreshold(self, value):
assert isinstance(value, int)
assert value >= 0
self.topicPage["eventTreshWgt"] = value | [
"\n what is the minimum total weight that an event has to have in order to get it among the results?\n @param value: threshold to use\n "
] |
Please provide a description of the function:def setMaxDaysBack(self, maxDaysBack):
assert isinstance(maxDaysBack, int), "maxDaysBack value has to be a positive integer"
assert maxDaysBack >= 1
self.topicPage["maxDaysBack"] = maxDaysBack | [
"\n what is the maximum allowed age of the results?\n "
] |
Please provide a description of the function:def addConcept(self, conceptUri, weight, label = None, conceptType = None):
assert isinstance(weight, (float, int)), "weight value has to be a positive or negative integer"
concept = {"uri": conceptUri, "wgt": weight}
if label != None: concep... | [
"\n add a relevant concept to the topic page\n @param conceptUri: uri of the concept to be added\n @param weight: importance of the provided concept (typically in range 1 - 50)\n "
] |
Please provide a description of the function:def addKeyword(self, keyword, weight):
assert isinstance(weight, (float, int)), "weight value has to be a positive or negative integer"
self.topicPage["keywords"].append({"keyword": keyword, "wgt": weight}) | [
"\n add a relevant keyword to the topic page\n @param keyword: keyword or phrase to be added\n @param weight: importance of the provided keyword (typically in range 1 - 50)\n "
] |
Please provide a description of the function:def addCategory(self, categoryUri, weight):
assert isinstance(weight, (float, int)), "weight value has to be a positive or negative integer"
self.topicPage["categories"].append({"uri": categoryUri, "wgt": weight}) | [
"\n add a relevant category to the topic page\n @param categoryUri: uri of the category to be added\n @param weight: importance of the provided category (typically in range 1 - 50)\n "
] |
Please provide a description of the function:def addSource(self, sourceUri, weight):
assert isinstance(weight, (float, int)), "weight value has to be a positive or negative integer"
self.topicPage["sources"].append({"uri": sourceUri, "wgt": weight}) | [
"\n add a news source to the topic page\n @param sourceUri: uri of the news source to add to the topic page\n @param weight: importance of the news source (typically in range 1 - 50)\n "
] |
Please provide a description of the function:def addSourceLocation(self, sourceLocationUri, weight):
assert isinstance(weight, (float, int)), "weight value has to be a positive or negative integer"
self.topicPage["sourceLocations"].append({"uri": sourceLocationUri, "wgt": weight}) | [
"\n add a list of relevant sources by identifying them by their geographic location\n @param sourceLocationUri: uri of the location where the sources should be geographically located\n @param weight: importance of the provided list of sources (typically in range 1 - 50)\n "
] |
Please provide a description of the function:def addSourceGroup(self, sourceGroupUri, weight):
assert isinstance(weight, (float, int)), "weight value has to be a positive or negative integer"
self.topicPage["sourceGroups"].append({"uri": sourceGroupUri, "wgt": weight}) | [
"\n add a list of relevant sources by specifying a whole source group to the topic page\n @param sourceGroupUri: uri of the source group to add\n @param weight: importance of the provided list of sources (typically in range 1 - 50)\n "
] |
Please provide a description of the function:def addLocation(self, locationUri, weight):
assert isinstance(weight, (float, int)), "weight value has to be a positive or negative integer"
self.topicPage["locations"].append({"uri": locationUri, "wgt": weight}) | [
"\n add relevant location to the topic page\n @param locationUri: uri of the location to add\n @param weight: importance of the provided location (typically in range 1 - 50)\n "
] |
Please provide a description of the function:def setLanguages(self, languages):
if isinstance(languages, six.string_types):
languages = [languages]
for lang in languages:
assert len(lang) == 3, "Expected to get language in ISO3 code"
self.topicPage["langs"] = lan... | [
"\n restrict the results to the list of specified languages\n "
] |
Please provide a description of the function:def getArticles(self,
page=1,
count=100,
sortBy = "rel",
sortByAsc = False,
returnInfo=ReturnInfo()):
assert page >= 1
assert count <= 100
params = {
... | [
"\n return a list of articles that match the topic page\n @param page: which page of the results to return (default: 1)\n @param count: number of articles to return (default: 100)\n @param sortBy: how are articles sorted. Options: id (internal id), date (publishing date), cosSim (closene... |
Please provide a description of the function:def AND(queryArr,
exclude = None):
assert isinstance(queryArr, list), "provided argument as not a list"
assert len(queryArr) > 0, "queryArr had an empty list"
q = CombinedQuery()
q.setQueryParam("$and", [])
for ite... | [
"\n create a combined query with multiple items on which to perform an AND operation\n @param queryArr: a list of items on which to perform an AND operation. Items can be either a CombinedQuery or BaseQuery instances.\n @param exclude: a instance of BaseQuery, CombinedQuery or None. Used to fil... |
Please provide a description of the function:async def start_pairing(self):
self.srp.initialize()
msg = messages.crypto_pairing({
tlv8.TLV_METHOD: b'\x00',
tlv8.TLV_SEQ_NO: b'\x01'})
resp = await self.protocol.send_and_receive(
msg, generate_identifi... | [
"Start pairing procedure."
] |
Please provide a description of the function:async def finish_pairing(self, pin):
self.srp.step1(pin)
pub_key, proof = self.srp.step2(self._atv_pub_key, self._atv_salt)
msg = messages.crypto_pairing({
tlv8.TLV_SEQ_NO: b'\x03',
tlv8.TLV_PUBLIC_KEY: pub_key,
... | [
"Finish pairing process."
] |
Please provide a description of the function:async def verify_credentials(self):
_, public_key = self.srp.initialize()
msg = messages.crypto_pairing({
tlv8.TLV_SEQ_NO: b'\x01',
tlv8.TLV_PUBLIC_KEY: public_key})
resp = await self.protocol.send_and_receive(
... | [
"Verify credentials with device."
] |
Please provide a description of the function:def lookup_tag(name):
return next((_TAGS[t] for t in _TAGS if t == name),
DmapTag(_read_unknown, 'unknown tag')) | [
"Look up a tag based on its key. Returns a DmapTag."
] |
Please provide a description of the function:async def scan_for_apple_tvs(loop, timeout=5, abort_on_found=False,
device_ip=None, only_usable=True,
protocol=None):
semaphore = asyncio.Semaphore(value=0, loop=loop)
listener = _ServiceListener(
... | [
"Scan for Apple TVs using zeroconf (bonjour) and returns them."
] |
Please provide a description of the function:def connect_to_apple_tv(details, loop, protocol=None, session=None):
service = _get_service_used_to_connect(details, protocol)
# If no session is given, create a default one
if session is None:
session = ClientSession(loop=loop)
# AirPlay servi... | [
"Connect and logins to an Apple TV."
] |
Please provide a description of the function:def add_service(self, zeroconf, service_type, name):
self.lock.acquire()
try:
self._internal_add(zeroconf, service_type, name)
finally:
self.lock.release() | [
"Handle callback from zeroconf when a service has been discovered."
] |
Please provide a description of the function:def add_hs_service(self, info, address):
if self.protocol and self.protocol != PROTOCOL_DMAP:
return
name = info.properties[b'Name'].decode('utf-8')
hsgid = info.properties[b'hG'].decode('utf-8')
self._handle_service(
... | [
"Add a new device to discovered list."
] |
Please provide a description of the function:def add_non_hs_service(self, info, address):
if self.protocol and self.protocol != PROTOCOL_DMAP:
return
name = info.properties[b'CtlN'].decode('utf-8')
self._handle_service(
address, name, conf.DmapService(None, port... | [
"Add a new device without Home Sharing to discovered list."
] |
Please provide a description of the function:def add_mrp_service(self, info, address):
if self.protocol and self.protocol != PROTOCOL_MRP:
return
name = info.properties[b'Name'].decode('utf-8')
self._handle_service(address, name, conf.MrpService(info.port)) | [
"Add a new MediaRemoteProtocol device to discovered list."
] |
Please provide a description of the function:def add_airplay_service(self, info, address):
name = info.name.replace('._airplay._tcp.local.', '')
self._handle_service(address, name, conf.AirPlayService(info.port)) | [
"Add a new AirPlay device to discovered list."
] |
Please provide a description of the function:def add_service(self, service):
if service.protocol in self._services:
existing = self._services[service.protocol]
if not existing.superseeded_by(service):
return
self._services[service.protocol] = service | [
"Add a new service.\n\n If the service already exists, it will be replaced.\n "
] |
Please provide a description of the function:def usable_service(self):
services = self._services
for protocol in self._supported_protocols:
if protocol in services and services[protocol].is_usable():
return services[protocol]
return None | [
"Return a usable service or None if there is none.\n\n A service is usable if enough configuration to be able to make a\n connection is available. If several protocols are usable, MRP will be\n preferred over DMAP.\n "
] |
Please provide a description of the function:def superseeded_by(self, other_service):
if not other_service or \
other_service.__class__ != self.__class__ or \
other_service.protocol != self.protocol or \
other_service.port != self.port:
return... | [
"Return True if input service has login id and this has not."
] |
Please provide a description of the function:async def print_what_is_playing(loop):
print('Discovering devices on network...')
atvs = await pyatv.scan_for_apple_tvs(loop, timeout=5)
if not atvs:
print('no device found', file=sys.stderr)
return
print('Connecting to {0}'.format(atvs... | [
"Find a device and print what is playing."
] |
Please provide a description of the function:async def start(self, **kwargs):
zeroconf = kwargs['zeroconf']
self._name = kwargs['name']
self._pairing_guid = kwargs.get('pairing_guid', None) or \
self._generate_random_guid()
self._web_server = web.Server(self.handle_... | [
"Start the pairing server and publish service."
] |
Please provide a description of the function:async def stop(self, **kwargs):
_LOGGER.debug('Shutting down pairing server')
if self._web_server is not None:
await self._web_server.shutdown()
self._server.close()
if self._server is not None:
await self... | [
"Stop pairing server and unpublish service."
] |
Please provide a description of the function:async def handle_request(self, request):
service_name = request.rel_url.query['servicename']
received_code = request.rel_url.query['pairingcode'].lower()
_LOGGER.info('Got pairing request from %s with code %s',
service_na... | [
"Respond to request if PIN is correct."
] |
Please provide a description of the function:def log_binary(logger, message, **kwargs):
if logger.isEnabledFor(logging.DEBUG):
output = ('{0}={1}'.format(k, binascii.hexlify(
bytearray(v)).decode()) for k, v in sorted(kwargs.items()))
logger.debug('%s (%s)', message, ', '.join(outpu... | [
"Log binary data if debug is enabled."
] |
Please provide a description of the function:async def cli_handler(loop):
parser = argparse.ArgumentParser()
parser.add_argument('command', nargs='+',
help='commands, help, ...')
parser.add_argument('--name', help='apple tv name',
dest='name', default='A... | [
"Application starts here."
] |
Please provide a description of the function:def _extract_command_with_args(cmd):
def _isint(value):
try:
int(value)
return True
except ValueError:
return False
equal_sign = cmd.find('=')
if equal_sign == -1:
return cmd, []
command = cmd... | [
"Parse input command with arguments.\n\n Parses the input command in such a way that the user may\n provide additional argument to the command. The format used is this:\n command=arg1,arg2,arg3,...\n all the additional arguments are passed as arguments to the target\n method.\n "
] |
Please provide a description of the function:def main():
# Helper method so that the coroutine exits cleanly if an exception
# happens (which would leave resources dangling)
async def _run_application(loop):
try:
return await cli_handler(loop)
except KeyboardInterrupt:
... | [
"Start the asyncio event loop and runs the application."
] |
Please provide a description of the function:async def commands(self):
_print_commands('Remote control', interface.RemoteControl)
_print_commands('Metadata', interface.Metadata)
_print_commands('Playing', interface.Playing)
_print_commands('AirPlay', interface.AirPlay)
_... | [
"Print a list with available commands."
] |
Please provide a description of the function:async def help(self):
if len(self.args.command) != 2:
print('Which command do you want help with?', file=sys.stderr)
return 1
iface = [interface.RemoteControl,
interface.Metadata,
interface.P... | [
"Print help text for a command."
] |
Please provide a description of the function:async def scan(self):
atvs = await pyatv.scan_for_apple_tvs(
self.loop, timeout=self.args.scan_timeout, only_usable=False)
_print_found_apple_tvs(atvs)
return 0 | [
"Scan for Apple TVs on the network."
] |
Please provide a description of the function:async def cli(self):
print('Enter commands and press enter')
print('Type help for help and exit to quit')
while True:
command = await _read_input(self.loop, 'pyatv> ')
if command.lower() == 'exit':
bre... | [
"Enter commands in a simple CLI."
] |
Please provide a description of the function:async def artwork_save(self):
artwork = await self.atv.metadata.artwork()
if artwork is not None:
with open('artwork.png', 'wb') as file:
file.write(artwork)
else:
print('No artwork is currently availab... | [
"Download artwork and save it to artwork.png."
] |
Please provide a description of the function:async def push_updates(self):
print('Press ENTER to stop')
self.atv.push_updater.start()
await self.atv.login()
await self.loop.run_in_executor(None, sys.stdin.readline)
self.atv.push_updater.stop()
return 0 | [
"Listen for push updates."
] |
Please provide a description of the function:async def auth(self):
credentials = await self.atv.airplay.generate_credentials()
await self.atv.airplay.load_credentials(credentials)
try:
await self.atv.airplay.start_authentication()
pin = await _read_input(self.lo... | [
"Perform AirPlay device authentication."
] |
Please provide a description of the function:async def pair(self):
# Connect using the specified protocol
# TODO: config should be stored elsewhere so that API is same for both
protocol = self.atv.service.protocol
if protocol == const.PROTOCOL_DMAP:
await self.atv.pa... | [
"Pair pyatv as a remote control with an Apple TV."
] |
Please provide a description of the function:def media_kind(kind):
if kind in [1]:
return const.MEDIA_TYPE_UNKNOWN
if kind in [3, 7, 11, 12, 13, 18, 32]:
return const.MEDIA_TYPE_VIDEO
if kind in [2, 4, 10, 14, 17, 21, 36]:
return const.MEDIA_TYPE_MUSIC
if kind in [8, 64]:
... | [
"Convert iTunes media kind to API representation."
] |
Please provide a description of the function:def media_type_str(mediatype):
if mediatype == const.MEDIA_TYPE_UNKNOWN:
return 'Unknown'
if mediatype == const.MEDIA_TYPE_VIDEO:
return 'Video'
if mediatype == const.MEDIA_TYPE_MUSIC:
return 'Music'
if mediatype == const.MEDIA_TY... | [
"Convert internal API media type to string."
] |
Please provide a description of the function:def playstate(state):
# pylint: disable=too-many-return-statements
if state is None:
return const.PLAY_STATE_NO_MEDIA
if state == 0:
return const.PLAY_STATE_IDLE
if state == 1:
return const.PLAY_STATE_LOADING
if state == 3:
... | [
"Convert iTunes playstate to API representation."
] |
Please provide a description of the function:def playstate_str(state):
if state == const.PLAY_STATE_NO_MEDIA:
return 'No media'
if state == const.PLAY_STATE_IDLE:
return 'Idle'
if state == const.PLAY_STATE_LOADING:
return 'Loading'
if state == const.PLAY_STATE_PAUSED:
... | [
"Convert internal API playstate to string."
] |
Please provide a description of the function:def repeat_str(state):
if state == const.REPEAT_STATE_OFF:
return 'Off'
if state == const.REPEAT_STATE_TRACK:
return 'Track'
if state == const.REPEAT_STATE_ALL:
return 'All'
return 'Unsupported' | [
"Convert internal API repeat state to string."
] |
Please provide a description of the function:def protocol_str(protocol):
if protocol == const.PROTOCOL_MRP:
return 'MRP'
if protocol == const.PROTOCOL_DMAP:
return 'DMAP'
if protocol == const.PROTOCOL_AIRPLAY:
return 'AirPlay'
return 'Unknown' | [
"Convert internal API protocol to string."
] |
Please provide a description of the function:def first(dmap_data, *path):
if not (path and isinstance(dmap_data, list)):
return dmap_data
for key in dmap_data:
if path[0] in key:
return first(key[path[0]], *path[1:])
return None | [
"Look up a value given a path in some parsed DMAP data."
] |
Please provide a description of the function:def pprint(data, tag_lookup, indent=0):
output = ''
if isinstance(data, dict):
for key, value in data.items():
tag = tag_lookup(key)
if isinstance(value, (dict, list)) and tag.type is not read_bplist:
output += '{0... | [
"Return a pretty formatted string of parsed DMAP data."
] |
Please provide a description of the function:def retrieve_commands(obj):
commands = {} # Name and help
for func in obj.__dict__:
if not inspect.isfunction(obj.__dict__[func]) and \
not isinstance(obj.__dict__[func], property):
continue
if func.startswith('_'):
... | [
"Retrieve all commands and help texts from an API object."
] |
Please provide a description of the function:def hash(self):
base = '{0}{1}{2}{3}'.format(
self.title, self.artist, self.album, self.total_time)
return hashlib.sha256(base.encode('utf-8')).hexdigest() | [
"Create a unique hash for what is currently playing.\n\n The hash is based on title, artist, album and total time. It should\n always be the same for the same content, but it is not guaranteed.\n "
] |
Please provide a description of the function:async def play_url(self, url, position=0):
headers = {'User-Agent': 'MediaControl/1.0',
'Content-Type': 'application/x-apple-binary-plist'}
body = {'Content-Location': url, 'Start-Position': position}
address = self._url(s... | [
"Play media from an URL on the device."
] |
Please provide a description of the function:def extract_message_info():
base_path = BASE_PACKAGE.replace('.', '/')
filename = os.path.join(base_path, 'ProtocolMessage.proto')
with open(filename, 'r') as file:
types_found = False
for line in file:
stripped = line.lstrip().... | [
"Get information about all messages of interest."
] |
Please provide a description of the function:def main():
message_names = set()
packages = []
messages = []
extensions = []
constants = []
# Extract everything needed to generate output file
for info in extract_message_info():
message_names.add(info.title)
packages.appen... | [
"Script starts somewhere around here."
] |
Please provide a description of the function:def hkdf_expand(salt, info, shared_secret):
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.backends import default_backend
hkdf = HKDF(
algorithm=hashes.SHA512()... | [
"Derive encryption keys from shared secret."
] |
Please provide a description of the function:def parse(cls, detail_string):
split = detail_string.split(':')
if len(split) != 4:
raise Exception('invalid credentials') # TODO: other exception
ltpk = binascii.unhexlify(split[0])
ltsk = binascii.unhexlify(split[1])
... | [
"Parse a string represention of Credentials."
] |
Please provide a description of the function:def initialize(self):
self._signing_key = SigningKey(os.urandom(32))
self._auth_private = self._signing_key.to_seed()
self._auth_public = self._signing_key.get_verifying_key().to_bytes()
self._verify_private = curve25519.Private(secre... | [
"Initialize operation by generating new keys."
] |
Please provide a description of the function:def verify1(self, credentials, session_pub_key, encrypted):
# No additional hashing used
self._shared = self._verify_private.get_shared_key(
curve25519.Public(session_pub_key), hashfunc=lambda x: x)
session_key = hkdf_expand('Pai... | [
"First verification step."
] |
Please provide a description of the function:def verify2(self):
output_key = hkdf_expand('MediaRemote-Salt',
'MediaRemote-Write-Encryption-Key',
self._shared)
input_key = hkdf_expand('MediaRemote-Salt',
... | [
"Last verification step.\n\n The derived keys (output, input) are returned here.\n "
] |
Please provide a description of the function:def step1(self, pin):
context = SRPContext(
'Pair-Setup', str(pin),
prime=constants.PRIME_3072,
generator=constants.PRIME_3072_GEN,
hash_func=hashlib.sha512)
self._session = SRPClientSession(
... | [
"First pairing step."
] |
Please provide a description of the function:def step2(self, atv_pub_key, atv_salt):
pk_str = binascii.hexlify(atv_pub_key).decode()
salt = binascii.hexlify(atv_salt).decode()
self._client_session_key, _, _ = self._session.process(pk_str, salt)
if not self._session.verify_proof... | [
"Second pairing step."
] |
Please provide a description of the function:def step3(self):
ios_device_x = hkdf_expand(
'Pair-Setup-Controller-Sign-Salt',
'Pair-Setup-Controller-Sign-Info',
binascii.unhexlify(self._client_session_key))
self._session_key = hkdf_expand(
'Pair-S... | [
"Third pairing step."
] |
Please provide a description of the function:def step4(self, encrypted_data):
chacha = chacha20.Chacha20Cipher(self._session_key, self._session_key)
decrypted_tlv_bytes = chacha.decrypt(
encrypted_data, nounce='PS-Msg06'.encode())
if not decrypted_tlv_bytes:
rais... | [
"Last pairing step."
] |
Please provide a description of the function:def hash_sha512(*indata):
hasher = hashlib.sha512()
for data in indata:
if isinstance(data, str):
hasher.update(data.encode('utf-8'))
elif isinstance(data, bytes):
hasher.update(data)
else:
raise Except... | [
"Create SHA512 hash for input arguments."
] |
Please provide a description of the function:def aes_encrypt(mode, aes_key, aes_iv, *data):
encryptor = Cipher(
algorithms.AES(aes_key),
mode(aes_iv),
backend=default_backend()).encryptor()
result = None
for value in data:
result = encryptor.update(value)
encryptor.... | [
"Encrypt data with AES in specified mode."
] |
Please provide a description of the function:def new_credentials():
identifier = binascii.b2a_hex(os.urandom(8)).decode().upper()
seed = binascii.b2a_hex(os.urandom(32)) # Corresponds to private key
return identifier, seed | [
"Generate a new identifier and seed for authentication.\n\n Use the returned values in the following way:\n * The identifier shall be passed as username to SRPAuthHandler.step1\n * Seed shall be passed to SRPAuthHandler constructor\n "
] |
Please provide a description of the function:def get_common_session_key(self, premaster_secret):
k_1 = self.hash(premaster_secret, b'\x00\x00\x00\x00', as_bytes=True)
k_2 = self.hash(premaster_secret, b'\x00\x00\x00\x01', as_bytes=True)
return k_1 + k_2 | [
"K = H(S).\n\n Special implementation for Apple TV.\n "
] |
Please provide a description of the function:def initialize(self, seed=None):
self.seed = seed or os.urandom(32) # Generate new seed if not provided
signing_key = SigningKey(self.seed)
verifying_key = signing_key.get_verifying_key()
self._auth_private = signing_key.to_seed()
... | [
"Initialize handler operation.\n\n This method will generate new encryption keys and must be called prior\n to doing authentication or verification.\n "
] |
Please provide a description of the function:def verify1(self):
self._check_initialized()
self._verify_private = curve25519.Private(secret=self.seed)
self._verify_public = self._verify_private.get_public()
log_binary(_LOGGER,
'Verification keys',
... | [
"First device verification step."
] |
Please provide a description of the function:def verify2(self, atv_public_key, data):
self._check_initialized()
log_binary(_LOGGER, 'Verify', PublicSecret=atv_public_key, Data=data)
# Generate a shared secret key
public = curve25519.Public(atv_public_key)
shared = self.... | [
"Last device verification step."
] |
Please provide a description of the function:def step1(self, username, password):
self._check_initialized()
context = AtvSRPContext(
str(username), str(password),
prime=constants.PRIME_2048,
generator=constants.PRIME_2048_GEN)
self.session = SRPClient... | [
"First authentication step."
] |
Please provide a description of the function:def step2(self, pub_key, salt):
self._check_initialized()
pk_str = binascii.hexlify(pub_key).decode()
salt = binascii.hexlify(salt).decode()
self.client_session_key, _, _ = self.session.process(pk_str, salt)
_LOGGER.debug('Cli... | [
"Second authentication step."
] |
Please provide a description of the function:def step3(self):
self._check_initialized()
# TODO: verify: self.client_session_key same as self.session.key_b64()?
session_key = binascii.unhexlify(self.client_session_key)
aes_key = hash_sha512('Pair-Setup-AES-Key', session_key)[0:1... | [
"Last authentication step."
] |
Please provide a description of the function:async def start_authentication(self):
_, code = await self.http.post_data(
'pair-pin-start', headers=_AIRPLAY_HEADERS)
if code != 200:
raise DeviceAuthenticationError('pair start failed') | [
"Start the authentication process.\n\n This method will show the expected PIN on screen.\n "
] |
Please provide a description of the function:async def finish_authentication(self, username, password):
# Step 1
self.srp.step1(username, password)
data = await self._send_plist(
'step1', method='pin', user=username)
resp = plistlib.loads(data)
# Step 2
... | [
"Finish authentication process.\n\n A username (generated by new_credentials) and the PIN code shown on\n screen must be provided.\n "
] |
Please provide a description of the function:async def verify_authed(self):
resp = await self._send(self.srp.verify1(), 'verify1')
atv_public_secret = resp[0:32]
data = resp[32:] # TODO: what is this?
await self._send(
self.srp.verify2(atv_public_secret, data), 've... | [
"Verify if device is allowed to use AirPlau."
] |
Please provide a description of the function:async def generate_credentials(self):
identifier, seed = new_credentials()
return '{0}:{1}'.format(identifier, seed.decode().upper()) | [
"Create new credentials for authentication.\n\n Credentials that have been authenticated shall be saved and loaded with\n load_credentials before playing anything. If credentials are lost,\n authentication must be performed again.\n "
] |
Please provide a description of the function:async def load_credentials(self, credentials):
split = credentials.split(':')
self.identifier = split[0]
self.srp.initialize(binascii.unhexlify(split[1]))
_LOGGER.debug('Loaded AirPlay credentials: %s', credentials) | [
"Load existing credentials."
] |
Please provide a description of the function:async def play_url(self, url, **kwargs):
# If credentials have been loaded, do device verification first
if self.identifier:
await self.verify_authenticated()
position = 0 if 'position' not in kwargs else int(kwargs['position'])
... | [
"Play media from an URL on the device.\n\n Note: This method will not yield until the media has finished playing.\n The Apple TV requires the request to stay open during the entire\n play duration.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.