id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
15,300
|
EventRegistry/event-registry-python
|
eventregistry/TopicPage.py
|
TopicPage.getArticles
|
def getArticles(self,
page=1,
count=100,
sortBy = "rel",
sortByAsc = False,
returnInfo=ReturnInfo()):
"""
return a list of articles that match the topic page
@param page: which page of the results to return (default: 1)
@param count: number of articles to return (default: 100)
@param sortBy: how are articles sorted. Options: id (internal id), date (publishing date), cosSim (closeness to the event centroid), rel (relevance to the query), sourceImportance (manually curated score of source importance - high value, high importance), sourceImportanceRank (reverse of sourceImportance), sourceAlexaGlobalRank (global rank of the news source), sourceAlexaCountryRank (country rank of the news source), socialScore (total shares on social media), facebookShares (shares on Facebook only)
@param sortByAsc: should the results be sorted in ascending order (True) or descending (False)
@param returnInfo: what details should be included in the returned information
"""
assert page >= 1
assert count <= 100
params = {
"action": "getArticlesForTopicPage",
"resultType": "articles",
"dataType": self.topicPage["dataType"],
"articlesCount": count,
"articlesSortBy": sortBy,
"articlesSortByAsc": sortByAsc,
"page": page,
"topicPage": json.dumps(self.topicPage)
}
params.update(returnInfo.getParams("articles"))
return self.eventRegistry.jsonRequest("/json/article", params)
|
python
|
def getArticles(self,
page=1,
count=100,
sortBy = "rel",
sortByAsc = False,
returnInfo=ReturnInfo()):
"""
return a list of articles that match the topic page
@param page: which page of the results to return (default: 1)
@param count: number of articles to return (default: 100)
@param sortBy: how are articles sorted. Options: id (internal id), date (publishing date), cosSim (closeness to the event centroid), rel (relevance to the query), sourceImportance (manually curated score of source importance - high value, high importance), sourceImportanceRank (reverse of sourceImportance), sourceAlexaGlobalRank (global rank of the news source), sourceAlexaCountryRank (country rank of the news source), socialScore (total shares on social media), facebookShares (shares on Facebook only)
@param sortByAsc: should the results be sorted in ascending order (True) or descending (False)
@param returnInfo: what details should be included in the returned information
"""
assert page >= 1
assert count <= 100
params = {
"action": "getArticlesForTopicPage",
"resultType": "articles",
"dataType": self.topicPage["dataType"],
"articlesCount": count,
"articlesSortBy": sortBy,
"articlesSortByAsc": sortByAsc,
"page": page,
"topicPage": json.dumps(self.topicPage)
}
params.update(returnInfo.getParams("articles"))
return self.eventRegistry.jsonRequest("/json/article", params)
|
[
"def",
"getArticles",
"(",
"self",
",",
"page",
"=",
"1",
",",
"count",
"=",
"100",
",",
"sortBy",
"=",
"\"rel\"",
",",
"sortByAsc",
"=",
"False",
",",
"returnInfo",
"=",
"ReturnInfo",
"(",
")",
")",
":",
"assert",
"page",
">=",
"1",
"assert",
"count",
"<=",
"100",
"params",
"=",
"{",
"\"action\"",
":",
"\"getArticlesForTopicPage\"",
",",
"\"resultType\"",
":",
"\"articles\"",
",",
"\"dataType\"",
":",
"self",
".",
"topicPage",
"[",
"\"dataType\"",
"]",
",",
"\"articlesCount\"",
":",
"count",
",",
"\"articlesSortBy\"",
":",
"sortBy",
",",
"\"articlesSortByAsc\"",
":",
"sortByAsc",
",",
"\"page\"",
":",
"page",
",",
"\"topicPage\"",
":",
"json",
".",
"dumps",
"(",
"self",
".",
"topicPage",
")",
"}",
"params",
".",
"update",
"(",
"returnInfo",
".",
"getParams",
"(",
"\"articles\"",
")",
")",
"return",
"self",
".",
"eventRegistry",
".",
"jsonRequest",
"(",
"\"/json/article\"",
",",
"params",
")"
] |
return a list of articles that match the topic page
@param page: which page of the results to return (default: 1)
@param count: number of articles to return (default: 100)
@param sortBy: how are articles sorted. Options: id (internal id), date (publishing date), cosSim (closeness to the event centroid), rel (relevance to the query), sourceImportance (manually curated score of source importance - high value, high importance), sourceImportanceRank (reverse of sourceImportance), sourceAlexaGlobalRank (global rank of the news source), sourceAlexaCountryRank (country rank of the news source), socialScore (total shares on social media), facebookShares (shares on Facebook only)
@param sortByAsc: should the results be sorted in ascending order (True) or descending (False)
@param returnInfo: what details should be included in the returned information
|
[
"return",
"a",
"list",
"of",
"articles",
"that",
"match",
"the",
"topic",
"page"
] |
534d20b616de02f5e1cd73665a02d189645dbeb6
|
https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L333-L360
|
15,301
|
EventRegistry/event-registry-python
|
eventregistry/Query.py
|
CombinedQuery.AND
|
def AND(queryArr,
exclude = None):
"""
create a combined query with multiple items on which to perform an AND operation
@param queryArr: a list of items on which to perform an AND operation. Items can be either a CombinedQuery or BaseQuery instances.
@param exclude: a instance of BaseQuery, CombinedQuery or None. Used to filter out results matching the other criteria specified in this query
"""
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 item in queryArr:
assert isinstance(item, (CombinedQuery, BaseQuery)), "item in the list was not a CombinedQuery or BaseQuery instance"
q.getQuery()["$and"].append(item.getQuery())
if exclude != None:
assert isinstance(exclude, (CombinedQuery, BaseQuery)), "exclude parameter was not a CombinedQuery or BaseQuery instance"
q.setQueryParam("$not", exclude.getQuery())
return q
|
python
|
def AND(queryArr,
exclude = None):
"""
create a combined query with multiple items on which to perform an AND operation
@param queryArr: a list of items on which to perform an AND operation. Items can be either a CombinedQuery or BaseQuery instances.
@param exclude: a instance of BaseQuery, CombinedQuery or None. Used to filter out results matching the other criteria specified in this query
"""
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 item in queryArr:
assert isinstance(item, (CombinedQuery, BaseQuery)), "item in the list was not a CombinedQuery or BaseQuery instance"
q.getQuery()["$and"].append(item.getQuery())
if exclude != None:
assert isinstance(exclude, (CombinedQuery, BaseQuery)), "exclude parameter was not a CombinedQuery or BaseQuery instance"
q.setQueryParam("$not", exclude.getQuery())
return q
|
[
"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",
"item",
"in",
"queryArr",
":",
"assert",
"isinstance",
"(",
"item",
",",
"(",
"CombinedQuery",
",",
"BaseQuery",
")",
")",
",",
"\"item in the list was not a CombinedQuery or BaseQuery instance\"",
"q",
".",
"getQuery",
"(",
")",
"[",
"\"$and\"",
"]",
".",
"append",
"(",
"item",
".",
"getQuery",
"(",
")",
")",
"if",
"exclude",
"!=",
"None",
":",
"assert",
"isinstance",
"(",
"exclude",
",",
"(",
"CombinedQuery",
",",
"BaseQuery",
")",
")",
",",
"\"exclude parameter was not a CombinedQuery or BaseQuery instance\"",
"q",
".",
"setQueryParam",
"(",
"\"$not\"",
",",
"exclude",
".",
"getQuery",
"(",
")",
")",
"return",
"q"
] |
create a combined query with multiple items on which to perform an AND operation
@param queryArr: a list of items on which to perform an AND operation. Items can be either a CombinedQuery or BaseQuery instances.
@param exclude: a instance of BaseQuery, CombinedQuery or None. Used to filter out results matching the other criteria specified in this query
|
[
"create",
"a",
"combined",
"query",
"with",
"multiple",
"items",
"on",
"which",
"to",
"perform",
"an",
"AND",
"operation"
] |
534d20b616de02f5e1cd73665a02d189645dbeb6
|
https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/Query.py#L121-L138
|
15,302
|
postlund/pyatv
|
pyatv/mrp/pairing.py
|
MrpPairingProcedure.start_pairing
|
async def start_pairing(self):
"""Start pairing procedure."""
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_identifier=False)
pairing_data = _get_pairing_data(resp)
if tlv8.TLV_BACK_OFF in pairing_data:
time = int.from_bytes(
pairing_data[tlv8.TLV_BACK_OFF], byteorder='big')
raise Exception('back off {0}s'.format(time))
self._atv_salt = pairing_data[tlv8.TLV_SALT]
self._atv_pub_key = pairing_data[tlv8.TLV_PUBLIC_KEY]
|
python
|
async def start_pairing(self):
"""Start pairing procedure."""
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_identifier=False)
pairing_data = _get_pairing_data(resp)
if tlv8.TLV_BACK_OFF in pairing_data:
time = int.from_bytes(
pairing_data[tlv8.TLV_BACK_OFF], byteorder='big')
raise Exception('back off {0}s'.format(time))
self._atv_salt = pairing_data[tlv8.TLV_SALT]
self._atv_pub_key = pairing_data[tlv8.TLV_PUBLIC_KEY]
|
[
"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_identifier",
"=",
"False",
")",
"pairing_data",
"=",
"_get_pairing_data",
"(",
"resp",
")",
"if",
"tlv8",
".",
"TLV_BACK_OFF",
"in",
"pairing_data",
":",
"time",
"=",
"int",
".",
"from_bytes",
"(",
"pairing_data",
"[",
"tlv8",
".",
"TLV_BACK_OFF",
"]",
",",
"byteorder",
"=",
"'big'",
")",
"raise",
"Exception",
"(",
"'back off {0}s'",
".",
"format",
"(",
"time",
")",
")",
"self",
".",
"_atv_salt",
"=",
"pairing_data",
"[",
"tlv8",
".",
"TLV_SALT",
"]",
"self",
".",
"_atv_pub_key",
"=",
"pairing_data",
"[",
"tlv8",
".",
"TLV_PUBLIC_KEY",
"]"
] |
Start pairing procedure.
|
[
"Start",
"pairing",
"procedure",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/pairing.py#L27-L45
|
15,303
|
postlund/pyatv
|
pyatv/mrp/pairing.py
|
MrpPairingProcedure.finish_pairing
|
async def finish_pairing(self, pin):
"""Finish pairing process."""
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,
tlv8.TLV_PROOF: proof})
resp = await self.protocol.send_and_receive(
msg, generate_identifier=False)
pairing_data = _get_pairing_data(resp)
atv_proof = pairing_data[tlv8.TLV_PROOF]
log_binary(_LOGGER, 'Device', Proof=atv_proof)
encrypted_data = self.srp.step3()
msg = messages.crypto_pairing({
tlv8.TLV_SEQ_NO: b'\x05',
tlv8.TLV_ENCRYPTED_DATA: encrypted_data})
resp = await self.protocol.send_and_receive(
msg, generate_identifier=False)
pairing_data = _get_pairing_data(resp)
encrypted_data = pairing_data[tlv8.TLV_ENCRYPTED_DATA]
return self.srp.step4(encrypted_data)
|
python
|
async def finish_pairing(self, pin):
"""Finish pairing process."""
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,
tlv8.TLV_PROOF: proof})
resp = await self.protocol.send_and_receive(
msg, generate_identifier=False)
pairing_data = _get_pairing_data(resp)
atv_proof = pairing_data[tlv8.TLV_PROOF]
log_binary(_LOGGER, 'Device', Proof=atv_proof)
encrypted_data = self.srp.step3()
msg = messages.crypto_pairing({
tlv8.TLV_SEQ_NO: b'\x05',
tlv8.TLV_ENCRYPTED_DATA: encrypted_data})
resp = await self.protocol.send_and_receive(
msg, generate_identifier=False)
pairing_data = _get_pairing_data(resp)
encrypted_data = pairing_data[tlv8.TLV_ENCRYPTED_DATA]
return self.srp.step4(encrypted_data)
|
[
"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",
",",
"tlv8",
".",
"TLV_PROOF",
":",
"proof",
"}",
")",
"resp",
"=",
"await",
"self",
".",
"protocol",
".",
"send_and_receive",
"(",
"msg",
",",
"generate_identifier",
"=",
"False",
")",
"pairing_data",
"=",
"_get_pairing_data",
"(",
"resp",
")",
"atv_proof",
"=",
"pairing_data",
"[",
"tlv8",
".",
"TLV_PROOF",
"]",
"log_binary",
"(",
"_LOGGER",
",",
"'Device'",
",",
"Proof",
"=",
"atv_proof",
")",
"encrypted_data",
"=",
"self",
".",
"srp",
".",
"step3",
"(",
")",
"msg",
"=",
"messages",
".",
"crypto_pairing",
"(",
"{",
"tlv8",
".",
"TLV_SEQ_NO",
":",
"b'\\x05'",
",",
"tlv8",
".",
"TLV_ENCRYPTED_DATA",
":",
"encrypted_data",
"}",
")",
"resp",
"=",
"await",
"self",
".",
"protocol",
".",
"send_and_receive",
"(",
"msg",
",",
"generate_identifier",
"=",
"False",
")",
"pairing_data",
"=",
"_get_pairing_data",
"(",
"resp",
")",
"encrypted_data",
"=",
"pairing_data",
"[",
"tlv8",
".",
"TLV_ENCRYPTED_DATA",
"]",
"return",
"self",
".",
"srp",
".",
"step4",
"(",
"encrypted_data",
")"
] |
Finish pairing process.
|
[
"Finish",
"pairing",
"process",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/pairing.py#L47-L74
|
15,304
|
postlund/pyatv
|
pyatv/mrp/pairing.py
|
MrpPairingVerifier.verify_credentials
|
async def verify_credentials(self):
"""Verify credentials with device."""
_, 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(
msg, generate_identifier=False)
resp = _get_pairing_data(resp)
session_pub_key = resp[tlv8.TLV_PUBLIC_KEY]
encrypted = resp[tlv8.TLV_ENCRYPTED_DATA]
log_binary(_LOGGER,
'Device',
Public=self.credentials.ltpk,
Encrypted=encrypted)
encrypted_data = self.srp.verify1(
self.credentials, session_pub_key, encrypted)
msg = messages.crypto_pairing({
tlv8.TLV_SEQ_NO: b'\x03',
tlv8.TLV_ENCRYPTED_DATA: encrypted_data})
resp = await self.protocol.send_and_receive(
msg, generate_identifier=False)
# TODO: check status code
self._output_key, self._input_key = self.srp.verify2()
|
python
|
async def verify_credentials(self):
"""Verify credentials with device."""
_, 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(
msg, generate_identifier=False)
resp = _get_pairing_data(resp)
session_pub_key = resp[tlv8.TLV_PUBLIC_KEY]
encrypted = resp[tlv8.TLV_ENCRYPTED_DATA]
log_binary(_LOGGER,
'Device',
Public=self.credentials.ltpk,
Encrypted=encrypted)
encrypted_data = self.srp.verify1(
self.credentials, session_pub_key, encrypted)
msg = messages.crypto_pairing({
tlv8.TLV_SEQ_NO: b'\x03',
tlv8.TLV_ENCRYPTED_DATA: encrypted_data})
resp = await self.protocol.send_and_receive(
msg, generate_identifier=False)
# TODO: check status code
self._output_key, self._input_key = self.srp.verify2()
|
[
"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",
"(",
"msg",
",",
"generate_identifier",
"=",
"False",
")",
"resp",
"=",
"_get_pairing_data",
"(",
"resp",
")",
"session_pub_key",
"=",
"resp",
"[",
"tlv8",
".",
"TLV_PUBLIC_KEY",
"]",
"encrypted",
"=",
"resp",
"[",
"tlv8",
".",
"TLV_ENCRYPTED_DATA",
"]",
"log_binary",
"(",
"_LOGGER",
",",
"'Device'",
",",
"Public",
"=",
"self",
".",
"credentials",
".",
"ltpk",
",",
"Encrypted",
"=",
"encrypted",
")",
"encrypted_data",
"=",
"self",
".",
"srp",
".",
"verify1",
"(",
"self",
".",
"credentials",
",",
"session_pub_key",
",",
"encrypted",
")",
"msg",
"=",
"messages",
".",
"crypto_pairing",
"(",
"{",
"tlv8",
".",
"TLV_SEQ_NO",
":",
"b'\\x03'",
",",
"tlv8",
".",
"TLV_ENCRYPTED_DATA",
":",
"encrypted_data",
"}",
")",
"resp",
"=",
"await",
"self",
".",
"protocol",
".",
"send_and_receive",
"(",
"msg",
",",
"generate_identifier",
"=",
"False",
")",
"# TODO: check status code",
"self",
".",
"_output_key",
",",
"self",
".",
"_input_key",
"=",
"self",
".",
"srp",
".",
"verify2",
"(",
")"
] |
Verify credentials with device.
|
[
"Verify",
"credentials",
"with",
"device",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/pairing.py#L88-L116
|
15,305
|
postlund/pyatv
|
pyatv/dmap/tag_definitions.py
|
lookup_tag
|
def lookup_tag(name):
"""Look up a tag based on its key. Returns a DmapTag."""
return next((_TAGS[t] for t in _TAGS if t == name),
DmapTag(_read_unknown, 'unknown tag'))
|
python
|
def lookup_tag(name):
"""Look up a tag based on its key. Returns a DmapTag."""
return next((_TAGS[t] for t in _TAGS if t == name),
DmapTag(_read_unknown, 'unknown tag'))
|
[
"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.
|
[
"Look",
"up",
"a",
"tag",
"based",
"on",
"its",
"key",
".",
"Returns",
"a",
"DmapTag",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/tag_definitions.py#L105-L108
|
15,306
|
postlund/pyatv
|
pyatv/__init__.py
|
connect_to_apple_tv
|
def connect_to_apple_tv(details, loop, protocol=None, session=None):
"""Connect and logins to an Apple TV."""
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 service is the same for both DMAP and MRP
airplay = _setup_airplay(loop, session, details)
# Create correct implementation depending on protocol
if service.protocol == PROTOCOL_DMAP:
return DmapAppleTV(loop, session, details, airplay)
return MrpAppleTV(loop, session, details, airplay)
|
python
|
def connect_to_apple_tv(details, loop, protocol=None, session=None):
"""Connect and logins to an Apple TV."""
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 service is the same for both DMAP and MRP
airplay = _setup_airplay(loop, session, details)
# Create correct implementation depending on protocol
if service.protocol == PROTOCOL_DMAP:
return DmapAppleTV(loop, session, details, airplay)
return MrpAppleTV(loop, session, details, airplay)
|
[
"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 service is the same for both DMAP and MRP",
"airplay",
"=",
"_setup_airplay",
"(",
"loop",
",",
"session",
",",
"details",
")",
"# Create correct implementation depending on protocol",
"if",
"service",
".",
"protocol",
"==",
"PROTOCOL_DMAP",
":",
"return",
"DmapAppleTV",
"(",
"loop",
",",
"session",
",",
"details",
",",
"airplay",
")",
"return",
"MrpAppleTV",
"(",
"loop",
",",
"session",
",",
"details",
",",
"airplay",
")"
] |
Connect and logins to an Apple TV.
|
[
"Connect",
"and",
"logins",
"to",
"an",
"Apple",
"TV",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__init__.py#L165-L180
|
15,307
|
postlund/pyatv
|
pyatv/__init__.py
|
_ServiceListener.add_service
|
def add_service(self, zeroconf, service_type, name):
"""Handle callback from zeroconf when a service has been discovered."""
self.lock.acquire()
try:
self._internal_add(zeroconf, service_type, name)
finally:
self.lock.release()
|
python
|
def add_service(self, zeroconf, service_type, name):
"""Handle callback from zeroconf when a service has been discovered."""
self.lock.acquire()
try:
self._internal_add(zeroconf, service_type, name)
finally:
self.lock.release()
|
[
"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.
|
[
"Handle",
"callback",
"from",
"zeroconf",
"when",
"a",
"service",
"has",
"been",
"discovered",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__init__.py#L43-L49
|
15,308
|
postlund/pyatv
|
pyatv/__init__.py
|
_ServiceListener.add_hs_service
|
def add_hs_service(self, info, address):
"""Add a new device to discovered list."""
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(
address, name, conf.DmapService(hsgid, port=info.port))
|
python
|
def add_hs_service(self, info, address):
"""Add a new device to discovered list."""
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(
address, name, conf.DmapService(hsgid, port=info.port))
|
[
"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",
"(",
"address",
",",
"name",
",",
"conf",
".",
"DmapService",
"(",
"hsgid",
",",
"port",
"=",
"info",
".",
"port",
")",
")"
] |
Add a new device to discovered list.
|
[
"Add",
"a",
"new",
"device",
"to",
"discovered",
"list",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__init__.py#L75-L83
|
15,309
|
postlund/pyatv
|
pyatv/__init__.py
|
_ServiceListener.add_non_hs_service
|
def add_non_hs_service(self, info, address):
"""Add a new device without Home Sharing to discovered list."""
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=info.port))
|
python
|
def add_non_hs_service(self, info, address):
"""Add a new device without Home Sharing to discovered list."""
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=info.port))
|
[
"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",
"=",
"info",
".",
"port",
")",
")"
] |
Add a new device without Home Sharing to discovered list.
|
[
"Add",
"a",
"new",
"device",
"without",
"Home",
"Sharing",
"to",
"discovered",
"list",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__init__.py#L85-L92
|
15,310
|
postlund/pyatv
|
pyatv/__init__.py
|
_ServiceListener.add_mrp_service
|
def add_mrp_service(self, info, address):
"""Add a new MediaRemoteProtocol device to discovered list."""
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))
|
python
|
def add_mrp_service(self, info, address):
"""Add a new MediaRemoteProtocol device to discovered list."""
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))
|
[
"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.
|
[
"Add",
"a",
"new",
"MediaRemoteProtocol",
"device",
"to",
"discovered",
"list",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__init__.py#L94-L100
|
15,311
|
postlund/pyatv
|
pyatv/__init__.py
|
_ServiceListener.add_airplay_service
|
def add_airplay_service(self, info, address):
"""Add a new AirPlay device to discovered list."""
name = info.name.replace('._airplay._tcp.local.', '')
self._handle_service(address, name, conf.AirPlayService(info.port))
|
python
|
def add_airplay_service(self, info, address):
"""Add a new AirPlay device to discovered list."""
name = info.name.replace('._airplay._tcp.local.', '')
self._handle_service(address, name, conf.AirPlayService(info.port))
|
[
"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.
|
[
"Add",
"a",
"new",
"AirPlay",
"device",
"to",
"discovered",
"list",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__init__.py#L102-L105
|
15,312
|
postlund/pyatv
|
pyatv/conf.py
|
AppleTV.usable_service
|
def usable_service(self):
"""Return a usable service or None if there is none.
A service is usable if enough configuration to be able to make a
connection is available. If several protocols are usable, MRP will be
preferred over DMAP.
"""
services = self._services
for protocol in self._supported_protocols:
if protocol in services and services[protocol].is_usable():
return services[protocol]
return None
|
python
|
def usable_service(self):
"""Return a usable service or None if there is none.
A service is usable if enough configuration to be able to make a
connection is available. If several protocols are usable, MRP will be
preferred over DMAP.
"""
services = self._services
for protocol in self._supported_protocols:
if protocol in services and services[protocol].is_usable():
return services[protocol]
return None
|
[
"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.
A service is usable if enough configuration to be able to make a
connection is available. If several protocols are usable, MRP will be
preferred over DMAP.
|
[
"Return",
"a",
"usable",
"service",
"or",
"None",
"if",
"there",
"is",
"none",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/conf.py#L49-L61
|
15,313
|
postlund/pyatv
|
pyatv/conf.py
|
DmapService.superseeded_by
|
def superseeded_by(self, other_service):
"""Return True if input service has login id and this has not."""
if not other_service or \
other_service.__class__ != self.__class__ or \
other_service.protocol != self.protocol or \
other_service.port != self.port:
return False
# If this service does not have a login id but the other one does, then
# we should return True here
return not self.device_credentials and other_service.device_credentials
|
python
|
def superseeded_by(self, other_service):
"""Return True if input service has login id and this has not."""
if not other_service or \
other_service.__class__ != self.__class__ or \
other_service.protocol != self.protocol or \
other_service.port != self.port:
return False
# If this service does not have a login id but the other one does, then
# we should return True here
return not self.device_credentials and other_service.device_credentials
|
[
"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",
"False",
"# If this service does not have a login id but the other one does, then",
"# we should return True here",
"return",
"not",
"self",
".",
"device_credentials",
"and",
"other_service",
".",
"device_credentials"
] |
Return True if input service has login id and this has not.
|
[
"Return",
"True",
"if",
"input",
"service",
"has",
"login",
"id",
"and",
"this",
"has",
"not",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/conf.py#L130-L140
|
15,314
|
postlund/pyatv
|
examples/autodiscover.py
|
print_what_is_playing
|
async def print_what_is_playing(loop):
"""Find a device and print what is playing."""
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[0].address))
atv = pyatv.connect_to_apple_tv(atvs[0], loop)
try:
playing = await atv.metadata.playing()
print('Currently playing:')
print(playing)
finally:
# Do not forget to logout
await atv.logout()
|
python
|
async def print_what_is_playing(loop):
"""Find a device and print what is playing."""
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[0].address))
atv = pyatv.connect_to_apple_tv(atvs[0], loop)
try:
playing = await atv.metadata.playing()
print('Currently playing:')
print(playing)
finally:
# Do not forget to logout
await atv.logout()
|
[
"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",
"[",
"0",
"]",
".",
"address",
")",
")",
"atv",
"=",
"pyatv",
".",
"connect_to_apple_tv",
"(",
"atvs",
"[",
"0",
"]",
",",
"loop",
")",
"try",
":",
"playing",
"=",
"await",
"atv",
".",
"metadata",
".",
"playing",
"(",
")",
"print",
"(",
"'Currently playing:'",
")",
"print",
"(",
"playing",
")",
"finally",
":",
"# Do not forget to logout",
"await",
"atv",
".",
"logout",
"(",
")"
] |
Find a device and print what is playing.
|
[
"Find",
"a",
"device",
"and",
"print",
"what",
"is",
"playing",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/examples/autodiscover.py#L11-L29
|
15,315
|
postlund/pyatv
|
pyatv/dmap/pairing.py
|
DmapPairingHandler.start
|
async def start(self, **kwargs):
"""Start the pairing server and publish service."""
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_request, loop=self._loop)
self._server = await self._loop.create_server(
self._web_server, '0.0.0.0')
# Get the allocated (random port) and include it in zeroconf service
allocated_port = self._server.sockets[0].getsockname()[1]
_LOGGER.debug('Started pairing web server at port %d', allocated_port)
self._setup_zeroconf(zeroconf, allocated_port)
|
python
|
async def start(self, **kwargs):
"""Start the pairing server and publish service."""
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_request, loop=self._loop)
self._server = await self._loop.create_server(
self._web_server, '0.0.0.0')
# Get the allocated (random port) and include it in zeroconf service
allocated_port = self._server.sockets[0].getsockname()[1]
_LOGGER.debug('Started pairing web server at port %d', allocated_port)
self._setup_zeroconf(zeroconf, allocated_port)
|
[
"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_request",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
"self",
".",
"_server",
"=",
"await",
"self",
".",
"_loop",
".",
"create_server",
"(",
"self",
".",
"_web_server",
",",
"'0.0.0.0'",
")",
"# Get the allocated (random port) and include it in zeroconf service",
"allocated_port",
"=",
"self",
".",
"_server",
".",
"sockets",
"[",
"0",
"]",
".",
"getsockname",
"(",
")",
"[",
"1",
"]",
"_LOGGER",
".",
"debug",
"(",
"'Started pairing web server at port %d'",
",",
"allocated_port",
")",
"self",
".",
"_setup_zeroconf",
"(",
"zeroconf",
",",
"allocated_port",
")"
] |
Start the pairing server and publish service.
|
[
"Start",
"the",
"pairing",
"server",
"and",
"publish",
"service",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/pairing.py#L71-L86
|
15,316
|
postlund/pyatv
|
pyatv/dmap/pairing.py
|
DmapPairingHandler.stop
|
async def stop(self, **kwargs):
"""Stop pairing server and unpublish service."""
_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._server.wait_closed()
|
python
|
async def stop(self, **kwargs):
"""Stop pairing server and unpublish service."""
_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._server.wait_closed()
|
[
"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",
".",
"_server",
".",
"wait_closed",
"(",
")"
] |
Stop pairing server and unpublish service.
|
[
"Stop",
"pairing",
"server",
"and",
"unpublish",
"service",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/pairing.py#L88-L96
|
15,317
|
postlund/pyatv
|
pyatv/dmap/pairing.py
|
DmapPairingHandler.handle_request
|
async def handle_request(self, request):
"""Respond to request if PIN is correct."""
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_name, received_code)
if self._verify_pin(received_code):
cmpg = tags.uint64_tag('cmpg', int(self._pairing_guid, 16))
cmnm = tags.string_tag('cmnm', self._name)
cmty = tags.string_tag('cmty', 'iPhone')
response = tags.container_tag('cmpa', cmpg + cmnm + cmty)
self._has_paired = True
return web.Response(body=response)
# Code did not match, generate an error
return web.Response(status=500)
|
python
|
async def handle_request(self, request):
"""Respond to request if PIN is correct."""
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_name, received_code)
if self._verify_pin(received_code):
cmpg = tags.uint64_tag('cmpg', int(self._pairing_guid, 16))
cmnm = tags.string_tag('cmnm', self._name)
cmty = tags.string_tag('cmty', 'iPhone')
response = tags.container_tag('cmpa', cmpg + cmnm + cmty)
self._has_paired = True
return web.Response(body=response)
# Code did not match, generate an error
return web.Response(status=500)
|
[
"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_name",
",",
"received_code",
")",
"if",
"self",
".",
"_verify_pin",
"(",
"received_code",
")",
":",
"cmpg",
"=",
"tags",
".",
"uint64_tag",
"(",
"'cmpg'",
",",
"int",
"(",
"self",
".",
"_pairing_guid",
",",
"16",
")",
")",
"cmnm",
"=",
"tags",
".",
"string_tag",
"(",
"'cmnm'",
",",
"self",
".",
"_name",
")",
"cmty",
"=",
"tags",
".",
"string_tag",
"(",
"'cmty'",
",",
"'iPhone'",
")",
"response",
"=",
"tags",
".",
"container_tag",
"(",
"'cmpa'",
",",
"cmpg",
"+",
"cmnm",
"+",
"cmty",
")",
"self",
".",
"_has_paired",
"=",
"True",
"return",
"web",
".",
"Response",
"(",
"body",
"=",
"response",
")",
"# Code did not match, generate an error",
"return",
"web",
".",
"Response",
"(",
"status",
"=",
"500",
")"
] |
Respond to request if PIN is correct.
|
[
"Respond",
"to",
"request",
"if",
"PIN",
"is",
"correct",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/pairing.py#L129-L145
|
15,318
|
postlund/pyatv
|
pyatv/log.py
|
log_binary
|
def log_binary(logger, message, **kwargs):
"""Log binary data if debug is enabled."""
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(output))
|
python
|
def log_binary(logger, message, **kwargs):
"""Log binary data if debug is enabled."""
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(output))
|
[
"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",
"(",
"output",
")",
")"
] |
Log binary data if debug is enabled.
|
[
"Log",
"binary",
"data",
"if",
"debug",
"is",
"enabled",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/log.py#L8-L13
|
15,319
|
postlund/pyatv
|
pyatv/__main__.py
|
_extract_command_with_args
|
def _extract_command_with_args(cmd):
"""Parse input command with arguments.
Parses the input command in such a way that the user may
provide additional argument to the command. The format used is this:
command=arg1,arg2,arg3,...
all the additional arguments are passed as arguments to the target
method.
"""
def _isint(value):
try:
int(value)
return True
except ValueError:
return False
equal_sign = cmd.find('=')
if equal_sign == -1:
return cmd, []
command = cmd[0:equal_sign]
args = cmd[equal_sign+1:].split(',')
converted = [x if not _isint(x) else int(x) for x in args]
return command, converted
|
python
|
def _extract_command_with_args(cmd):
"""Parse input command with arguments.
Parses the input command in such a way that the user may
provide additional argument to the command. The format used is this:
command=arg1,arg2,arg3,...
all the additional arguments are passed as arguments to the target
method.
"""
def _isint(value):
try:
int(value)
return True
except ValueError:
return False
equal_sign = cmd.find('=')
if equal_sign == -1:
return cmd, []
command = cmd[0:equal_sign]
args = cmd[equal_sign+1:].split(',')
converted = [x if not _isint(x) else int(x) for x in args]
return command, converted
|
[
"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",
"[",
"0",
":",
"equal_sign",
"]",
"args",
"=",
"cmd",
"[",
"equal_sign",
"+",
"1",
":",
"]",
".",
"split",
"(",
"','",
")",
"converted",
"=",
"[",
"x",
"if",
"not",
"_isint",
"(",
"x",
")",
"else",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"args",
"]",
"return",
"command",
",",
"converted"
] |
Parse input command with arguments.
Parses the input command in such a way that the user may
provide additional argument to the command. The format used is this:
command=arg1,arg2,arg3,...
all the additional arguments are passed as arguments to the target
method.
|
[
"Parse",
"input",
"command",
"with",
"arguments",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L362-L385
|
15,320
|
postlund/pyatv
|
pyatv/__main__.py
|
main
|
def main():
"""Start the asyncio event loop and runs the application."""
# 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:
pass # User pressed Ctrl+C, just ignore it
except SystemExit:
pass # sys.exit() was used - do nothing
except: # pylint: disable=bare-except # noqa
import traceback
traceback.print_exc(file=sys.stderr)
sys.stderr.writelines(
'\n>>> An error occurred, full stack trace above\n')
return 1
try:
loop = asyncio.get_event_loop()
return loop.run_until_complete(_run_application(loop))
except KeyboardInterrupt:
pass
return 1
|
python
|
def main():
"""Start the asyncio event loop and runs the application."""
# 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:
pass # User pressed Ctrl+C, just ignore it
except SystemExit:
pass # sys.exit() was used - do nothing
except: # pylint: disable=bare-except # noqa
import traceback
traceback.print_exc(file=sys.stderr)
sys.stderr.writelines(
'\n>>> An error occurred, full stack trace above\n')
return 1
try:
loop = asyncio.get_event_loop()
return loop.run_until_complete(_run_application(loop))
except KeyboardInterrupt:
pass
return 1
|
[
"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",
":",
"pass",
"# User pressed Ctrl+C, just ignore it",
"except",
"SystemExit",
":",
"pass",
"# sys.exit() was used - do nothing",
"except",
":",
"# pylint: disable=bare-except # noqa",
"import",
"traceback",
"traceback",
".",
"print_exc",
"(",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"stderr",
".",
"writelines",
"(",
"'\\n>>> An error occurred, full stack trace above\\n'",
")",
"return",
"1",
"try",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"return",
"loop",
".",
"run_until_complete",
"(",
"_run_application",
"(",
"loop",
")",
")",
"except",
"KeyboardInterrupt",
":",
"pass",
"return",
"1"
] |
Start the asyncio event loop and runs the application.
|
[
"Start",
"the",
"asyncio",
"event",
"loop",
"and",
"runs",
"the",
"application",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L484-L513
|
15,321
|
postlund/pyatv
|
pyatv/__main__.py
|
GlobalCommands.commands
|
async def commands(self):
"""Print a list with available commands."""
_print_commands('Remote control', interface.RemoteControl)
_print_commands('Metadata', interface.Metadata)
_print_commands('Playing', interface.Playing)
_print_commands('AirPlay', interface.AirPlay)
_print_commands('Device', DeviceCommands)
_print_commands('Global', self.__class__)
return 0
|
python
|
async def commands(self):
"""Print a list with available commands."""
_print_commands('Remote control', interface.RemoteControl)
_print_commands('Metadata', interface.Metadata)
_print_commands('Playing', interface.Playing)
_print_commands('AirPlay', interface.AirPlay)
_print_commands('Device', DeviceCommands)
_print_commands('Global', self.__class__)
return 0
|
[
"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_commands",
"(",
"'Device'",
",",
"DeviceCommands",
")",
"_print_commands",
"(",
"'Global'",
",",
"self",
".",
"__class__",
")",
"return",
"0"
] |
Print a list with available commands.
|
[
"Print",
"a",
"list",
"with",
"available",
"commands",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L43-L52
|
15,322
|
postlund/pyatv
|
pyatv/__main__.py
|
GlobalCommands.help
|
async def help(self):
"""Print help text for a command."""
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.Playing,
interface.AirPlay,
self.__class__,
DeviceCommands]
for cmd in iface:
for key, value in cmd.__dict__.items():
if key.startswith('_') or key != self.args.command[1]:
continue
if inspect.isfunction(value):
signature = inspect.signature(value)
else:
signature = ' (property)'
print('COMMAND:\n>> {0}{1}\n\nHELP:\n{2}'.format(
key, signature, inspect.getdoc(value)))
return 0
|
python
|
async def help(self):
"""Print help text for a command."""
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.Playing,
interface.AirPlay,
self.__class__,
DeviceCommands]
for cmd in iface:
for key, value in cmd.__dict__.items():
if key.startswith('_') or key != self.args.command[1]:
continue
if inspect.isfunction(value):
signature = inspect.signature(value)
else:
signature = ' (property)'
print('COMMAND:\n>> {0}{1}\n\nHELP:\n{2}'.format(
key, signature, inspect.getdoc(value)))
return 0
|
[
"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",
".",
"Playing",
",",
"interface",
".",
"AirPlay",
",",
"self",
".",
"__class__",
",",
"DeviceCommands",
"]",
"for",
"cmd",
"in",
"iface",
":",
"for",
"key",
",",
"value",
"in",
"cmd",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"'_'",
")",
"or",
"key",
"!=",
"self",
".",
"args",
".",
"command",
"[",
"1",
"]",
":",
"continue",
"if",
"inspect",
".",
"isfunction",
"(",
"value",
")",
":",
"signature",
"=",
"inspect",
".",
"signature",
"(",
"value",
")",
"else",
":",
"signature",
"=",
"' (property)'",
"print",
"(",
"'COMMAND:\\n>> {0}{1}\\n\\nHELP:\\n{2}'",
".",
"format",
"(",
"key",
",",
"signature",
",",
"inspect",
".",
"getdoc",
"(",
"value",
")",
")",
")",
"return",
"0"
] |
Print help text for a command.
|
[
"Print",
"help",
"text",
"for",
"a",
"command",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L54-L78
|
15,323
|
postlund/pyatv
|
pyatv/__main__.py
|
GlobalCommands.scan
|
async def scan(self):
"""Scan for Apple TVs on the network."""
atvs = await pyatv.scan_for_apple_tvs(
self.loop, timeout=self.args.scan_timeout, only_usable=False)
_print_found_apple_tvs(atvs)
return 0
|
python
|
async def scan(self):
"""Scan for Apple TVs on the network."""
atvs = await pyatv.scan_for_apple_tvs(
self.loop, timeout=self.args.scan_timeout, only_usable=False)
_print_found_apple_tvs(atvs)
return 0
|
[
"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.
|
[
"Scan",
"for",
"Apple",
"TVs",
"on",
"the",
"network",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L80-L86
|
15,324
|
postlund/pyatv
|
pyatv/__main__.py
|
DeviceCommands.cli
|
async def cli(self):
"""Enter commands in a simple CLI."""
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':
break
elif command == 'cli':
print('Command not availble here')
continue
await _handle_device_command(
self.args, command, self.atv, self.loop)
|
python
|
async def cli(self):
"""Enter commands in a simple CLI."""
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':
break
elif command == 'cli':
print('Command not availble here')
continue
await _handle_device_command(
self.args, command, self.atv, self.loop)
|
[
"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'",
":",
"break",
"elif",
"command",
"==",
"'cli'",
":",
"print",
"(",
"'Command not availble here'",
")",
"continue",
"await",
"_handle_device_command",
"(",
"self",
".",
"args",
",",
"command",
",",
"self",
".",
"atv",
",",
"self",
".",
"loop",
")"
] |
Enter commands in a simple CLI.
|
[
"Enter",
"commands",
"in",
"a",
"simple",
"CLI",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L101-L115
|
15,325
|
postlund/pyatv
|
pyatv/__main__.py
|
DeviceCommands.artwork_save
|
async def artwork_save(self):
"""Download artwork and save it to artwork.png."""
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 available.')
return 1
return 0
|
python
|
async def artwork_save(self):
"""Download artwork and save it to artwork.png."""
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 available.')
return 1
return 0
|
[
"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 available.'",
")",
"return",
"1",
"return",
"0"
] |
Download artwork and save it to artwork.png.
|
[
"Download",
"artwork",
"and",
"save",
"it",
"to",
"artwork",
".",
"png",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L117-L126
|
15,326
|
postlund/pyatv
|
pyatv/__main__.py
|
DeviceCommands.push_updates
|
async def push_updates(self):
"""Listen for push updates."""
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
|
python
|
async def push_updates(self):
"""Listen for push updates."""
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
|
[
"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.
|
[
"Listen",
"for",
"push",
"updates",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L128-L136
|
15,327
|
postlund/pyatv
|
pyatv/__main__.py
|
DeviceCommands.auth
|
async def auth(self):
"""Perform AirPlay device authentication."""
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.loop, 'Enter PIN on screen: ')
await self.atv.airplay.finish_authentication(pin)
print('You may now use these credentials:')
print(credentials)
return 0
except exceptions.DeviceAuthenticationError:
logging.exception('Failed to authenticate - invalid PIN?')
return 1
|
python
|
async def auth(self):
"""Perform AirPlay device authentication."""
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.loop, 'Enter PIN on screen: ')
await self.atv.airplay.finish_authentication(pin)
print('You may now use these credentials:')
print(credentials)
return 0
except exceptions.DeviceAuthenticationError:
logging.exception('Failed to authenticate - invalid PIN?')
return 1
|
[
"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",
".",
"loop",
",",
"'Enter PIN on screen: '",
")",
"await",
"self",
".",
"atv",
".",
"airplay",
".",
"finish_authentication",
"(",
"pin",
")",
"print",
"(",
"'You may now use these credentials:'",
")",
"print",
"(",
"credentials",
")",
"return",
"0",
"except",
"exceptions",
".",
"DeviceAuthenticationError",
":",
"logging",
".",
"exception",
"(",
"'Failed to authenticate - invalid PIN?'",
")",
"return",
"1"
] |
Perform AirPlay device authentication.
|
[
"Perform",
"AirPlay",
"device",
"authentication",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L138-L154
|
15,328
|
postlund/pyatv
|
pyatv/__main__.py
|
DeviceCommands.pair
|
async def pair(self):
"""Pair pyatv as a remote control with an Apple TV."""
# 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.pairing.start(zeroconf=Zeroconf(),
name=self.args.remote_name,
pairing_guid=self.args.pairing_guid)
elif protocol == const.PROTOCOL_MRP:
await self.atv.pairing.start()
# Ask for PIN if present or just wait for pairing to end
if self.atv.pairing.device_provides_pin:
pin = await _read_input(self.loop, 'Enter PIN on screen: ')
self.atv.pairing.pin(pin)
else:
self.atv.pairing.pin(self.args.pin_code)
print('Use {0} to pair with "{1}" (press ENTER to stop)'.format(
self.args.pin_code, self.args.remote_name))
if self.args.pin_code is None:
print('Use any pin to pair with "{}" (press ENTER to stop)'.format(
self.args.remote_name))
else:
print('Use pin {} to pair with "{}" (press ENTER to stop)'.format(
self.args.pin_code, self.args.remote_name))
await self.loop.run_in_executor(None, sys.stdin.readline)
await self.atv.pairing.stop()
# Give some feedback to the user
if self.atv.pairing.has_paired:
print('Pairing seems to have succeeded, yey!')
print('You may now use these credentials: {0}'.format(
self.atv.pairing.credentials))
else:
print('Pairing failed!')
return 1
return 0
|
python
|
async def pair(self):
"""Pair pyatv as a remote control with an Apple TV."""
# 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.pairing.start(zeroconf=Zeroconf(),
name=self.args.remote_name,
pairing_guid=self.args.pairing_guid)
elif protocol == const.PROTOCOL_MRP:
await self.atv.pairing.start()
# Ask for PIN if present or just wait for pairing to end
if self.atv.pairing.device_provides_pin:
pin = await _read_input(self.loop, 'Enter PIN on screen: ')
self.atv.pairing.pin(pin)
else:
self.atv.pairing.pin(self.args.pin_code)
print('Use {0} to pair with "{1}" (press ENTER to stop)'.format(
self.args.pin_code, self.args.remote_name))
if self.args.pin_code is None:
print('Use any pin to pair with "{}" (press ENTER to stop)'.format(
self.args.remote_name))
else:
print('Use pin {} to pair with "{}" (press ENTER to stop)'.format(
self.args.pin_code, self.args.remote_name))
await self.loop.run_in_executor(None, sys.stdin.readline)
await self.atv.pairing.stop()
# Give some feedback to the user
if self.atv.pairing.has_paired:
print('Pairing seems to have succeeded, yey!')
print('You may now use these credentials: {0}'.format(
self.atv.pairing.credentials))
else:
print('Pairing failed!')
return 1
return 0
|
[
"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",
".",
"pairing",
".",
"start",
"(",
"zeroconf",
"=",
"Zeroconf",
"(",
")",
",",
"name",
"=",
"self",
".",
"args",
".",
"remote_name",
",",
"pairing_guid",
"=",
"self",
".",
"args",
".",
"pairing_guid",
")",
"elif",
"protocol",
"==",
"const",
".",
"PROTOCOL_MRP",
":",
"await",
"self",
".",
"atv",
".",
"pairing",
".",
"start",
"(",
")",
"# Ask for PIN if present or just wait for pairing to end",
"if",
"self",
".",
"atv",
".",
"pairing",
".",
"device_provides_pin",
":",
"pin",
"=",
"await",
"_read_input",
"(",
"self",
".",
"loop",
",",
"'Enter PIN on screen: '",
")",
"self",
".",
"atv",
".",
"pairing",
".",
"pin",
"(",
"pin",
")",
"else",
":",
"self",
".",
"atv",
".",
"pairing",
".",
"pin",
"(",
"self",
".",
"args",
".",
"pin_code",
")",
"print",
"(",
"'Use {0} to pair with \"{1}\" (press ENTER to stop)'",
".",
"format",
"(",
"self",
".",
"args",
".",
"pin_code",
",",
"self",
".",
"args",
".",
"remote_name",
")",
")",
"if",
"self",
".",
"args",
".",
"pin_code",
"is",
"None",
":",
"print",
"(",
"'Use any pin to pair with \"{}\" (press ENTER to stop)'",
".",
"format",
"(",
"self",
".",
"args",
".",
"remote_name",
")",
")",
"else",
":",
"print",
"(",
"'Use pin {} to pair with \"{}\" (press ENTER to stop)'",
".",
"format",
"(",
"self",
".",
"args",
".",
"pin_code",
",",
"self",
".",
"args",
".",
"remote_name",
")",
")",
"await",
"self",
".",
"loop",
".",
"run_in_executor",
"(",
"None",
",",
"sys",
".",
"stdin",
".",
"readline",
")",
"await",
"self",
".",
"atv",
".",
"pairing",
".",
"stop",
"(",
")",
"# Give some feedback to the user",
"if",
"self",
".",
"atv",
".",
"pairing",
".",
"has_paired",
":",
"print",
"(",
"'Pairing seems to have succeeded, yey!'",
")",
"print",
"(",
"'You may now use these credentials: {0}'",
".",
"format",
"(",
"self",
".",
"atv",
".",
"pairing",
".",
"credentials",
")",
")",
"else",
":",
"print",
"(",
"'Pairing failed!'",
")",
"return",
"1",
"return",
"0"
] |
Pair pyatv as a remote control with an Apple TV.
|
[
"Pair",
"pyatv",
"as",
"a",
"remote",
"control",
"with",
"an",
"Apple",
"TV",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/__main__.py#L156-L198
|
15,329
|
postlund/pyatv
|
pyatv/convert.py
|
media_kind
|
def media_kind(kind):
"""Convert iTunes media kind to API representation."""
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]:
return const.MEDIA_TYPE_TV
raise exceptions.UnknownMediaKind('Unknown media kind: ' + str(kind))
|
python
|
def media_kind(kind):
"""Convert iTunes media kind to API representation."""
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]:
return const.MEDIA_TYPE_TV
raise exceptions.UnknownMediaKind('Unknown media kind: ' + str(kind))
|
[
"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",
"]",
":",
"return",
"const",
".",
"MEDIA_TYPE_TV",
"raise",
"exceptions",
".",
"UnknownMediaKind",
"(",
"'Unknown media kind: '",
"+",
"str",
"(",
"kind",
")",
")"
] |
Convert iTunes media kind to API representation.
|
[
"Convert",
"iTunes",
"media",
"kind",
"to",
"API",
"representation",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L6-L17
|
15,330
|
postlund/pyatv
|
pyatv/convert.py
|
media_type_str
|
def media_type_str(mediatype):
"""Convert internal API media type to string."""
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_TYPE_TV:
return 'TV'
return 'Unsupported'
|
python
|
def media_type_str(mediatype):
"""Convert internal API media type to string."""
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_TYPE_TV:
return 'TV'
return 'Unsupported'
|
[
"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_TYPE_TV",
":",
"return",
"'TV'",
"return",
"'Unsupported'"
] |
Convert internal API media type to string.
|
[
"Convert",
"internal",
"API",
"media",
"type",
"to",
"string",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L20-L30
|
15,331
|
postlund/pyatv
|
pyatv/convert.py
|
playstate
|
def playstate(state):
"""Convert iTunes playstate to API representation."""
# 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:
return const.PLAY_STATE_PAUSED
if state == 4:
return const.PLAY_STATE_PLAYING
if state == 5:
return const.PLAY_STATE_FAST_FORWARD
if state == 6:
return const.PLAY_STATE_FAST_BACKWARD
raise exceptions.UnknownPlayState('Unknown playstate: ' + str(state))
|
python
|
def playstate(state):
"""Convert iTunes playstate to API representation."""
# 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:
return const.PLAY_STATE_PAUSED
if state == 4:
return const.PLAY_STATE_PLAYING
if state == 5:
return const.PLAY_STATE_FAST_FORWARD
if state == 6:
return const.PLAY_STATE_FAST_BACKWARD
raise exceptions.UnknownPlayState('Unknown playstate: ' + str(state))
|
[
"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",
":",
"return",
"const",
".",
"PLAY_STATE_PAUSED",
"if",
"state",
"==",
"4",
":",
"return",
"const",
".",
"PLAY_STATE_PLAYING",
"if",
"state",
"==",
"5",
":",
"return",
"const",
".",
"PLAY_STATE_FAST_FORWARD",
"if",
"state",
"==",
"6",
":",
"return",
"const",
".",
"PLAY_STATE_FAST_BACKWARD",
"raise",
"exceptions",
".",
"UnknownPlayState",
"(",
"'Unknown playstate: '",
"+",
"str",
"(",
"state",
")",
")"
] |
Convert iTunes playstate to API representation.
|
[
"Convert",
"iTunes",
"playstate",
"to",
"API",
"representation",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L33-L51
|
15,332
|
postlund/pyatv
|
pyatv/convert.py
|
playstate_str
|
def playstate_str(state):
"""Convert internal API playstate to string."""
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:
return 'Paused'
if state == const.PLAY_STATE_PLAYING:
return 'Playing'
if state == const.PLAY_STATE_FAST_FORWARD:
return 'Fast forward'
if state == const.PLAY_STATE_FAST_BACKWARD:
return 'Fast backward'
return 'Unsupported'
|
python
|
def playstate_str(state):
"""Convert internal API playstate to string."""
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:
return 'Paused'
if state == const.PLAY_STATE_PLAYING:
return 'Playing'
if state == const.PLAY_STATE_FAST_FORWARD:
return 'Fast forward'
if state == const.PLAY_STATE_FAST_BACKWARD:
return 'Fast backward'
return 'Unsupported'
|
[
"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",
":",
"return",
"'Paused'",
"if",
"state",
"==",
"const",
".",
"PLAY_STATE_PLAYING",
":",
"return",
"'Playing'",
"if",
"state",
"==",
"const",
".",
"PLAY_STATE_FAST_FORWARD",
":",
"return",
"'Fast forward'",
"if",
"state",
"==",
"const",
".",
"PLAY_STATE_FAST_BACKWARD",
":",
"return",
"'Fast backward'",
"return",
"'Unsupported'"
] |
Convert internal API playstate to string.
|
[
"Convert",
"internal",
"API",
"playstate",
"to",
"string",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L55-L71
|
15,333
|
postlund/pyatv
|
pyatv/convert.py
|
repeat_str
|
def repeat_str(state):
"""Convert internal API repeat state to string."""
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'
|
python
|
def repeat_str(state):
"""Convert internal API repeat state to string."""
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'
|
[
"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.
|
[
"Convert",
"internal",
"API",
"repeat",
"state",
"to",
"string",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L74-L82
|
15,334
|
postlund/pyatv
|
pyatv/convert.py
|
protocol_str
|
def protocol_str(protocol):
"""Convert internal API protocol to string."""
if protocol == const.PROTOCOL_MRP:
return 'MRP'
if protocol == const.PROTOCOL_DMAP:
return 'DMAP'
if protocol == const.PROTOCOL_AIRPLAY:
return 'AirPlay'
return 'Unknown'
|
python
|
def protocol_str(protocol):
"""Convert internal API protocol to string."""
if protocol == const.PROTOCOL_MRP:
return 'MRP'
if protocol == const.PROTOCOL_DMAP:
return 'DMAP'
if protocol == const.PROTOCOL_AIRPLAY:
return 'AirPlay'
return 'Unknown'
|
[
"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.
|
[
"Convert",
"internal",
"API",
"protocol",
"to",
"string",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/convert.py#L96-L104
|
15,335
|
postlund/pyatv
|
pyatv/dmap/parser.py
|
first
|
def first(dmap_data, *path):
"""Look up a value given a path in some parsed DMAP data."""
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
|
python
|
def first(dmap_data, *path):
"""Look up a value given a path in some parsed DMAP data."""
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
|
[
"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.
|
[
"Look",
"up",
"a",
"value",
"given",
"a",
"path",
"in",
"some",
"parsed",
"DMAP",
"data",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/parser.py#L56-L65
|
15,336
|
postlund/pyatv
|
pyatv/dmap/parser.py
|
pprint
|
def pprint(data, tag_lookup, indent=0):
"""Return a pretty formatted string of parsed DMAP data."""
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}{1}: {2}\n'.format(indent*' ', key, tag)
output += pprint(value, tag_lookup, indent+2)
else:
output += '{0}{1}: {2} {3}\n'.format(
indent*' ', key, str(value), tag)
elif isinstance(data, list):
for elem in data:
output += pprint(elem, tag_lookup, indent)
else:
raise exceptions.InvalidDmapDataError(
'invalid dmap data: ' + str(data))
return output
|
python
|
def pprint(data, tag_lookup, indent=0):
"""Return a pretty formatted string of parsed DMAP data."""
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}{1}: {2}\n'.format(indent*' ', key, tag)
output += pprint(value, tag_lookup, indent+2)
else:
output += '{0}{1}: {2} {3}\n'.format(
indent*' ', key, str(value), tag)
elif isinstance(data, list):
for elem in data:
output += pprint(elem, tag_lookup, indent)
else:
raise exceptions.InvalidDmapDataError(
'invalid dmap data: ' + str(data))
return output
|
[
"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}{1}: {2}\\n'",
".",
"format",
"(",
"indent",
"*",
"' '",
",",
"key",
",",
"tag",
")",
"output",
"+=",
"pprint",
"(",
"value",
",",
"tag_lookup",
",",
"indent",
"+",
"2",
")",
"else",
":",
"output",
"+=",
"'{0}{1}: {2} {3}\\n'",
".",
"format",
"(",
"indent",
"*",
"' '",
",",
"key",
",",
"str",
"(",
"value",
")",
",",
"tag",
")",
"elif",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"for",
"elem",
"in",
"data",
":",
"output",
"+=",
"pprint",
"(",
"elem",
",",
"tag_lookup",
",",
"indent",
")",
"else",
":",
"raise",
"exceptions",
".",
"InvalidDmapDataError",
"(",
"'invalid dmap data: '",
"+",
"str",
"(",
"data",
")",
")",
"return",
"output"
] |
Return a pretty formatted string of parsed DMAP data.
|
[
"Return",
"a",
"pretty",
"formatted",
"string",
"of",
"parsed",
"DMAP",
"data",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/parser.py#L69-L87
|
15,337
|
postlund/pyatv
|
pyatv/interface.py
|
retrieve_commands
|
def retrieve_commands(obj):
"""Retrieve all commands and help texts from an API object."""
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('_'):
continue
commands[func] = _get_first_sentence_in_pydoc(
obj.__dict__[func])
return commands
|
python
|
def retrieve_commands(obj):
"""Retrieve all commands and help texts from an API object."""
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('_'):
continue
commands[func] = _get_first_sentence_in_pydoc(
obj.__dict__[func])
return commands
|
[
"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",
"(",
"'_'",
")",
":",
"continue",
"commands",
"[",
"func",
"]",
"=",
"_get_first_sentence_in_pydoc",
"(",
"obj",
".",
"__dict__",
"[",
"func",
"]",
")",
"return",
"commands"
] |
Retrieve all commands and help texts from an API object.
|
[
"Retrieve",
"all",
"commands",
"and",
"help",
"texts",
"from",
"an",
"API",
"object",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/interface.py#L28-L39
|
15,338
|
postlund/pyatv
|
pyatv/interface.py
|
Playing.hash
|
def hash(self):
"""Create a unique hash for what is currently playing.
The hash is based on title, artist, album and total time. It should
always be the same for the same content, but it is not guaranteed.
"""
base = '{0}{1}{2}{3}'.format(
self.title, self.artist, self.album, self.total_time)
return hashlib.sha256(base.encode('utf-8')).hexdigest()
|
python
|
def hash(self):
"""Create a unique hash for what is currently playing.
The hash is based on title, artist, album and total time. It should
always be the same for the same content, but it is not guaranteed.
"""
base = '{0}{1}{2}{3}'.format(
self.title, self.artist, self.album, self.total_time)
return hashlib.sha256(base.encode('utf-8')).hexdigest()
|
[
"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.
The hash is based on title, artist, album and total time. It should
always be the same for the same content, but it is not guaranteed.
|
[
"Create",
"a",
"unique",
"hash",
"for",
"what",
"is",
"currently",
"playing",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/interface.py#L213-L221
|
15,339
|
postlund/pyatv
|
scripts/autogen_protobuf_extensions.py
|
extract_message_info
|
def extract_message_info():
"""Get information about all messages of interest."""
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().rstrip()
# Look for the Type enum
if stripped == 'enum Type {':
types_found = True
continue
elif types_found and stripped == '}':
break
elif not types_found:
continue
constant = stripped.split(' ')[0]
title = constant.title().replace(
'_', '').replace('Hid', 'HID') # Hack...
accessor = title[0].lower() + title[1:]
if not os.path.exists(os.path.join(base_path, title + '.proto')):
continue
yield MessageInfo(
title + '_pb2', title, accessor, constant)
|
python
|
def extract_message_info():
"""Get information about all messages of interest."""
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().rstrip()
# Look for the Type enum
if stripped == 'enum Type {':
types_found = True
continue
elif types_found and stripped == '}':
break
elif not types_found:
continue
constant = stripped.split(' ')[0]
title = constant.title().replace(
'_', '').replace('Hid', 'HID') # Hack...
accessor = title[0].lower() + title[1:]
if not os.path.exists(os.path.join(base_path, title + '.proto')):
continue
yield MessageInfo(
title + '_pb2', title, accessor, constant)
|
[
"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",
"(",
")",
".",
"rstrip",
"(",
")",
"# Look for the Type enum",
"if",
"stripped",
"==",
"'enum Type {'",
":",
"types_found",
"=",
"True",
"continue",
"elif",
"types_found",
"and",
"stripped",
"==",
"'}'",
":",
"break",
"elif",
"not",
"types_found",
":",
"continue",
"constant",
"=",
"stripped",
".",
"split",
"(",
"' '",
")",
"[",
"0",
"]",
"title",
"=",
"constant",
".",
"title",
"(",
")",
".",
"replace",
"(",
"'_'",
",",
"''",
")",
".",
"replace",
"(",
"'Hid'",
",",
"'HID'",
")",
"# Hack...",
"accessor",
"=",
"title",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"+",
"title",
"[",
"1",
":",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"title",
"+",
"'.proto'",
")",
")",
":",
"continue",
"yield",
"MessageInfo",
"(",
"title",
"+",
"'_pb2'",
",",
"title",
",",
"accessor",
",",
"constant",
")"
] |
Get information about all messages of interest.
|
[
"Get",
"information",
"about",
"all",
"messages",
"of",
"interest",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/scripts/autogen_protobuf_extensions.py#L54-L83
|
15,340
|
postlund/pyatv
|
scripts/autogen_protobuf_extensions.py
|
main
|
def main():
"""Script starts somewhere around here."""
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.append(
'from {0} import {1}'.format(
BASE_PACKAGE, info.module))
messages.append(
'from {0}.{1} import {2}'.format(
BASE_PACKAGE, info.module, info.title))
extensions.append(
'ProtocolMessage.{0}: {1}.{2},'.format(
info.const, info.module, info.accessor))
constants.append(
'{0} = ProtocolMessage.{0}'.format(
info.const))
# Look for remaining messages
for module_name, message_name in extract_unreferenced_messages():
if message_name not in message_names:
message_names.add(message_name)
messages.append('from {0}.{1} import {2}'.format(
BASE_PACKAGE, module_name, message_name))
# Print file output with values inserted
print(OUTPUT_TEMPLATE.format(
packages='\n'.join(sorted(packages)),
messages='\n'.join(sorted(messages)),
extensions='\n '.join(sorted(extensions)),
constants='\n'.join(sorted(constants))))
return 0
|
python
|
def main():
"""Script starts somewhere around here."""
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.append(
'from {0} import {1}'.format(
BASE_PACKAGE, info.module))
messages.append(
'from {0}.{1} import {2}'.format(
BASE_PACKAGE, info.module, info.title))
extensions.append(
'ProtocolMessage.{0}: {1}.{2},'.format(
info.const, info.module, info.accessor))
constants.append(
'{0} = ProtocolMessage.{0}'.format(
info.const))
# Look for remaining messages
for module_name, message_name in extract_unreferenced_messages():
if message_name not in message_names:
message_names.add(message_name)
messages.append('from {0}.{1} import {2}'.format(
BASE_PACKAGE, module_name, message_name))
# Print file output with values inserted
print(OUTPUT_TEMPLATE.format(
packages='\n'.join(sorted(packages)),
messages='\n'.join(sorted(messages)),
extensions='\n '.join(sorted(extensions)),
constants='\n'.join(sorted(constants))))
return 0
|
[
"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",
".",
"append",
"(",
"'from {0} import {1}'",
".",
"format",
"(",
"BASE_PACKAGE",
",",
"info",
".",
"module",
")",
")",
"messages",
".",
"append",
"(",
"'from {0}.{1} import {2}'",
".",
"format",
"(",
"BASE_PACKAGE",
",",
"info",
".",
"module",
",",
"info",
".",
"title",
")",
")",
"extensions",
".",
"append",
"(",
"'ProtocolMessage.{0}: {1}.{2},'",
".",
"format",
"(",
"info",
".",
"const",
",",
"info",
".",
"module",
",",
"info",
".",
"accessor",
")",
")",
"constants",
".",
"append",
"(",
"'{0} = ProtocolMessage.{0}'",
".",
"format",
"(",
"info",
".",
"const",
")",
")",
"# Look for remaining messages",
"for",
"module_name",
",",
"message_name",
"in",
"extract_unreferenced_messages",
"(",
")",
":",
"if",
"message_name",
"not",
"in",
"message_names",
":",
"message_names",
".",
"add",
"(",
"message_name",
")",
"messages",
".",
"append",
"(",
"'from {0}.{1} import {2}'",
".",
"format",
"(",
"BASE_PACKAGE",
",",
"module_name",
",",
"message_name",
")",
")",
"# Print file output with values inserted",
"print",
"(",
"OUTPUT_TEMPLATE",
".",
"format",
"(",
"packages",
"=",
"'\\n'",
".",
"join",
"(",
"sorted",
"(",
"packages",
")",
")",
",",
"messages",
"=",
"'\\n'",
".",
"join",
"(",
"sorted",
"(",
"messages",
")",
")",
",",
"extensions",
"=",
"'\\n '",
".",
"join",
"(",
"sorted",
"(",
"extensions",
")",
")",
",",
"constants",
"=",
"'\\n'",
".",
"join",
"(",
"sorted",
"(",
"constants",
")",
")",
")",
")",
"return",
"0"
] |
Script starts somewhere around here.
|
[
"Script",
"starts",
"somewhere",
"around",
"here",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/scripts/autogen_protobuf_extensions.py#L101-L140
|
15,341
|
postlund/pyatv
|
pyatv/mrp/srp.py
|
hkdf_expand
|
def hkdf_expand(salt, info, shared_secret):
"""Derive encryption keys from 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(),
length=32,
salt=salt.encode(),
info=info.encode(),
backend=default_backend()
)
return hkdf.derive(shared_secret)
|
python
|
def hkdf_expand(salt, info, shared_secret):
"""Derive encryption keys from 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(),
length=32,
salt=salt.encode(),
info=info.encode(),
backend=default_backend()
)
return hkdf.derive(shared_secret)
|
[
"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",
"(",
")",
",",
"length",
"=",
"32",
",",
"salt",
"=",
"salt",
".",
"encode",
"(",
")",
",",
"info",
"=",
"info",
".",
"encode",
"(",
")",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
"return",
"hkdf",
".",
"derive",
"(",
"shared_secret",
")"
] |
Derive encryption keys from shared secret.
|
[
"Derive",
"encryption",
"keys",
"from",
"shared",
"secret",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/srp.py#L53-L65
|
15,342
|
postlund/pyatv
|
pyatv/mrp/srp.py
|
Credentials.parse
|
def parse(cls, detail_string):
"""Parse a string represention of Credentials."""
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])
atv_id = binascii.unhexlify(split[2])
client_id = binascii.unhexlify(split[3])
return Credentials(ltpk, ltsk, atv_id, client_id)
|
python
|
def parse(cls, detail_string):
"""Parse a string represention of Credentials."""
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])
atv_id = binascii.unhexlify(split[2])
client_id = binascii.unhexlify(split[3])
return Credentials(ltpk, ltsk, atv_id, client_id)
|
[
"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",
"]",
")",
"atv_id",
"=",
"binascii",
".",
"unhexlify",
"(",
"split",
"[",
"2",
"]",
")",
"client_id",
"=",
"binascii",
".",
"unhexlify",
"(",
"split",
"[",
"3",
"]",
")",
"return",
"Credentials",
"(",
"ltpk",
",",
"ltsk",
",",
"atv_id",
",",
"client_id",
")"
] |
Parse a string represention of Credentials.
|
[
"Parse",
"a",
"string",
"represention",
"of",
"Credentials",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/srp.py#L32-L42
|
15,343
|
postlund/pyatv
|
pyatv/mrp/srp.py
|
SRPAuthHandler.initialize
|
def initialize(self):
"""Initialize operation by generating new keys."""
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(secret=os.urandom(32))
self._verify_public = self._verify_private.get_public()
return self._auth_public, self._verify_public.serialize()
|
python
|
def initialize(self):
"""Initialize operation by generating new keys."""
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(secret=os.urandom(32))
self._verify_public = self._verify_private.get_public()
return self._auth_public, self._verify_public.serialize()
|
[
"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",
"(",
"secret",
"=",
"os",
".",
"urandom",
"(",
"32",
")",
")",
"self",
".",
"_verify_public",
"=",
"self",
".",
"_verify_private",
".",
"get_public",
"(",
")",
"return",
"self",
".",
"_auth_public",
",",
"self",
".",
"_verify_public",
".",
"serialize",
"(",
")"
] |
Initialize operation by generating new keys.
|
[
"Initialize",
"operation",
"by",
"generating",
"new",
"keys",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/srp.py#L85-L92
|
15,344
|
postlund/pyatv
|
pyatv/mrp/srp.py
|
SRPAuthHandler.verify1
|
def verify1(self, credentials, session_pub_key, encrypted):
"""First verification step."""
# 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('Pair-Verify-Encrypt-Salt',
'Pair-Verify-Encrypt-Info',
self._shared)
chacha = chacha20.Chacha20Cipher(session_key, session_key)
decrypted_tlv = tlv8.read_tlv(
chacha.decrypt(encrypted, nounce='PV-Msg02'.encode()))
identifier = decrypted_tlv[tlv8.TLV_IDENTIFIER]
signature = decrypted_tlv[tlv8.TLV_SIGNATURE]
if identifier != credentials.atv_id:
raise Exception('incorrect device response') # TODO: new exception
info = session_pub_key + \
bytes(identifier) + self._verify_public.serialize()
ltpk = VerifyingKey(bytes(credentials.ltpk))
ltpk.verify(bytes(signature), bytes(info)) # throws if no match
device_info = self._verify_public.serialize() + \
credentials.client_id + session_pub_key
device_signature = SigningKey(credentials.ltsk).sign(device_info)
tlv = tlv8.write_tlv({tlv8.TLV_IDENTIFIER: credentials.client_id,
tlv8.TLV_SIGNATURE: device_signature})
return chacha.encrypt(tlv, nounce='PV-Msg03'.encode())
|
python
|
def verify1(self, credentials, session_pub_key, encrypted):
"""First verification step."""
# 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('Pair-Verify-Encrypt-Salt',
'Pair-Verify-Encrypt-Info',
self._shared)
chacha = chacha20.Chacha20Cipher(session_key, session_key)
decrypted_tlv = tlv8.read_tlv(
chacha.decrypt(encrypted, nounce='PV-Msg02'.encode()))
identifier = decrypted_tlv[tlv8.TLV_IDENTIFIER]
signature = decrypted_tlv[tlv8.TLV_SIGNATURE]
if identifier != credentials.atv_id:
raise Exception('incorrect device response') # TODO: new exception
info = session_pub_key + \
bytes(identifier) + self._verify_public.serialize()
ltpk = VerifyingKey(bytes(credentials.ltpk))
ltpk.verify(bytes(signature), bytes(info)) # throws if no match
device_info = self._verify_public.serialize() + \
credentials.client_id + session_pub_key
device_signature = SigningKey(credentials.ltsk).sign(device_info)
tlv = tlv8.write_tlv({tlv8.TLV_IDENTIFIER: credentials.client_id,
tlv8.TLV_SIGNATURE: device_signature})
return chacha.encrypt(tlv, nounce='PV-Msg03'.encode())
|
[
"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",
"(",
"'Pair-Verify-Encrypt-Salt'",
",",
"'Pair-Verify-Encrypt-Info'",
",",
"self",
".",
"_shared",
")",
"chacha",
"=",
"chacha20",
".",
"Chacha20Cipher",
"(",
"session_key",
",",
"session_key",
")",
"decrypted_tlv",
"=",
"tlv8",
".",
"read_tlv",
"(",
"chacha",
".",
"decrypt",
"(",
"encrypted",
",",
"nounce",
"=",
"'PV-Msg02'",
".",
"encode",
"(",
")",
")",
")",
"identifier",
"=",
"decrypted_tlv",
"[",
"tlv8",
".",
"TLV_IDENTIFIER",
"]",
"signature",
"=",
"decrypted_tlv",
"[",
"tlv8",
".",
"TLV_SIGNATURE",
"]",
"if",
"identifier",
"!=",
"credentials",
".",
"atv_id",
":",
"raise",
"Exception",
"(",
"'incorrect device response'",
")",
"# TODO: new exception",
"info",
"=",
"session_pub_key",
"+",
"bytes",
"(",
"identifier",
")",
"+",
"self",
".",
"_verify_public",
".",
"serialize",
"(",
")",
"ltpk",
"=",
"VerifyingKey",
"(",
"bytes",
"(",
"credentials",
".",
"ltpk",
")",
")",
"ltpk",
".",
"verify",
"(",
"bytes",
"(",
"signature",
")",
",",
"bytes",
"(",
"info",
")",
")",
"# throws if no match",
"device_info",
"=",
"self",
".",
"_verify_public",
".",
"serialize",
"(",
")",
"+",
"credentials",
".",
"client_id",
"+",
"session_pub_key",
"device_signature",
"=",
"SigningKey",
"(",
"credentials",
".",
"ltsk",
")",
".",
"sign",
"(",
"device_info",
")",
"tlv",
"=",
"tlv8",
".",
"write_tlv",
"(",
"{",
"tlv8",
".",
"TLV_IDENTIFIER",
":",
"credentials",
".",
"client_id",
",",
"tlv8",
".",
"TLV_SIGNATURE",
":",
"device_signature",
"}",
")",
"return",
"chacha",
".",
"encrypt",
"(",
"tlv",
",",
"nounce",
"=",
"'PV-Msg03'",
".",
"encode",
"(",
")",
")"
] |
First verification step.
|
[
"First",
"verification",
"step",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/srp.py#L94-L127
|
15,345
|
postlund/pyatv
|
pyatv/mrp/srp.py
|
SRPAuthHandler.verify2
|
def verify2(self):
"""Last verification step.
The derived keys (output, input) are returned here.
"""
output_key = hkdf_expand('MediaRemote-Salt',
'MediaRemote-Write-Encryption-Key',
self._shared)
input_key = hkdf_expand('MediaRemote-Salt',
'MediaRemote-Read-Encryption-Key',
self._shared)
log_binary(_LOGGER, 'Keys', Output=output_key, Input=input_key)
return output_key, input_key
|
python
|
def verify2(self):
"""Last verification step.
The derived keys (output, input) are returned here.
"""
output_key = hkdf_expand('MediaRemote-Salt',
'MediaRemote-Write-Encryption-Key',
self._shared)
input_key = hkdf_expand('MediaRemote-Salt',
'MediaRemote-Read-Encryption-Key',
self._shared)
log_binary(_LOGGER, 'Keys', Output=output_key, Input=input_key)
return output_key, input_key
|
[
"def",
"verify2",
"(",
"self",
")",
":",
"output_key",
"=",
"hkdf_expand",
"(",
"'MediaRemote-Salt'",
",",
"'MediaRemote-Write-Encryption-Key'",
",",
"self",
".",
"_shared",
")",
"input_key",
"=",
"hkdf_expand",
"(",
"'MediaRemote-Salt'",
",",
"'MediaRemote-Read-Encryption-Key'",
",",
"self",
".",
"_shared",
")",
"log_binary",
"(",
"_LOGGER",
",",
"'Keys'",
",",
"Output",
"=",
"output_key",
",",
"Input",
"=",
"input_key",
")",
"return",
"output_key",
",",
"input_key"
] |
Last verification step.
The derived keys (output, input) are returned here.
|
[
"Last",
"verification",
"step",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/srp.py#L129-L143
|
15,346
|
postlund/pyatv
|
pyatv/mrp/srp.py
|
SRPAuthHandler.step1
|
def step1(self, pin):
"""First pairing step."""
context = SRPContext(
'Pair-Setup', str(pin),
prime=constants.PRIME_3072,
generator=constants.PRIME_3072_GEN,
hash_func=hashlib.sha512)
self._session = SRPClientSession(
context, binascii.hexlify(self._auth_private).decode())
|
python
|
def step1(self, pin):
"""First pairing step."""
context = SRPContext(
'Pair-Setup', str(pin),
prime=constants.PRIME_3072,
generator=constants.PRIME_3072_GEN,
hash_func=hashlib.sha512)
self._session = SRPClientSession(
context, binascii.hexlify(self._auth_private).decode())
|
[
"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",
"(",
"context",
",",
"binascii",
".",
"hexlify",
"(",
"self",
".",
"_auth_private",
")",
".",
"decode",
"(",
")",
")"
] |
First pairing step.
|
[
"First",
"pairing",
"step",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/srp.py#L145-L153
|
15,347
|
postlund/pyatv
|
pyatv/mrp/srp.py
|
SRPAuthHandler.step2
|
def step2(self, atv_pub_key, atv_salt):
"""Second pairing step."""
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(self._session.key_proof_hash):
raise exceptions.AuthenticationError('proofs do not match (mitm?)')
pub_key = binascii.unhexlify(self._session.public)
proof = binascii.unhexlify(self._session.key_proof)
log_binary(_LOGGER, 'Client', Public=pub_key, Proof=proof)
return pub_key, proof
|
python
|
def step2(self, atv_pub_key, atv_salt):
"""Second pairing step."""
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(self._session.key_proof_hash):
raise exceptions.AuthenticationError('proofs do not match (mitm?)')
pub_key = binascii.unhexlify(self._session.public)
proof = binascii.unhexlify(self._session.key_proof)
log_binary(_LOGGER, 'Client', Public=pub_key, Proof=proof)
return pub_key, proof
|
[
"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",
"(",
"self",
".",
"_session",
".",
"key_proof_hash",
")",
":",
"raise",
"exceptions",
".",
"AuthenticationError",
"(",
"'proofs do not match (mitm?)'",
")",
"pub_key",
"=",
"binascii",
".",
"unhexlify",
"(",
"self",
".",
"_session",
".",
"public",
")",
"proof",
"=",
"binascii",
".",
"unhexlify",
"(",
"self",
".",
"_session",
".",
"key_proof",
")",
"log_binary",
"(",
"_LOGGER",
",",
"'Client'",
",",
"Public",
"=",
"pub_key",
",",
"Proof",
"=",
"proof",
")",
"return",
"pub_key",
",",
"proof"
] |
Second pairing step.
|
[
"Second",
"pairing",
"step",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/srp.py#L155-L167
|
15,348
|
postlund/pyatv
|
pyatv/mrp/srp.py
|
SRPAuthHandler.step3
|
def step3(self):
"""Third pairing step."""
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-Setup-Encrypt-Salt',
'Pair-Setup-Encrypt-Info',
binascii.unhexlify(self._client_session_key))
device_info = ios_device_x + self.pairing_id + self._auth_public
device_signature = self._signing_key.sign(device_info)
tlv = tlv8.write_tlv({tlv8.TLV_IDENTIFIER: self.pairing_id,
tlv8.TLV_PUBLIC_KEY: self._auth_public,
tlv8.TLV_SIGNATURE: device_signature})
chacha = chacha20.Chacha20Cipher(self._session_key, self._session_key)
encrypted_data = chacha.encrypt(tlv, nounce='PS-Msg05'.encode())
log_binary(_LOGGER, 'Data', Encrypted=encrypted_data)
return encrypted_data
|
python
|
def step3(self):
"""Third pairing step."""
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-Setup-Encrypt-Salt',
'Pair-Setup-Encrypt-Info',
binascii.unhexlify(self._client_session_key))
device_info = ios_device_x + self.pairing_id + self._auth_public
device_signature = self._signing_key.sign(device_info)
tlv = tlv8.write_tlv({tlv8.TLV_IDENTIFIER: self.pairing_id,
tlv8.TLV_PUBLIC_KEY: self._auth_public,
tlv8.TLV_SIGNATURE: device_signature})
chacha = chacha20.Chacha20Cipher(self._session_key, self._session_key)
encrypted_data = chacha.encrypt(tlv, nounce='PS-Msg05'.encode())
log_binary(_LOGGER, 'Data', Encrypted=encrypted_data)
return encrypted_data
|
[
"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-Setup-Encrypt-Salt'",
",",
"'Pair-Setup-Encrypt-Info'",
",",
"binascii",
".",
"unhexlify",
"(",
"self",
".",
"_client_session_key",
")",
")",
"device_info",
"=",
"ios_device_x",
"+",
"self",
".",
"pairing_id",
"+",
"self",
".",
"_auth_public",
"device_signature",
"=",
"self",
".",
"_signing_key",
".",
"sign",
"(",
"device_info",
")",
"tlv",
"=",
"tlv8",
".",
"write_tlv",
"(",
"{",
"tlv8",
".",
"TLV_IDENTIFIER",
":",
"self",
".",
"pairing_id",
",",
"tlv8",
".",
"TLV_PUBLIC_KEY",
":",
"self",
".",
"_auth_public",
",",
"tlv8",
".",
"TLV_SIGNATURE",
":",
"device_signature",
"}",
")",
"chacha",
"=",
"chacha20",
".",
"Chacha20Cipher",
"(",
"self",
".",
"_session_key",
",",
"self",
".",
"_session_key",
")",
"encrypted_data",
"=",
"chacha",
".",
"encrypt",
"(",
"tlv",
",",
"nounce",
"=",
"'PS-Msg05'",
".",
"encode",
"(",
")",
")",
"log_binary",
"(",
"_LOGGER",
",",
"'Data'",
",",
"Encrypted",
"=",
"encrypted_data",
")",
"return",
"encrypted_data"
] |
Third pairing step.
|
[
"Third",
"pairing",
"step",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/srp.py#L169-L191
|
15,349
|
postlund/pyatv
|
pyatv/mrp/srp.py
|
SRPAuthHandler.step4
|
def step4(self, encrypted_data):
"""Last pairing step."""
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:
raise Exception('data decrypt failed') # TODO: new exception
decrypted_tlv = tlv8.read_tlv(decrypted_tlv_bytes)
_LOGGER.debug('PS-Msg06: %s', decrypted_tlv)
atv_identifier = decrypted_tlv[tlv8.TLV_IDENTIFIER]
atv_signature = decrypted_tlv[tlv8.TLV_SIGNATURE]
atv_pub_key = decrypted_tlv[tlv8.TLV_PUBLIC_KEY]
log_binary(_LOGGER,
'Device',
Identifier=atv_identifier,
Signature=atv_signature,
Public=atv_pub_key)
# TODO: verify signature here
return Credentials(atv_pub_key, self._signing_key.to_seed(),
atv_identifier, self.pairing_id)
|
python
|
def step4(self, encrypted_data):
"""Last pairing step."""
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:
raise Exception('data decrypt failed') # TODO: new exception
decrypted_tlv = tlv8.read_tlv(decrypted_tlv_bytes)
_LOGGER.debug('PS-Msg06: %s', decrypted_tlv)
atv_identifier = decrypted_tlv[tlv8.TLV_IDENTIFIER]
atv_signature = decrypted_tlv[tlv8.TLV_SIGNATURE]
atv_pub_key = decrypted_tlv[tlv8.TLV_PUBLIC_KEY]
log_binary(_LOGGER,
'Device',
Identifier=atv_identifier,
Signature=atv_signature,
Public=atv_pub_key)
# TODO: verify signature here
return Credentials(atv_pub_key, self._signing_key.to_seed(),
atv_identifier, self.pairing_id)
|
[
"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",
":",
"raise",
"Exception",
"(",
"'data decrypt failed'",
")",
"# TODO: new exception",
"decrypted_tlv",
"=",
"tlv8",
".",
"read_tlv",
"(",
"decrypted_tlv_bytes",
")",
"_LOGGER",
".",
"debug",
"(",
"'PS-Msg06: %s'",
",",
"decrypted_tlv",
")",
"atv_identifier",
"=",
"decrypted_tlv",
"[",
"tlv8",
".",
"TLV_IDENTIFIER",
"]",
"atv_signature",
"=",
"decrypted_tlv",
"[",
"tlv8",
".",
"TLV_SIGNATURE",
"]",
"atv_pub_key",
"=",
"decrypted_tlv",
"[",
"tlv8",
".",
"TLV_PUBLIC_KEY",
"]",
"log_binary",
"(",
"_LOGGER",
",",
"'Device'",
",",
"Identifier",
"=",
"atv_identifier",
",",
"Signature",
"=",
"atv_signature",
",",
"Public",
"=",
"atv_pub_key",
")",
"# TODO: verify signature here",
"return",
"Credentials",
"(",
"atv_pub_key",
",",
"self",
".",
"_signing_key",
".",
"to_seed",
"(",
")",
",",
"atv_identifier",
",",
"self",
".",
"pairing_id",
")"
] |
Last pairing step.
|
[
"Last",
"pairing",
"step",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/srp.py#L193-L215
|
15,350
|
postlund/pyatv
|
pyatv/airplay/srp.py
|
hash_sha512
|
def hash_sha512(*indata):
"""Create SHA512 hash for input arguments."""
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 Exception('invalid input data: ' + str(data))
return hasher.digest()
|
python
|
def hash_sha512(*indata):
"""Create SHA512 hash for input arguments."""
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 Exception('invalid input data: ' + str(data))
return hasher.digest()
|
[
"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",
"Exception",
"(",
"'invalid input data: '",
"+",
"str",
"(",
"data",
")",
")",
"return",
"hasher",
".",
"digest",
"(",
")"
] |
Create SHA512 hash for input arguments.
|
[
"Create",
"SHA512",
"hash",
"for",
"input",
"arguments",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/srp.py#L20-L30
|
15,351
|
postlund/pyatv
|
pyatv/airplay/srp.py
|
aes_encrypt
|
def aes_encrypt(mode, aes_key, aes_iv, *data):
"""Encrypt data with AES in specified mode."""
encryptor = Cipher(
algorithms.AES(aes_key),
mode(aes_iv),
backend=default_backend()).encryptor()
result = None
for value in data:
result = encryptor.update(value)
encryptor.finalize()
return result, None if not hasattr(encryptor, 'tag') else encryptor.tag
|
python
|
def aes_encrypt(mode, aes_key, aes_iv, *data):
"""Encrypt data with AES in specified mode."""
encryptor = Cipher(
algorithms.AES(aes_key),
mode(aes_iv),
backend=default_backend()).encryptor()
result = None
for value in data:
result = encryptor.update(value)
encryptor.finalize()
return result, None if not hasattr(encryptor, 'tag') else encryptor.tag
|
[
"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",
".",
"finalize",
"(",
")",
"return",
"result",
",",
"None",
"if",
"not",
"hasattr",
"(",
"encryptor",
",",
"'tag'",
")",
"else",
"encryptor",
".",
"tag"
] |
Encrypt data with AES in specified mode.
|
[
"Encrypt",
"data",
"with",
"AES",
"in",
"specified",
"mode",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/srp.py#L33-L45
|
15,352
|
postlund/pyatv
|
pyatv/airplay/srp.py
|
new_credentials
|
def new_credentials():
"""Generate a new identifier and seed for authentication.
Use the returned values in the following way:
* The identifier shall be passed as username to SRPAuthHandler.step1
* Seed shall be passed to SRPAuthHandler constructor
"""
identifier = binascii.b2a_hex(os.urandom(8)).decode().upper()
seed = binascii.b2a_hex(os.urandom(32)) # Corresponds to private key
return identifier, seed
|
python
|
def new_credentials():
"""Generate a new identifier and seed for authentication.
Use the returned values in the following way:
* The identifier shall be passed as username to SRPAuthHandler.step1
* Seed shall be passed to SRPAuthHandler constructor
"""
identifier = binascii.b2a_hex(os.urandom(8)).decode().upper()
seed = binascii.b2a_hex(os.urandom(32)) # Corresponds to private key
return identifier, seed
|
[
"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.
Use the returned values in the following way:
* The identifier shall be passed as username to SRPAuthHandler.step1
* Seed shall be passed to SRPAuthHandler constructor
|
[
"Generate",
"a",
"new",
"identifier",
"and",
"seed",
"for",
"authentication",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/srp.py#L48-L57
|
15,353
|
postlund/pyatv
|
pyatv/airplay/srp.py
|
SRPAuthHandler.initialize
|
def initialize(self, seed=None):
"""Initialize handler operation.
This method will generate new encryption keys and must be called prior
to doing authentication or verification.
"""
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()
self._auth_public = verifying_key.to_bytes()
log_binary(_LOGGER,
'Authentication keys',
Private=self._auth_private,
Public=self._auth_public)
|
python
|
def initialize(self, seed=None):
"""Initialize handler operation.
This method will generate new encryption keys and must be called prior
to doing authentication or verification.
"""
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()
self._auth_public = verifying_key.to_bytes()
log_binary(_LOGGER,
'Authentication keys',
Private=self._auth_private,
Public=self._auth_public)
|
[
"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",
"(",
")",
"self",
".",
"_auth_public",
"=",
"verifying_key",
".",
"to_bytes",
"(",
")",
"log_binary",
"(",
"_LOGGER",
",",
"'Authentication keys'",
",",
"Private",
"=",
"self",
".",
"_auth_private",
",",
"Public",
"=",
"self",
".",
"_auth_public",
")"
] |
Initialize handler operation.
This method will generate new encryption keys and must be called prior
to doing authentication or verification.
|
[
"Initialize",
"handler",
"operation",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/srp.py#L86-L100
|
15,354
|
postlund/pyatv
|
pyatv/airplay/srp.py
|
SRPAuthHandler.verify1
|
def verify1(self):
"""First device verification step."""
self._check_initialized()
self._verify_private = curve25519.Private(secret=self.seed)
self._verify_public = self._verify_private.get_public()
log_binary(_LOGGER,
'Verification keys',
Private=self._verify_private.serialize(),
Public=self._verify_public.serialize())
verify_public = self._verify_public.serialize()
return b'\x01\x00\x00\x00' + verify_public + self._auth_public
|
python
|
def verify1(self):
"""First device verification step."""
self._check_initialized()
self._verify_private = curve25519.Private(secret=self.seed)
self._verify_public = self._verify_private.get_public()
log_binary(_LOGGER,
'Verification keys',
Private=self._verify_private.serialize(),
Public=self._verify_public.serialize())
verify_public = self._verify_public.serialize()
return b'\x01\x00\x00\x00' + verify_public + self._auth_public
|
[
"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'",
",",
"Private",
"=",
"self",
".",
"_verify_private",
".",
"serialize",
"(",
")",
",",
"Public",
"=",
"self",
".",
"_verify_public",
".",
"serialize",
"(",
")",
")",
"verify_public",
"=",
"self",
".",
"_verify_public",
".",
"serialize",
"(",
")",
"return",
"b'\\x01\\x00\\x00\\x00'",
"+",
"verify_public",
"+",
"self",
".",
"_auth_public"
] |
First device verification step.
|
[
"First",
"device",
"verification",
"step",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/srp.py#L102-L112
|
15,355
|
postlund/pyatv
|
pyatv/airplay/srp.py
|
SRPAuthHandler.verify2
|
def verify2(self, atv_public_key, data):
"""Last device verification step."""
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._verify_private.get_shared_key(
public, hashfunc=lambda x: x) # No additional hashing used
log_binary(_LOGGER, 'Shared secret', Secret=shared)
# Derive new AES key and IV from shared key
aes_key = hash_sha512('Pair-Verify-AES-Key', shared)[0:16]
aes_iv = hash_sha512('Pair-Verify-AES-IV', shared)[0:16]
log_binary(_LOGGER, 'Pair-Verify-AES', Key=aes_key, IV=aes_iv)
# Sign public keys and encrypt with AES
signer = SigningKey(self._auth_private)
signed = signer.sign(self._verify_public.serialize() + atv_public_key)
signature, _ = aes_encrypt(modes.CTR, aes_key, aes_iv, data, signed)
log_binary(_LOGGER, 'Signature', Signature=signature)
# Signature is prepended with 0x00000000 (alignment?)
return b'\x00\x00\x00\x00' + signature
|
python
|
def verify2(self, atv_public_key, data):
"""Last device verification step."""
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._verify_private.get_shared_key(
public, hashfunc=lambda x: x) # No additional hashing used
log_binary(_LOGGER, 'Shared secret', Secret=shared)
# Derive new AES key and IV from shared key
aes_key = hash_sha512('Pair-Verify-AES-Key', shared)[0:16]
aes_iv = hash_sha512('Pair-Verify-AES-IV', shared)[0:16]
log_binary(_LOGGER, 'Pair-Verify-AES', Key=aes_key, IV=aes_iv)
# Sign public keys and encrypt with AES
signer = SigningKey(self._auth_private)
signed = signer.sign(self._verify_public.serialize() + atv_public_key)
signature, _ = aes_encrypt(modes.CTR, aes_key, aes_iv, data, signed)
log_binary(_LOGGER, 'Signature', Signature=signature)
# Signature is prepended with 0x00000000 (alignment?)
return b'\x00\x00\x00\x00' + signature
|
[
"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",
".",
"_verify_private",
".",
"get_shared_key",
"(",
"public",
",",
"hashfunc",
"=",
"lambda",
"x",
":",
"x",
")",
"# No additional hashing used",
"log_binary",
"(",
"_LOGGER",
",",
"'Shared secret'",
",",
"Secret",
"=",
"shared",
")",
"# Derive new AES key and IV from shared key",
"aes_key",
"=",
"hash_sha512",
"(",
"'Pair-Verify-AES-Key'",
",",
"shared",
")",
"[",
"0",
":",
"16",
"]",
"aes_iv",
"=",
"hash_sha512",
"(",
"'Pair-Verify-AES-IV'",
",",
"shared",
")",
"[",
"0",
":",
"16",
"]",
"log_binary",
"(",
"_LOGGER",
",",
"'Pair-Verify-AES'",
",",
"Key",
"=",
"aes_key",
",",
"IV",
"=",
"aes_iv",
")",
"# Sign public keys and encrypt with AES",
"signer",
"=",
"SigningKey",
"(",
"self",
".",
"_auth_private",
")",
"signed",
"=",
"signer",
".",
"sign",
"(",
"self",
".",
"_verify_public",
".",
"serialize",
"(",
")",
"+",
"atv_public_key",
")",
"signature",
",",
"_",
"=",
"aes_encrypt",
"(",
"modes",
".",
"CTR",
",",
"aes_key",
",",
"aes_iv",
",",
"data",
",",
"signed",
")",
"log_binary",
"(",
"_LOGGER",
",",
"'Signature'",
",",
"Signature",
"=",
"signature",
")",
"# Signature is prepended with 0x00000000 (alignment?)",
"return",
"b'\\x00\\x00\\x00\\x00'",
"+",
"signature"
] |
Last device verification step.
|
[
"Last",
"device",
"verification",
"step",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/srp.py#L114-L137
|
15,356
|
postlund/pyatv
|
pyatv/airplay/srp.py
|
SRPAuthHandler.step1
|
def step1(self, username, password):
"""First authentication step."""
self._check_initialized()
context = AtvSRPContext(
str(username), str(password),
prime=constants.PRIME_2048,
generator=constants.PRIME_2048_GEN)
self.session = SRPClientSession(
context, binascii.hexlify(self._auth_private).decode())
|
python
|
def step1(self, username, password):
"""First authentication step."""
self._check_initialized()
context = AtvSRPContext(
str(username), str(password),
prime=constants.PRIME_2048,
generator=constants.PRIME_2048_GEN)
self.session = SRPClientSession(
context, binascii.hexlify(self._auth_private).decode())
|
[
"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",
"=",
"SRPClientSession",
"(",
"context",
",",
"binascii",
".",
"hexlify",
"(",
"self",
".",
"_auth_private",
")",
".",
"decode",
"(",
")",
")"
] |
First authentication step.
|
[
"First",
"authentication",
"step",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/srp.py#L139-L147
|
15,357
|
postlund/pyatv
|
pyatv/airplay/srp.py
|
SRPAuthHandler.step2
|
def step2(self, pub_key, salt):
"""Second authentication step."""
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('Client session key: %s', self.client_session_key)
# Generate client public and session key proof.
client_public = self.session.public
client_session_key_proof = self.session.key_proof
_LOGGER.debug('Client public: %s, proof: %s',
client_public, client_session_key_proof)
if not self.session.verify_proof(self.session.key_proof_hash):
raise AuthenticationError('proofs do not match (mitm?)')
return client_public, client_session_key_proof
|
python
|
def step2(self, pub_key, salt):
"""Second authentication step."""
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('Client session key: %s', self.client_session_key)
# Generate client public and session key proof.
client_public = self.session.public
client_session_key_proof = self.session.key_proof
_LOGGER.debug('Client public: %s, proof: %s',
client_public, client_session_key_proof)
if not self.session.verify_proof(self.session.key_proof_hash):
raise AuthenticationError('proofs do not match (mitm?)')
return client_public, client_session_key_proof
|
[
"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",
"(",
"'Client session key: %s'",
",",
"self",
".",
"client_session_key",
")",
"# Generate client public and session key proof.",
"client_public",
"=",
"self",
".",
"session",
".",
"public",
"client_session_key_proof",
"=",
"self",
".",
"session",
".",
"key_proof",
"_LOGGER",
".",
"debug",
"(",
"'Client public: %s, proof: %s'",
",",
"client_public",
",",
"client_session_key_proof",
")",
"if",
"not",
"self",
".",
"session",
".",
"verify_proof",
"(",
"self",
".",
"session",
".",
"key_proof_hash",
")",
":",
"raise",
"AuthenticationError",
"(",
"'proofs do not match (mitm?)'",
")",
"return",
"client_public",
",",
"client_session_key_proof"
] |
Second authentication step.
|
[
"Second",
"authentication",
"step",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/srp.py#L149-L165
|
15,358
|
postlund/pyatv
|
pyatv/airplay/srp.py
|
SRPAuthHandler.step3
|
def step3(self):
"""Last authentication step."""
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:16]
tmp = bytearray(hash_sha512('Pair-Setup-AES-IV', session_key)[0:16])
tmp[-1] = tmp[-1] + 1 # Last byte must be increased by 1
aes_iv = bytes(tmp)
log_binary(_LOGGER, 'Pair-Setup-AES', Key=aes_key, IV=aes_iv)
epk, tag = aes_encrypt(modes.GCM, aes_key, aes_iv, self._auth_public)
log_binary(_LOGGER, 'Pair-Setup EPK+Tag', EPK=epk, Tag=tag)
return epk, tag
|
python
|
def step3(self):
"""Last authentication step."""
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:16]
tmp = bytearray(hash_sha512('Pair-Setup-AES-IV', session_key)[0:16])
tmp[-1] = tmp[-1] + 1 # Last byte must be increased by 1
aes_iv = bytes(tmp)
log_binary(_LOGGER, 'Pair-Setup-AES', Key=aes_key, IV=aes_iv)
epk, tag = aes_encrypt(modes.GCM, aes_key, aes_iv, self._auth_public)
log_binary(_LOGGER, 'Pair-Setup EPK+Tag', EPK=epk, Tag=tag)
return epk, tag
|
[
"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",
":",
"16",
"]",
"tmp",
"=",
"bytearray",
"(",
"hash_sha512",
"(",
"'Pair-Setup-AES-IV'",
",",
"session_key",
")",
"[",
"0",
":",
"16",
"]",
")",
"tmp",
"[",
"-",
"1",
"]",
"=",
"tmp",
"[",
"-",
"1",
"]",
"+",
"1",
"# Last byte must be increased by 1",
"aes_iv",
"=",
"bytes",
"(",
"tmp",
")",
"log_binary",
"(",
"_LOGGER",
",",
"'Pair-Setup-AES'",
",",
"Key",
"=",
"aes_key",
",",
"IV",
"=",
"aes_iv",
")",
"epk",
",",
"tag",
"=",
"aes_encrypt",
"(",
"modes",
".",
"GCM",
",",
"aes_key",
",",
"aes_iv",
",",
"self",
".",
"_auth_public",
")",
"log_binary",
"(",
"_LOGGER",
",",
"'Pair-Setup EPK+Tag'",
",",
"EPK",
"=",
"epk",
",",
"Tag",
"=",
"tag",
")",
"return",
"epk",
",",
"tag"
] |
Last authentication step.
|
[
"Last",
"authentication",
"step",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/srp.py#L167-L182
|
15,359
|
postlund/pyatv
|
pyatv/airplay/auth.py
|
DeviceAuthenticator.start_authentication
|
async def start_authentication(self):
"""Start the authentication process.
This method will show the expected PIN on screen.
"""
_, code = await self.http.post_data(
'pair-pin-start', headers=_AIRPLAY_HEADERS)
if code != 200:
raise DeviceAuthenticationError('pair start failed')
|
python
|
async def start_authentication(self):
"""Start the authentication process.
This method will show the expected PIN on screen.
"""
_, code = await self.http.post_data(
'pair-pin-start', headers=_AIRPLAY_HEADERS)
if code != 200:
raise DeviceAuthenticationError('pair start failed')
|
[
"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.
This method will show the expected PIN on screen.
|
[
"Start",
"the",
"authentication",
"process",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/auth.py#L26-L34
|
15,360
|
postlund/pyatv
|
pyatv/airplay/auth.py
|
DeviceAuthenticator.finish_authentication
|
async def finish_authentication(self, username, password):
"""Finish authentication process.
A username (generated by new_credentials) and the PIN code shown on
screen must be provided.
"""
# Step 1
self.srp.step1(username, password)
data = await self._send_plist(
'step1', method='pin', user=username)
resp = plistlib.loads(data)
# Step 2
pub_key, key_proof = self.srp.step2(resp['pk'], resp['salt'])
await self._send_plist(
'step2',
pk=binascii.unhexlify(pub_key),
proof=binascii.unhexlify(key_proof))
# Step 3
epk, tag = self.srp.step3()
await self._send_plist('step3', epk=epk, authTag=tag)
return True
|
python
|
async def finish_authentication(self, username, password):
"""Finish authentication process.
A username (generated by new_credentials) and the PIN code shown on
screen must be provided.
"""
# Step 1
self.srp.step1(username, password)
data = await self._send_plist(
'step1', method='pin', user=username)
resp = plistlib.loads(data)
# Step 2
pub_key, key_proof = self.srp.step2(resp['pk'], resp['salt'])
await self._send_plist(
'step2',
pk=binascii.unhexlify(pub_key),
proof=binascii.unhexlify(key_proof))
# Step 3
epk, tag = self.srp.step3()
await self._send_plist('step3', epk=epk, authTag=tag)
return True
|
[
"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",
"pub_key",
",",
"key_proof",
"=",
"self",
".",
"srp",
".",
"step2",
"(",
"resp",
"[",
"'pk'",
"]",
",",
"resp",
"[",
"'salt'",
"]",
")",
"await",
"self",
".",
"_send_plist",
"(",
"'step2'",
",",
"pk",
"=",
"binascii",
".",
"unhexlify",
"(",
"pub_key",
")",
",",
"proof",
"=",
"binascii",
".",
"unhexlify",
"(",
"key_proof",
")",
")",
"# Step 3",
"epk",
",",
"tag",
"=",
"self",
".",
"srp",
".",
"step3",
"(",
")",
"await",
"self",
".",
"_send_plist",
"(",
"'step3'",
",",
"epk",
"=",
"epk",
",",
"authTag",
"=",
"tag",
")",
"return",
"True"
] |
Finish authentication process.
A username (generated by new_credentials) and the PIN code shown on
screen must be provided.
|
[
"Finish",
"authentication",
"process",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/auth.py#L36-L58
|
15,361
|
postlund/pyatv
|
pyatv/airplay/auth.py
|
AuthenticationVerifier.verify_authed
|
async def verify_authed(self):
"""Verify if device is allowed to use AirPlau."""
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), 'verify2')
return True
|
python
|
async def verify_authed(self):
"""Verify if device is allowed to use AirPlau."""
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), 'verify2')
return True
|
[
"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",
")",
",",
"'verify2'",
")",
"return",
"True"
] |
Verify if device is allowed to use AirPlau.
|
[
"Verify",
"if",
"device",
"is",
"allowed",
"to",
"use",
"AirPlau",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/auth.py#L86-L94
|
15,362
|
postlund/pyatv
|
pyatv/airplay/api.py
|
AirPlayAPI.generate_credentials
|
async def generate_credentials(self):
"""Create new credentials for authentication.
Credentials that have been authenticated shall be saved and loaded with
load_credentials before playing anything. If credentials are lost,
authentication must be performed again.
"""
identifier, seed = new_credentials()
return '{0}:{1}'.format(identifier, seed.decode().upper())
|
python
|
async def generate_credentials(self):
"""Create new credentials for authentication.
Credentials that have been authenticated shall be saved and loaded with
load_credentials before playing anything. If credentials are lost,
authentication must be performed again.
"""
identifier, seed = new_credentials()
return '{0}:{1}'.format(identifier, seed.decode().upper())
|
[
"async",
"def",
"generate_credentials",
"(",
"self",
")",
":",
"identifier",
",",
"seed",
"=",
"new_credentials",
"(",
")",
"return",
"'{0}:{1}'",
".",
"format",
"(",
"identifier",
",",
"seed",
".",
"decode",
"(",
")",
".",
"upper",
"(",
")",
")"
] |
Create new credentials for authentication.
Credentials that have been authenticated shall be saved and loaded with
load_credentials before playing anything. If credentials are lost,
authentication must be performed again.
|
[
"Create",
"new",
"credentials",
"for",
"authentication",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/api.py#L25-L33
|
15,363
|
postlund/pyatv
|
pyatv/airplay/api.py
|
AirPlayAPI.load_credentials
|
async def load_credentials(self, credentials):
"""Load existing credentials."""
split = credentials.split(':')
self.identifier = split[0]
self.srp.initialize(binascii.unhexlify(split[1]))
_LOGGER.debug('Loaded AirPlay credentials: %s', credentials)
|
python
|
async def load_credentials(self, credentials):
"""Load existing credentials."""
split = credentials.split(':')
self.identifier = split[0]
self.srp.initialize(binascii.unhexlify(split[1]))
_LOGGER.debug('Loaded AirPlay credentials: %s', credentials)
|
[
"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.
|
[
"Load",
"existing",
"credentials",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/api.py#L35-L40
|
15,364
|
postlund/pyatv
|
pyatv/mrp/connection.py
|
MrpConnection.enable_encryption
|
def enable_encryption(self, output_key, input_key):
"""Enable encryption with the specified keys."""
self._chacha = chacha20.Chacha20Cipher(output_key, input_key)
|
python
|
def enable_encryption(self, output_key, input_key):
"""Enable encryption with the specified keys."""
self._chacha = chacha20.Chacha20Cipher(output_key, input_key)
|
[
"def",
"enable_encryption",
"(",
"self",
",",
"output_key",
",",
"input_key",
")",
":",
"self",
".",
"_chacha",
"=",
"chacha20",
".",
"Chacha20Cipher",
"(",
"output_key",
",",
"input_key",
")"
] |
Enable encryption with the specified keys.
|
[
"Enable",
"encryption",
"with",
"the",
"specified",
"keys",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/connection.py#L37-L39
|
15,365
|
postlund/pyatv
|
pyatv/mrp/connection.py
|
MrpConnection.connect
|
def connect(self):
"""Connect to device."""
return self.loop.create_connection(lambda: self, self.host, self.port)
|
python
|
def connect(self):
"""Connect to device."""
return self.loop.create_connection(lambda: self, self.host, self.port)
|
[
"def",
"connect",
"(",
"self",
")",
":",
"return",
"self",
".",
"loop",
".",
"create_connection",
"(",
"lambda",
":",
"self",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
")"
] |
Connect to device.
|
[
"Connect",
"to",
"device",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/connection.py#L46-L48
|
15,366
|
postlund/pyatv
|
pyatv/mrp/connection.py
|
MrpConnection.close
|
def close(self):
"""Close connection to device."""
if self._transport:
self._transport.close()
self._transport = None
self._chacha = None
|
python
|
def close(self):
"""Close connection to device."""
if self._transport:
self._transport.close()
self._transport = None
self._chacha = None
|
[
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_transport",
":",
"self",
".",
"_transport",
".",
"close",
"(",
")",
"self",
".",
"_transport",
"=",
"None",
"self",
".",
"_chacha",
"=",
"None"
] |
Close connection to device.
|
[
"Close",
"connection",
"to",
"device",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/connection.py#L50-L55
|
15,367
|
postlund/pyatv
|
pyatv/mrp/connection.py
|
MrpConnection.send
|
def send(self, message):
"""Send message to device."""
serialized = message.SerializeToString()
log_binary(_LOGGER, '>> Send', Data=serialized)
if self._chacha:
serialized = self._chacha.encrypt(serialized)
log_binary(_LOGGER, '>> Send', Encrypted=serialized)
data = write_variant(len(serialized)) + serialized
self._transport.write(data)
_LOGGER.debug('>> Send: Protobuf=%s', message)
|
python
|
def send(self, message):
"""Send message to device."""
serialized = message.SerializeToString()
log_binary(_LOGGER, '>> Send', Data=serialized)
if self._chacha:
serialized = self._chacha.encrypt(serialized)
log_binary(_LOGGER, '>> Send', Encrypted=serialized)
data = write_variant(len(serialized)) + serialized
self._transport.write(data)
_LOGGER.debug('>> Send: Protobuf=%s', message)
|
[
"def",
"send",
"(",
"self",
",",
"message",
")",
":",
"serialized",
"=",
"message",
".",
"SerializeToString",
"(",
")",
"log_binary",
"(",
"_LOGGER",
",",
"'>> Send'",
",",
"Data",
"=",
"serialized",
")",
"if",
"self",
".",
"_chacha",
":",
"serialized",
"=",
"self",
".",
"_chacha",
".",
"encrypt",
"(",
"serialized",
")",
"log_binary",
"(",
"_LOGGER",
",",
"'>> Send'",
",",
"Encrypted",
"=",
"serialized",
")",
"data",
"=",
"write_variant",
"(",
"len",
"(",
"serialized",
")",
")",
"+",
"serialized",
"self",
".",
"_transport",
".",
"write",
"(",
"data",
")",
"_LOGGER",
".",
"debug",
"(",
"'>> Send: Protobuf=%s'",
",",
"message",
")"
] |
Send message to device.
|
[
"Send",
"message",
"to",
"device",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/connection.py#L57-L68
|
15,368
|
postlund/pyatv
|
pyatv/net.py
|
HttpSession.get_data
|
async def get_data(self, path, headers=None, timeout=None):
"""Perform a GET request."""
url = self.base_url + path
_LOGGER.debug('GET URL: %s', url)
resp = None
try:
resp = await self._session.get(
url, headers=headers,
timeout=DEFAULT_TIMEOUT if timeout is None else timeout)
if resp.content_length is not None:
resp_data = await resp.read()
else:
resp_data = None
return resp_data, resp.status
except Exception as ex:
if resp is not None:
resp.close()
raise ex
finally:
if resp is not None:
await resp.release()
|
python
|
async def get_data(self, path, headers=None, timeout=None):
"""Perform a GET request."""
url = self.base_url + path
_LOGGER.debug('GET URL: %s', url)
resp = None
try:
resp = await self._session.get(
url, headers=headers,
timeout=DEFAULT_TIMEOUT if timeout is None else timeout)
if resp.content_length is not None:
resp_data = await resp.read()
else:
resp_data = None
return resp_data, resp.status
except Exception as ex:
if resp is not None:
resp.close()
raise ex
finally:
if resp is not None:
await resp.release()
|
[
"async",
"def",
"get_data",
"(",
"self",
",",
"path",
",",
"headers",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"path",
"_LOGGER",
".",
"debug",
"(",
"'GET URL: %s'",
",",
"url",
")",
"resp",
"=",
"None",
"try",
":",
"resp",
"=",
"await",
"self",
".",
"_session",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
"if",
"timeout",
"is",
"None",
"else",
"timeout",
")",
"if",
"resp",
".",
"content_length",
"is",
"not",
"None",
":",
"resp_data",
"=",
"await",
"resp",
".",
"read",
"(",
")",
"else",
":",
"resp_data",
"=",
"None",
"return",
"resp_data",
",",
"resp",
".",
"status",
"except",
"Exception",
"as",
"ex",
":",
"if",
"resp",
"is",
"not",
"None",
":",
"resp",
".",
"close",
"(",
")",
"raise",
"ex",
"finally",
":",
"if",
"resp",
"is",
"not",
"None",
":",
"await",
"resp",
".",
"release",
"(",
")"
] |
Perform a GET request.
|
[
"Perform",
"a",
"GET",
"request",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/net.py#L20-L40
|
15,369
|
postlund/pyatv
|
pyatv/net.py
|
HttpSession.post_data
|
async def post_data(self, path, data=None, headers=None, timeout=None):
"""Perform a POST request."""
url = self.base_url + path
_LOGGER.debug('POST URL: %s', url)
self._log_data(data, False)
resp = None
try:
resp = await self._session.post(
url, headers=headers, data=data,
timeout=DEFAULT_TIMEOUT if timeout is None else timeout)
if resp.content_length is not None:
resp_data = await resp.read()
else:
resp_data = None
self._log_data(resp_data, True)
return resp_data, resp.status
except Exception as ex:
if resp is not None:
resp.close()
raise ex
finally:
if resp is not None:
await resp.release()
|
python
|
async def post_data(self, path, data=None, headers=None, timeout=None):
"""Perform a POST request."""
url = self.base_url + path
_LOGGER.debug('POST URL: %s', url)
self._log_data(data, False)
resp = None
try:
resp = await self._session.post(
url, headers=headers, data=data,
timeout=DEFAULT_TIMEOUT if timeout is None else timeout)
if resp.content_length is not None:
resp_data = await resp.read()
else:
resp_data = None
self._log_data(resp_data, True)
return resp_data, resp.status
except Exception as ex:
if resp is not None:
resp.close()
raise ex
finally:
if resp is not None:
await resp.release()
|
[
"async",
"def",
"post_data",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"path",
"_LOGGER",
".",
"debug",
"(",
"'POST URL: %s'",
",",
"url",
")",
"self",
".",
"_log_data",
"(",
"data",
",",
"False",
")",
"resp",
"=",
"None",
"try",
":",
"resp",
"=",
"await",
"self",
".",
"_session",
".",
"post",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"data",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
"if",
"timeout",
"is",
"None",
"else",
"timeout",
")",
"if",
"resp",
".",
"content_length",
"is",
"not",
"None",
":",
"resp_data",
"=",
"await",
"resp",
".",
"read",
"(",
")",
"else",
":",
"resp_data",
"=",
"None",
"self",
".",
"_log_data",
"(",
"resp_data",
",",
"True",
")",
"return",
"resp_data",
",",
"resp",
".",
"status",
"except",
"Exception",
"as",
"ex",
":",
"if",
"resp",
"is",
"not",
"None",
":",
"resp",
".",
"close",
"(",
")",
"raise",
"ex",
"finally",
":",
"if",
"resp",
"is",
"not",
"None",
":",
"await",
"resp",
".",
"release",
"(",
")"
] |
Perform a POST request.
|
[
"Perform",
"a",
"POST",
"request",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/net.py#L42-L65
|
15,370
|
postlund/pyatv
|
pyatv/dmap/tags.py
|
read_uint
|
def read_uint(data, start, length):
"""Extract a uint from a position in a sequence."""
return int.from_bytes(data[start:start+length], byteorder='big')
|
python
|
def read_uint(data, start, length):
"""Extract a uint from a position in a sequence."""
return int.from_bytes(data[start:start+length], byteorder='big')
|
[
"def",
"read_uint",
"(",
"data",
",",
"start",
",",
"length",
")",
":",
"return",
"int",
".",
"from_bytes",
"(",
"data",
"[",
"start",
":",
"start",
"+",
"length",
"]",
",",
"byteorder",
"=",
"'big'",
")"
] |
Extract a uint from a position in a sequence.
|
[
"Extract",
"a",
"uint",
"from",
"a",
"position",
"in",
"a",
"sequence",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/tags.py#L11-L13
|
15,371
|
postlund/pyatv
|
pyatv/dmap/tags.py
|
read_bplist
|
def read_bplist(data, start, length):
"""Extract a binary plist from a position in a sequence."""
# TODO: pylint doesn't find FMT_BINARY, why?
# pylint: disable=no-member
return plistlib.loads(data[start:start+length],
fmt=plistlib.FMT_BINARY)
|
python
|
def read_bplist(data, start, length):
"""Extract a binary plist from a position in a sequence."""
# TODO: pylint doesn't find FMT_BINARY, why?
# pylint: disable=no-member
return plistlib.loads(data[start:start+length],
fmt=plistlib.FMT_BINARY)
|
[
"def",
"read_bplist",
"(",
"data",
",",
"start",
",",
"length",
")",
":",
"# TODO: pylint doesn't find FMT_BINARY, why?",
"# pylint: disable=no-member",
"return",
"plistlib",
".",
"loads",
"(",
"data",
"[",
"start",
":",
"start",
"+",
"length",
"]",
",",
"fmt",
"=",
"plistlib",
".",
"FMT_BINARY",
")"
] |
Extract a binary plist from a position in a sequence.
|
[
"Extract",
"a",
"binary",
"plist",
"from",
"a",
"position",
"in",
"a",
"sequence",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/tags.py#L21-L26
|
15,372
|
postlund/pyatv
|
pyatv/dmap/tags.py
|
raw_tag
|
def raw_tag(name, value):
"""Create a DMAP tag with raw data."""
return name.encode('utf-8') + \
len(value).to_bytes(4, byteorder='big') + \
value
|
python
|
def raw_tag(name, value):
"""Create a DMAP tag with raw data."""
return name.encode('utf-8') + \
len(value).to_bytes(4, byteorder='big') + \
value
|
[
"def",
"raw_tag",
"(",
"name",
",",
"value",
")",
":",
"return",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
"+",
"len",
"(",
"value",
")",
".",
"to_bytes",
"(",
"4",
",",
"byteorder",
"=",
"'big'",
")",
"+",
"value"
] |
Create a DMAP tag with raw data.
|
[
"Create",
"a",
"DMAP",
"tag",
"with",
"raw",
"data",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/tags.py#L69-L73
|
15,373
|
postlund/pyatv
|
pyatv/dmap/tags.py
|
string_tag
|
def string_tag(name, value):
"""Create a DMAP tag with string data."""
return name.encode('utf-8') + \
len(value).to_bytes(4, byteorder='big') + \
value.encode('utf-8')
|
python
|
def string_tag(name, value):
"""Create a DMAP tag with string data."""
return name.encode('utf-8') + \
len(value).to_bytes(4, byteorder='big') + \
value.encode('utf-8')
|
[
"def",
"string_tag",
"(",
"name",
",",
"value",
")",
":",
"return",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
"+",
"len",
"(",
"value",
")",
".",
"to_bytes",
"(",
"4",
",",
"byteorder",
"=",
"'big'",
")",
"+",
"value",
".",
"encode",
"(",
"'utf-8'",
")"
] |
Create a DMAP tag with string data.
|
[
"Create",
"a",
"DMAP",
"tag",
"with",
"string",
"data",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/tags.py#L76-L80
|
15,374
|
postlund/pyatv
|
pyatv/mrp/messages.py
|
create
|
def create(message_type, priority=0):
"""Create a ProtocolMessage."""
message = protobuf.ProtocolMessage()
message.type = message_type
message.priority = priority
return message
|
python
|
def create(message_type, priority=0):
"""Create a ProtocolMessage."""
message = protobuf.ProtocolMessage()
message.type = message_type
message.priority = priority
return message
|
[
"def",
"create",
"(",
"message_type",
",",
"priority",
"=",
"0",
")",
":",
"message",
"=",
"protobuf",
".",
"ProtocolMessage",
"(",
")",
"message",
".",
"type",
"=",
"message_type",
"message",
".",
"priority",
"=",
"priority",
"return",
"message"
] |
Create a ProtocolMessage.
|
[
"Create",
"a",
"ProtocolMessage",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L9-L14
|
15,375
|
postlund/pyatv
|
pyatv/mrp/messages.py
|
device_information
|
def device_information(name, identifier):
"""Create a new DEVICE_INFO_MESSAGE."""
# pylint: disable=no-member
message = create(protobuf.DEVICE_INFO_MESSAGE)
info = message.inner()
info.uniqueIdentifier = identifier
info.name = name
info.localizedModelName = 'iPhone'
info.systemBuildVersion = '14G60'
info.applicationBundleIdentifier = 'com.apple.TVRemote'
info.applicationBundleVersion = '273.12'
info.protocolVersion = 1
info.lastSupportedMessageType = 58
info.supportsExtendedMotion = True
return message
|
python
|
def device_information(name, identifier):
"""Create a new DEVICE_INFO_MESSAGE."""
# pylint: disable=no-member
message = create(protobuf.DEVICE_INFO_MESSAGE)
info = message.inner()
info.uniqueIdentifier = identifier
info.name = name
info.localizedModelName = 'iPhone'
info.systemBuildVersion = '14G60'
info.applicationBundleIdentifier = 'com.apple.TVRemote'
info.applicationBundleVersion = '273.12'
info.protocolVersion = 1
info.lastSupportedMessageType = 58
info.supportsExtendedMotion = True
return message
|
[
"def",
"device_information",
"(",
"name",
",",
"identifier",
")",
":",
"# pylint: disable=no-member",
"message",
"=",
"create",
"(",
"protobuf",
".",
"DEVICE_INFO_MESSAGE",
")",
"info",
"=",
"message",
".",
"inner",
"(",
")",
"info",
".",
"uniqueIdentifier",
"=",
"identifier",
"info",
".",
"name",
"=",
"name",
"info",
".",
"localizedModelName",
"=",
"'iPhone'",
"info",
".",
"systemBuildVersion",
"=",
"'14G60'",
"info",
".",
"applicationBundleIdentifier",
"=",
"'com.apple.TVRemote'",
"info",
".",
"applicationBundleVersion",
"=",
"'273.12'",
"info",
".",
"protocolVersion",
"=",
"1",
"info",
".",
"lastSupportedMessageType",
"=",
"58",
"info",
".",
"supportsExtendedMotion",
"=",
"True",
"return",
"message"
] |
Create a new DEVICE_INFO_MESSAGE.
|
[
"Create",
"a",
"new",
"DEVICE_INFO_MESSAGE",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L18-L32
|
15,376
|
postlund/pyatv
|
pyatv/mrp/messages.py
|
set_connection_state
|
def set_connection_state():
"""Create a new SET_CONNECTION_STATE."""
message = create(protobuf.ProtocolMessage.SET_CONNECTION_STATE_MESSAGE)
message.inner().state = protobuf.SetConnectionStateMessage.Connected
return message
|
python
|
def set_connection_state():
"""Create a new SET_CONNECTION_STATE."""
message = create(protobuf.ProtocolMessage.SET_CONNECTION_STATE_MESSAGE)
message.inner().state = protobuf.SetConnectionStateMessage.Connected
return message
|
[
"def",
"set_connection_state",
"(",
")",
":",
"message",
"=",
"create",
"(",
"protobuf",
".",
"ProtocolMessage",
".",
"SET_CONNECTION_STATE_MESSAGE",
")",
"message",
".",
"inner",
"(",
")",
".",
"state",
"=",
"protobuf",
".",
"SetConnectionStateMessage",
".",
"Connected",
"return",
"message"
] |
Create a new SET_CONNECTION_STATE.
|
[
"Create",
"a",
"new",
"SET_CONNECTION_STATE",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L40-L44
|
15,377
|
postlund/pyatv
|
pyatv/mrp/messages.py
|
crypto_pairing
|
def crypto_pairing(pairing_data):
"""Create a new CRYPTO_PAIRING_MESSAGE."""
message = create(protobuf.CRYPTO_PAIRING_MESSAGE)
crypto = message.inner()
crypto.status = 0
crypto.pairingData = tlv8.write_tlv(pairing_data)
return message
|
python
|
def crypto_pairing(pairing_data):
"""Create a new CRYPTO_PAIRING_MESSAGE."""
message = create(protobuf.CRYPTO_PAIRING_MESSAGE)
crypto = message.inner()
crypto.status = 0
crypto.pairingData = tlv8.write_tlv(pairing_data)
return message
|
[
"def",
"crypto_pairing",
"(",
"pairing_data",
")",
":",
"message",
"=",
"create",
"(",
"protobuf",
".",
"CRYPTO_PAIRING_MESSAGE",
")",
"crypto",
"=",
"message",
".",
"inner",
"(",
")",
"crypto",
".",
"status",
"=",
"0",
"crypto",
".",
"pairingData",
"=",
"tlv8",
".",
"write_tlv",
"(",
"pairing_data",
")",
"return",
"message"
] |
Create a new CRYPTO_PAIRING_MESSAGE.
|
[
"Create",
"a",
"new",
"CRYPTO_PAIRING_MESSAGE",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L47-L53
|
15,378
|
postlund/pyatv
|
pyatv/mrp/messages.py
|
client_updates_config
|
def client_updates_config(artwork=True, now_playing=True,
volume=True, keyboard=True):
"""Create a new CLIENT_UPDATES_CONFIG_MESSAGE."""
message = create(protobuf.CLIENT_UPDATES_CONFIG_MESSAGE)
config = message.inner()
config.artworkUpdates = artwork
config.nowPlayingUpdates = now_playing
config.volumeUpdates = volume
config.keyboardUpdates = keyboard
return message
|
python
|
def client_updates_config(artwork=True, now_playing=True,
volume=True, keyboard=True):
"""Create a new CLIENT_UPDATES_CONFIG_MESSAGE."""
message = create(protobuf.CLIENT_UPDATES_CONFIG_MESSAGE)
config = message.inner()
config.artworkUpdates = artwork
config.nowPlayingUpdates = now_playing
config.volumeUpdates = volume
config.keyboardUpdates = keyboard
return message
|
[
"def",
"client_updates_config",
"(",
"artwork",
"=",
"True",
",",
"now_playing",
"=",
"True",
",",
"volume",
"=",
"True",
",",
"keyboard",
"=",
"True",
")",
":",
"message",
"=",
"create",
"(",
"protobuf",
".",
"CLIENT_UPDATES_CONFIG_MESSAGE",
")",
"config",
"=",
"message",
".",
"inner",
"(",
")",
"config",
".",
"artworkUpdates",
"=",
"artwork",
"config",
".",
"nowPlayingUpdates",
"=",
"now_playing",
"config",
".",
"volumeUpdates",
"=",
"volume",
"config",
".",
"keyboardUpdates",
"=",
"keyboard",
"return",
"message"
] |
Create a new CLIENT_UPDATES_CONFIG_MESSAGE.
|
[
"Create",
"a",
"new",
"CLIENT_UPDATES_CONFIG_MESSAGE",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L56-L65
|
15,379
|
postlund/pyatv
|
pyatv/mrp/messages.py
|
register_hid_device
|
def register_hid_device(screen_width, screen_height,
absolute=False, integrated_display=False):
"""Create a new REGISTER_HID_DEVICE_MESSAGE."""
message = create(protobuf.REGISTER_HID_DEVICE_MESSAGE)
descriptor = message.inner().deviceDescriptor
descriptor.absolute = 1 if absolute else 0
descriptor.integratedDisplay = 1 if integrated_display else 0
descriptor.screenSizeWidth = screen_width
descriptor.screenSizeHeight = screen_height
return message
|
python
|
def register_hid_device(screen_width, screen_height,
absolute=False, integrated_display=False):
"""Create a new REGISTER_HID_DEVICE_MESSAGE."""
message = create(protobuf.REGISTER_HID_DEVICE_MESSAGE)
descriptor = message.inner().deviceDescriptor
descriptor.absolute = 1 if absolute else 0
descriptor.integratedDisplay = 1 if integrated_display else 0
descriptor.screenSizeWidth = screen_width
descriptor.screenSizeHeight = screen_height
return message
|
[
"def",
"register_hid_device",
"(",
"screen_width",
",",
"screen_height",
",",
"absolute",
"=",
"False",
",",
"integrated_display",
"=",
"False",
")",
":",
"message",
"=",
"create",
"(",
"protobuf",
".",
"REGISTER_HID_DEVICE_MESSAGE",
")",
"descriptor",
"=",
"message",
".",
"inner",
"(",
")",
".",
"deviceDescriptor",
"descriptor",
".",
"absolute",
"=",
"1",
"if",
"absolute",
"else",
"0",
"descriptor",
".",
"integratedDisplay",
"=",
"1",
"if",
"integrated_display",
"else",
"0",
"descriptor",
".",
"screenSizeWidth",
"=",
"screen_width",
"descriptor",
".",
"screenSizeHeight",
"=",
"screen_height",
"return",
"message"
] |
Create a new REGISTER_HID_DEVICE_MESSAGE.
|
[
"Create",
"a",
"new",
"REGISTER_HID_DEVICE_MESSAGE",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L73-L82
|
15,380
|
postlund/pyatv
|
pyatv/mrp/messages.py
|
send_packed_virtual_touch_event
|
def send_packed_virtual_touch_event(xpos, ypos, phase, device_id, finger):
"""Create a new WAKE_DEVICE_MESSAGE."""
message = create(protobuf.SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE)
event = message.inner()
# The packed version of VirtualTouchEvent contains X, Y, phase, deviceID
# and finger stored as a byte array. Each value is written as 16bit little
# endian integers.
event.data = xpos.to_bytes(2, byteorder='little')
event.data += ypos.to_bytes(2, byteorder='little')
event.data += phase.to_bytes(2, byteorder='little')
event.data += device_id.to_bytes(2, byteorder='little')
event.data += finger.to_bytes(2, byteorder='little')
return message
|
python
|
def send_packed_virtual_touch_event(xpos, ypos, phase, device_id, finger):
"""Create a new WAKE_DEVICE_MESSAGE."""
message = create(protobuf.SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE)
event = message.inner()
# The packed version of VirtualTouchEvent contains X, Y, phase, deviceID
# and finger stored as a byte array. Each value is written as 16bit little
# endian integers.
event.data = xpos.to_bytes(2, byteorder='little')
event.data += ypos.to_bytes(2, byteorder='little')
event.data += phase.to_bytes(2, byteorder='little')
event.data += device_id.to_bytes(2, byteorder='little')
event.data += finger.to_bytes(2, byteorder='little')
return message
|
[
"def",
"send_packed_virtual_touch_event",
"(",
"xpos",
",",
"ypos",
",",
"phase",
",",
"device_id",
",",
"finger",
")",
":",
"message",
"=",
"create",
"(",
"protobuf",
".",
"SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE",
")",
"event",
"=",
"message",
".",
"inner",
"(",
")",
"# The packed version of VirtualTouchEvent contains X, Y, phase, deviceID",
"# and finger stored as a byte array. Each value is written as 16bit little",
"# endian integers.",
"event",
".",
"data",
"=",
"xpos",
".",
"to_bytes",
"(",
"2",
",",
"byteorder",
"=",
"'little'",
")",
"event",
".",
"data",
"+=",
"ypos",
".",
"to_bytes",
"(",
"2",
",",
"byteorder",
"=",
"'little'",
")",
"event",
".",
"data",
"+=",
"phase",
".",
"to_bytes",
"(",
"2",
",",
"byteorder",
"=",
"'little'",
")",
"event",
".",
"data",
"+=",
"device_id",
".",
"to_bytes",
"(",
"2",
",",
"byteorder",
"=",
"'little'",
")",
"event",
".",
"data",
"+=",
"finger",
".",
"to_bytes",
"(",
"2",
",",
"byteorder",
"=",
"'little'",
")",
"return",
"message"
] |
Create a new WAKE_DEVICE_MESSAGE.
|
[
"Create",
"a",
"new",
"WAKE_DEVICE_MESSAGE",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L85-L99
|
15,381
|
postlund/pyatv
|
pyatv/mrp/messages.py
|
send_hid_event
|
def send_hid_event(use_page, usage, down):
"""Create a new SEND_HID_EVENT_MESSAGE."""
message = create(protobuf.SEND_HID_EVENT_MESSAGE)
event = message.inner()
# TODO: This should be generated somehow. I guess it's mach AbsoluteTime
# which is tricky to generate. The device does not seem to care much about
# the value though, so hardcode something here.
abstime = binascii.unhexlify(b'438922cf08020000')
data = use_page.to_bytes(2, byteorder='big')
data += usage.to_bytes(2, byteorder='big')
data += (1 if down else 0).to_bytes(2, byteorder='big')
# This is the format that the device expects. Some day I might take some
# time to decode it for real, but this is fine for now.
event.hidEventData = abstime + \
binascii.unhexlify(b'00000000000000000100000000000000020' +
b'00000200000000300000001000000000000') + \
data + \
binascii.unhexlify(b'0000000000000001000000')
return message
|
python
|
def send_hid_event(use_page, usage, down):
"""Create a new SEND_HID_EVENT_MESSAGE."""
message = create(protobuf.SEND_HID_EVENT_MESSAGE)
event = message.inner()
# TODO: This should be generated somehow. I guess it's mach AbsoluteTime
# which is tricky to generate. The device does not seem to care much about
# the value though, so hardcode something here.
abstime = binascii.unhexlify(b'438922cf08020000')
data = use_page.to_bytes(2, byteorder='big')
data += usage.to_bytes(2, byteorder='big')
data += (1 if down else 0).to_bytes(2, byteorder='big')
# This is the format that the device expects. Some day I might take some
# time to decode it for real, but this is fine for now.
event.hidEventData = abstime + \
binascii.unhexlify(b'00000000000000000100000000000000020' +
b'00000200000000300000001000000000000') + \
data + \
binascii.unhexlify(b'0000000000000001000000')
return message
|
[
"def",
"send_hid_event",
"(",
"use_page",
",",
"usage",
",",
"down",
")",
":",
"message",
"=",
"create",
"(",
"protobuf",
".",
"SEND_HID_EVENT_MESSAGE",
")",
"event",
"=",
"message",
".",
"inner",
"(",
")",
"# TODO: This should be generated somehow. I guess it's mach AbsoluteTime",
"# which is tricky to generate. The device does not seem to care much about",
"# the value though, so hardcode something here.",
"abstime",
"=",
"binascii",
".",
"unhexlify",
"(",
"b'438922cf08020000'",
")",
"data",
"=",
"use_page",
".",
"to_bytes",
"(",
"2",
",",
"byteorder",
"=",
"'big'",
")",
"data",
"+=",
"usage",
".",
"to_bytes",
"(",
"2",
",",
"byteorder",
"=",
"'big'",
")",
"data",
"+=",
"(",
"1",
"if",
"down",
"else",
"0",
")",
".",
"to_bytes",
"(",
"2",
",",
"byteorder",
"=",
"'big'",
")",
"# This is the format that the device expects. Some day I might take some",
"# time to decode it for real, but this is fine for now.",
"event",
".",
"hidEventData",
"=",
"abstime",
"+",
"binascii",
".",
"unhexlify",
"(",
"b'00000000000000000100000000000000020'",
"+",
"b'00000200000000300000001000000000000'",
")",
"+",
"data",
"+",
"binascii",
".",
"unhexlify",
"(",
"b'0000000000000001000000'",
")",
"return",
"message"
] |
Create a new SEND_HID_EVENT_MESSAGE.
|
[
"Create",
"a",
"new",
"SEND_HID_EVENT_MESSAGE",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L102-L124
|
15,382
|
postlund/pyatv
|
pyatv/mrp/messages.py
|
command
|
def command(cmd):
"""Playback command request."""
message = create(protobuf.SEND_COMMAND_MESSAGE)
send_command = message.inner()
send_command.command = cmd
return message
|
python
|
def command(cmd):
"""Playback command request."""
message = create(protobuf.SEND_COMMAND_MESSAGE)
send_command = message.inner()
send_command.command = cmd
return message
|
[
"def",
"command",
"(",
"cmd",
")",
":",
"message",
"=",
"create",
"(",
"protobuf",
".",
"SEND_COMMAND_MESSAGE",
")",
"send_command",
"=",
"message",
".",
"inner",
"(",
")",
"send_command",
".",
"command",
"=",
"cmd",
"return",
"message"
] |
Playback command request.
|
[
"Playback",
"command",
"request",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L127-L132
|
15,383
|
postlund/pyatv
|
pyatv/mrp/messages.py
|
repeat
|
def repeat(mode):
"""Change repeat mode of current player."""
message = command(protobuf.CommandInfo_pb2.ChangeShuffleMode)
send_command = message.inner()
send_command.options.externalPlayerCommand = True
send_command.options.repeatMode = mode
return message
|
python
|
def repeat(mode):
"""Change repeat mode of current player."""
message = command(protobuf.CommandInfo_pb2.ChangeShuffleMode)
send_command = message.inner()
send_command.options.externalPlayerCommand = True
send_command.options.repeatMode = mode
return message
|
[
"def",
"repeat",
"(",
"mode",
")",
":",
"message",
"=",
"command",
"(",
"protobuf",
".",
"CommandInfo_pb2",
".",
"ChangeShuffleMode",
")",
"send_command",
"=",
"message",
".",
"inner",
"(",
")",
"send_command",
".",
"options",
".",
"externalPlayerCommand",
"=",
"True",
"send_command",
".",
"options",
".",
"repeatMode",
"=",
"mode",
"return",
"message"
] |
Change repeat mode of current player.
|
[
"Change",
"repeat",
"mode",
"of",
"current",
"player",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L135-L141
|
15,384
|
postlund/pyatv
|
pyatv/mrp/messages.py
|
shuffle
|
def shuffle(enable):
"""Change shuffle mode of current player."""
message = command(protobuf.CommandInfo_pb2.ChangeShuffleMode)
send_command = message.inner()
send_command.options.shuffleMode = 3 if enable else 1
return message
|
python
|
def shuffle(enable):
"""Change shuffle mode of current player."""
message = command(protobuf.CommandInfo_pb2.ChangeShuffleMode)
send_command = message.inner()
send_command.options.shuffleMode = 3 if enable else 1
return message
|
[
"def",
"shuffle",
"(",
"enable",
")",
":",
"message",
"=",
"command",
"(",
"protobuf",
".",
"CommandInfo_pb2",
".",
"ChangeShuffleMode",
")",
"send_command",
"=",
"message",
".",
"inner",
"(",
")",
"send_command",
".",
"options",
".",
"shuffleMode",
"=",
"3",
"if",
"enable",
"else",
"1",
"return",
"message"
] |
Change shuffle mode of current player.
|
[
"Change",
"shuffle",
"mode",
"of",
"current",
"player",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L144-L149
|
15,385
|
postlund/pyatv
|
pyatv/mrp/messages.py
|
seek_to_position
|
def seek_to_position(position):
"""Seek to an absolute position in stream."""
message = command(protobuf.CommandInfo_pb2.SeekToPlaybackPosition)
send_command = message.inner()
send_command.options.playbackPosition = position
return message
|
python
|
def seek_to_position(position):
"""Seek to an absolute position in stream."""
message = command(protobuf.CommandInfo_pb2.SeekToPlaybackPosition)
send_command = message.inner()
send_command.options.playbackPosition = position
return message
|
[
"def",
"seek_to_position",
"(",
"position",
")",
":",
"message",
"=",
"command",
"(",
"protobuf",
".",
"CommandInfo_pb2",
".",
"SeekToPlaybackPosition",
")",
"send_command",
"=",
"message",
".",
"inner",
"(",
")",
"send_command",
".",
"options",
".",
"playbackPosition",
"=",
"position",
"return",
"message"
] |
Seek to an absolute position in stream.
|
[
"Seek",
"to",
"an",
"absolute",
"position",
"in",
"stream",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/messages.py#L152-L157
|
15,386
|
postlund/pyatv
|
examples/pairing.py
|
pair_with_device
|
async def pair_with_device(loop):
"""Make it possible to pair with device."""
my_zeroconf = Zeroconf()
details = conf.AppleTV('127.0.0.1', 'Apple TV')
details.add_service(conf.DmapService('login_id'))
atv = pyatv.connect_to_apple_tv(details, loop)
atv.pairing.pin(PIN_CODE)
await atv.pairing.start(zeroconf=my_zeroconf, name=REMOTE_NAME)
print('You can now pair with pyatv')
# Wait for a minute to allow pairing
await asyncio.sleep(60, loop=loop)
await atv.pairing.stop()
# Give some feedback about the process
if atv.pairing.has_paired:
print('Paired with device!')
print('Credentials:', atv.pairing.credentials)
else:
print('Did not pair with device!')
my_zeroconf.close()
|
python
|
async def pair_with_device(loop):
"""Make it possible to pair with device."""
my_zeroconf = Zeroconf()
details = conf.AppleTV('127.0.0.1', 'Apple TV')
details.add_service(conf.DmapService('login_id'))
atv = pyatv.connect_to_apple_tv(details, loop)
atv.pairing.pin(PIN_CODE)
await atv.pairing.start(zeroconf=my_zeroconf, name=REMOTE_NAME)
print('You can now pair with pyatv')
# Wait for a minute to allow pairing
await asyncio.sleep(60, loop=loop)
await atv.pairing.stop()
# Give some feedback about the process
if atv.pairing.has_paired:
print('Paired with device!')
print('Credentials:', atv.pairing.credentials)
else:
print('Did not pair with device!')
my_zeroconf.close()
|
[
"async",
"def",
"pair_with_device",
"(",
"loop",
")",
":",
"my_zeroconf",
"=",
"Zeroconf",
"(",
")",
"details",
"=",
"conf",
".",
"AppleTV",
"(",
"'127.0.0.1'",
",",
"'Apple TV'",
")",
"details",
".",
"add_service",
"(",
"conf",
".",
"DmapService",
"(",
"'login_id'",
")",
")",
"atv",
"=",
"pyatv",
".",
"connect_to_apple_tv",
"(",
"details",
",",
"loop",
")",
"atv",
".",
"pairing",
".",
"pin",
"(",
"PIN_CODE",
")",
"await",
"atv",
".",
"pairing",
".",
"start",
"(",
"zeroconf",
"=",
"my_zeroconf",
",",
"name",
"=",
"REMOTE_NAME",
")",
"print",
"(",
"'You can now pair with pyatv'",
")",
"# Wait for a minute to allow pairing",
"await",
"asyncio",
".",
"sleep",
"(",
"60",
",",
"loop",
"=",
"loop",
")",
"await",
"atv",
".",
"pairing",
".",
"stop",
"(",
")",
"# Give some feedback about the process",
"if",
"atv",
".",
"pairing",
".",
"has_paired",
":",
"print",
"(",
"'Paired with device!'",
")",
"print",
"(",
"'Credentials:'",
",",
"atv",
".",
"pairing",
".",
"credentials",
")",
"else",
":",
"print",
"(",
"'Did not pair with device!'",
")",
"my_zeroconf",
".",
"close",
"(",
")"
] |
Make it possible to pair with device.
|
[
"Make",
"it",
"possible",
"to",
"pair",
"with",
"device",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/examples/pairing.py#L17-L40
|
15,387
|
postlund/pyatv
|
pyatv/mrp/variant.py
|
read_variant
|
def read_variant(variant):
"""Read and parse a binary protobuf variant value."""
result = 0
cnt = 0
for data in variant:
result |= (data & 0x7f) << (7 * cnt)
cnt += 1
if not data & 0x80:
return result, variant[cnt:]
raise Exception('invalid variant')
|
python
|
def read_variant(variant):
"""Read and parse a binary protobuf variant value."""
result = 0
cnt = 0
for data in variant:
result |= (data & 0x7f) << (7 * cnt)
cnt += 1
if not data & 0x80:
return result, variant[cnt:]
raise Exception('invalid variant')
|
[
"def",
"read_variant",
"(",
"variant",
")",
":",
"result",
"=",
"0",
"cnt",
"=",
"0",
"for",
"data",
"in",
"variant",
":",
"result",
"|=",
"(",
"data",
"&",
"0x7f",
")",
"<<",
"(",
"7",
"*",
"cnt",
")",
"cnt",
"+=",
"1",
"if",
"not",
"data",
"&",
"0x80",
":",
"return",
"result",
",",
"variant",
"[",
"cnt",
":",
"]",
"raise",
"Exception",
"(",
"'invalid variant'",
")"
] |
Read and parse a binary protobuf variant value.
|
[
"Read",
"and",
"parse",
"a",
"binary",
"protobuf",
"variant",
"value",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/variant.py#L4-L13
|
15,388
|
postlund/pyatv
|
examples/manual_connect.py
|
print_what_is_playing
|
async def print_what_is_playing(loop):
"""Connect to device and print what is playing."""
details = conf.AppleTV(ADDRESS, NAME)
details.add_service(conf.DmapService(HSGID))
print('Connecting to {}'.format(details.address))
atv = pyatv.connect_to_apple_tv(details, loop)
try:
print((await atv.metadata.playing()))
finally:
# Do not forget to logout
await atv.logout()
|
python
|
async def print_what_is_playing(loop):
"""Connect to device and print what is playing."""
details = conf.AppleTV(ADDRESS, NAME)
details.add_service(conf.DmapService(HSGID))
print('Connecting to {}'.format(details.address))
atv = pyatv.connect_to_apple_tv(details, loop)
try:
print((await atv.metadata.playing()))
finally:
# Do not forget to logout
await atv.logout()
|
[
"async",
"def",
"print_what_is_playing",
"(",
"loop",
")",
":",
"details",
"=",
"conf",
".",
"AppleTV",
"(",
"ADDRESS",
",",
"NAME",
")",
"details",
".",
"add_service",
"(",
"conf",
".",
"DmapService",
"(",
"HSGID",
")",
")",
"print",
"(",
"'Connecting to {}'",
".",
"format",
"(",
"details",
".",
"address",
")",
")",
"atv",
"=",
"pyatv",
".",
"connect_to_apple_tv",
"(",
"details",
",",
"loop",
")",
"try",
":",
"print",
"(",
"(",
"await",
"atv",
".",
"metadata",
".",
"playing",
"(",
")",
")",
")",
"finally",
":",
"# Do not forget to logout",
"await",
"atv",
".",
"logout",
"(",
")"
] |
Connect to device and print what is playing.
|
[
"Connect",
"to",
"device",
"and",
"print",
"what",
"is",
"playing",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/examples/manual_connect.py#L16-L28
|
15,389
|
postlund/pyatv
|
pyatv/mrp/protocol.py
|
MrpProtocol.add_listener
|
def add_listener(self, listener, message_type, data=None, one_shot=False):
"""Add a listener that will receice incoming messages."""
lst = self._one_shots if one_shot else self._listeners
if message_type not in lst:
lst[message_type] = []
lst[message_type].append(Listener(listener, data))
|
python
|
def add_listener(self, listener, message_type, data=None, one_shot=False):
"""Add a listener that will receice incoming messages."""
lst = self._one_shots if one_shot else self._listeners
if message_type not in lst:
lst[message_type] = []
lst[message_type].append(Listener(listener, data))
|
[
"def",
"add_listener",
"(",
"self",
",",
"listener",
",",
"message_type",
",",
"data",
"=",
"None",
",",
"one_shot",
"=",
"False",
")",
":",
"lst",
"=",
"self",
".",
"_one_shots",
"if",
"one_shot",
"else",
"self",
".",
"_listeners",
"if",
"message_type",
"not",
"in",
"lst",
":",
"lst",
"[",
"message_type",
"]",
"=",
"[",
"]",
"lst",
"[",
"message_type",
"]",
".",
"append",
"(",
"Listener",
"(",
"listener",
",",
"data",
")",
")"
] |
Add a listener that will receice incoming messages.
|
[
"Add",
"a",
"listener",
"that",
"will",
"receice",
"incoming",
"messages",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/protocol.py#L43-L50
|
15,390
|
postlund/pyatv
|
pyatv/mrp/protocol.py
|
MrpProtocol.start
|
async def start(self):
"""Connect to device and listen to incoming messages."""
if self.connection.connected:
return
await self.connection.connect()
# In case credentials have been given externally (i.e. not by pairing
# with a device), then use that client id
if self.service.device_credentials:
self.srp.pairing_id = Credentials.parse(
self.service.device_credentials).client_id
# The first message must always be DEVICE_INFORMATION, otherwise the
# device will not respond with anything
msg = messages.device_information(
'pyatv', self.srp.pairing_id.decode())
await self.send_and_receive(msg)
self._initial_message_sent = True
# This should be the first message sent after encryption has
# been enabled
await self.send(messages.set_ready_state())
async def _wait_for_updates(_, semaphore):
# Use a counter here whenever more than one message is expected
semaphore.release()
# Wait for some stuff to arrive before returning
semaphore = asyncio.Semaphore(value=0, loop=self.loop)
self.add_listener(_wait_for_updates,
protobuf.SET_STATE_MESSAGE,
data=semaphore,
one_shot=True)
# Subscribe to updates at this stage
await self.send(messages.client_updates_config())
await self.send(messages.wake_device())
try:
await asyncio.wait_for(
semaphore.acquire(), 1, loop=self.loop)
except asyncio.TimeoutError:
# This is not an issue itself, but I should do something better.
# Basically this gives the device about one second to respond with
# some metadata before continuing.
pass
|
python
|
async def start(self):
"""Connect to device and listen to incoming messages."""
if self.connection.connected:
return
await self.connection.connect()
# In case credentials have been given externally (i.e. not by pairing
# with a device), then use that client id
if self.service.device_credentials:
self.srp.pairing_id = Credentials.parse(
self.service.device_credentials).client_id
# The first message must always be DEVICE_INFORMATION, otherwise the
# device will not respond with anything
msg = messages.device_information(
'pyatv', self.srp.pairing_id.decode())
await self.send_and_receive(msg)
self._initial_message_sent = True
# This should be the first message sent after encryption has
# been enabled
await self.send(messages.set_ready_state())
async def _wait_for_updates(_, semaphore):
# Use a counter here whenever more than one message is expected
semaphore.release()
# Wait for some stuff to arrive before returning
semaphore = asyncio.Semaphore(value=0, loop=self.loop)
self.add_listener(_wait_for_updates,
protobuf.SET_STATE_MESSAGE,
data=semaphore,
one_shot=True)
# Subscribe to updates at this stage
await self.send(messages.client_updates_config())
await self.send(messages.wake_device())
try:
await asyncio.wait_for(
semaphore.acquire(), 1, loop=self.loop)
except asyncio.TimeoutError:
# This is not an issue itself, but I should do something better.
# Basically this gives the device about one second to respond with
# some metadata before continuing.
pass
|
[
"async",
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"connection",
".",
"connected",
":",
"return",
"await",
"self",
".",
"connection",
".",
"connect",
"(",
")",
"# In case credentials have been given externally (i.e. not by pairing",
"# with a device), then use that client id",
"if",
"self",
".",
"service",
".",
"device_credentials",
":",
"self",
".",
"srp",
".",
"pairing_id",
"=",
"Credentials",
".",
"parse",
"(",
"self",
".",
"service",
".",
"device_credentials",
")",
".",
"client_id",
"# The first message must always be DEVICE_INFORMATION, otherwise the",
"# device will not respond with anything",
"msg",
"=",
"messages",
".",
"device_information",
"(",
"'pyatv'",
",",
"self",
".",
"srp",
".",
"pairing_id",
".",
"decode",
"(",
")",
")",
"await",
"self",
".",
"send_and_receive",
"(",
"msg",
")",
"self",
".",
"_initial_message_sent",
"=",
"True",
"# This should be the first message sent after encryption has",
"# been enabled",
"await",
"self",
".",
"send",
"(",
"messages",
".",
"set_ready_state",
"(",
")",
")",
"async",
"def",
"_wait_for_updates",
"(",
"_",
",",
"semaphore",
")",
":",
"# Use a counter here whenever more than one message is expected",
"semaphore",
".",
"release",
"(",
")",
"# Wait for some stuff to arrive before returning",
"semaphore",
"=",
"asyncio",
".",
"Semaphore",
"(",
"value",
"=",
"0",
",",
"loop",
"=",
"self",
".",
"loop",
")",
"self",
".",
"add_listener",
"(",
"_wait_for_updates",
",",
"protobuf",
".",
"SET_STATE_MESSAGE",
",",
"data",
"=",
"semaphore",
",",
"one_shot",
"=",
"True",
")",
"# Subscribe to updates at this stage",
"await",
"self",
".",
"send",
"(",
"messages",
".",
"client_updates_config",
"(",
")",
")",
"await",
"self",
".",
"send",
"(",
"messages",
".",
"wake_device",
"(",
")",
")",
"try",
":",
"await",
"asyncio",
".",
"wait_for",
"(",
"semaphore",
".",
"acquire",
"(",
")",
",",
"1",
",",
"loop",
"=",
"self",
".",
"loop",
")",
"except",
"asyncio",
".",
"TimeoutError",
":",
"# This is not an issue itself, but I should do something better.",
"# Basically this gives the device about one second to respond with",
"# some metadata before continuing.",
"pass"
] |
Connect to device and listen to incoming messages.
|
[
"Connect",
"to",
"device",
"and",
"listen",
"to",
"incoming",
"messages",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/protocol.py#L53-L99
|
15,391
|
postlund/pyatv
|
pyatv/mrp/protocol.py
|
MrpProtocol.stop
|
def stop(self):
"""Disconnect from device."""
if self._outstanding:
_LOGGER.warning('There were %d outstanding requests',
len(self._outstanding))
self._initial_message_sent = False
self._outstanding = {}
self._one_shots = {}
self.connection.close()
|
python
|
def stop(self):
"""Disconnect from device."""
if self._outstanding:
_LOGGER.warning('There were %d outstanding requests',
len(self._outstanding))
self._initial_message_sent = False
self._outstanding = {}
self._one_shots = {}
self.connection.close()
|
[
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_outstanding",
":",
"_LOGGER",
".",
"warning",
"(",
"'There were %d outstanding requests'",
",",
"len",
"(",
"self",
".",
"_outstanding",
")",
")",
"self",
".",
"_initial_message_sent",
"=",
"False",
"self",
".",
"_outstanding",
"=",
"{",
"}",
"self",
".",
"_one_shots",
"=",
"{",
"}",
"self",
".",
"connection",
".",
"close",
"(",
")"
] |
Disconnect from device.
|
[
"Disconnect",
"from",
"device",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/protocol.py#L101-L110
|
15,392
|
postlund/pyatv
|
pyatv/mrp/protocol.py
|
MrpProtocol.send_and_receive
|
async def send_and_receive(self, message,
generate_identifier=True, timeout=5):
"""Send a message and wait for a response."""
await self._connect_and_encrypt()
# Some messages will respond with the same identifier as used in the
# corresponding request. Others will not and one example is the crypto
# message (for pairing). They will never include an identifer, but it
# it is in turn only possible to have one of those message outstanding
# at one time (i.e. it's not possible to mix up the responses). In
# those cases, a "fake" identifier is used that includes the message
# type instead.
if generate_identifier:
identifier = str(uuid.uuid4())
message.identifier = identifier
else:
identifier = 'type_' + str(message.type)
self.connection.send(message)
return await self._receive(identifier, timeout)
|
python
|
async def send_and_receive(self, message,
generate_identifier=True, timeout=5):
"""Send a message and wait for a response."""
await self._connect_and_encrypt()
# Some messages will respond with the same identifier as used in the
# corresponding request. Others will not and one example is the crypto
# message (for pairing). They will never include an identifer, but it
# it is in turn only possible to have one of those message outstanding
# at one time (i.e. it's not possible to mix up the responses). In
# those cases, a "fake" identifier is used that includes the message
# type instead.
if generate_identifier:
identifier = str(uuid.uuid4())
message.identifier = identifier
else:
identifier = 'type_' + str(message.type)
self.connection.send(message)
return await self._receive(identifier, timeout)
|
[
"async",
"def",
"send_and_receive",
"(",
"self",
",",
"message",
",",
"generate_identifier",
"=",
"True",
",",
"timeout",
"=",
"5",
")",
":",
"await",
"self",
".",
"_connect_and_encrypt",
"(",
")",
"# Some messages will respond with the same identifier as used in the",
"# corresponding request. Others will not and one example is the crypto",
"# message (for pairing). They will never include an identifer, but it",
"# it is in turn only possible to have one of those message outstanding",
"# at one time (i.e. it's not possible to mix up the responses). In",
"# those cases, a \"fake\" identifier is used that includes the message",
"# type instead.",
"if",
"generate_identifier",
":",
"identifier",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"message",
".",
"identifier",
"=",
"identifier",
"else",
":",
"identifier",
"=",
"'type_'",
"+",
"str",
"(",
"message",
".",
"type",
")",
"self",
".",
"connection",
".",
"send",
"(",
"message",
")",
"return",
"await",
"self",
".",
"_receive",
"(",
"identifier",
",",
"timeout",
")"
] |
Send a message and wait for a response.
|
[
"Send",
"a",
"message",
"and",
"wait",
"for",
"a",
"response",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/mrp/protocol.py#L134-L153
|
15,393
|
postlund/pyatv
|
pyatv/dmap/__init__.py
|
BaseDmapAppleTV.playstatus
|
async def playstatus(self, use_revision=False, timeout=None):
"""Request raw data about what is currently playing.
If use_revision=True, this command will "block" until playstatus
changes on the device.
Must be logged in.
"""
cmd_url = _PSU_CMD.format(
self.playstatus_revision if use_revision else 0)
resp = await self.daap.get(cmd_url, timeout=timeout)
self.playstatus_revision = parser.first(resp, 'cmst', 'cmsr')
return resp
|
python
|
async def playstatus(self, use_revision=False, timeout=None):
"""Request raw data about what is currently playing.
If use_revision=True, this command will "block" until playstatus
changes on the device.
Must be logged in.
"""
cmd_url = _PSU_CMD.format(
self.playstatus_revision if use_revision else 0)
resp = await self.daap.get(cmd_url, timeout=timeout)
self.playstatus_revision = parser.first(resp, 'cmst', 'cmsr')
return resp
|
[
"async",
"def",
"playstatus",
"(",
"self",
",",
"use_revision",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"cmd_url",
"=",
"_PSU_CMD",
".",
"format",
"(",
"self",
".",
"playstatus_revision",
"if",
"use_revision",
"else",
"0",
")",
"resp",
"=",
"await",
"self",
".",
"daap",
".",
"get",
"(",
"cmd_url",
",",
"timeout",
"=",
"timeout",
")",
"self",
".",
"playstatus_revision",
"=",
"parser",
".",
"first",
"(",
"resp",
",",
"'cmst'",
",",
"'cmsr'",
")",
"return",
"resp"
] |
Request raw data about what is currently playing.
If use_revision=True, this command will "block" until playstatus
changes on the device.
Must be logged in.
|
[
"Request",
"raw",
"data",
"about",
"what",
"is",
"currently",
"playing",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/__init__.py#L31-L43
|
15,394
|
postlund/pyatv
|
pyatv/dmap/__init__.py
|
BaseDmapAppleTV.ctrl_int_cmd
|
def ctrl_int_cmd(self, cmd):
"""Perform a "ctrl-int" command."""
cmd_url = 'ctrl-int/1/{}?[AUTH]&prompt-id=0'.format(cmd)
return self.daap.post(cmd_url)
|
python
|
def ctrl_int_cmd(self, cmd):
"""Perform a "ctrl-int" command."""
cmd_url = 'ctrl-int/1/{}?[AUTH]&prompt-id=0'.format(cmd)
return self.daap.post(cmd_url)
|
[
"def",
"ctrl_int_cmd",
"(",
"self",
",",
"cmd",
")",
":",
"cmd_url",
"=",
"'ctrl-int/1/{}?[AUTH]&prompt-id=0'",
".",
"format",
"(",
"cmd",
")",
"return",
"self",
".",
"daap",
".",
"post",
"(",
"cmd_url",
")"
] |
Perform a "ctrl-int" command.
|
[
"Perform",
"a",
"ctrl",
"-",
"int",
"command",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/__init__.py#L65-L68
|
15,395
|
postlund/pyatv
|
pyatv/dmap/__init__.py
|
BaseDmapAppleTV.controlprompt_cmd
|
def controlprompt_cmd(self, cmd):
"""Perform a "controlpromptentry" command."""
data = tags.string_tag('cmbe', cmd) + tags.uint8_tag('cmcc', 0)
return self.daap.post(_CTRL_PROMPT_CMD, data=data)
|
python
|
def controlprompt_cmd(self, cmd):
"""Perform a "controlpromptentry" command."""
data = tags.string_tag('cmbe', cmd) + tags.uint8_tag('cmcc', 0)
return self.daap.post(_CTRL_PROMPT_CMD, data=data)
|
[
"def",
"controlprompt_cmd",
"(",
"self",
",",
"cmd",
")",
":",
"data",
"=",
"tags",
".",
"string_tag",
"(",
"'cmbe'",
",",
"cmd",
")",
"+",
"tags",
".",
"uint8_tag",
"(",
"'cmcc'",
",",
"0",
")",
"return",
"self",
".",
"daap",
".",
"post",
"(",
"_CTRL_PROMPT_CMD",
",",
"data",
"=",
"data",
")"
] |
Perform a "controlpromptentry" command.
|
[
"Perform",
"a",
"controlpromptentry",
"command",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/__init__.py#L70-L73
|
15,396
|
postlund/pyatv
|
pyatv/dmap/__init__.py
|
DmapRemoteControl.up
|
async def up(self):
"""Press key up."""
await self._send_commands(
self._move('Down', 0, 20, 275),
self._move('Move', 1, 20, 270),
self._move('Move', 2, 20, 265),
self._move('Move', 3, 20, 260),
self._move('Move', 4, 20, 255),
self._move('Move', 5, 20, 250),
self._move('Up', 6, 20, 250))
|
python
|
async def up(self):
"""Press key up."""
await self._send_commands(
self._move('Down', 0, 20, 275),
self._move('Move', 1, 20, 270),
self._move('Move', 2, 20, 265),
self._move('Move', 3, 20, 260),
self._move('Move', 4, 20, 255),
self._move('Move', 5, 20, 250),
self._move('Up', 6, 20, 250))
|
[
"async",
"def",
"up",
"(",
"self",
")",
":",
"await",
"self",
".",
"_send_commands",
"(",
"self",
".",
"_move",
"(",
"'Down'",
",",
"0",
",",
"20",
",",
"275",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"1",
",",
"20",
",",
"270",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"2",
",",
"20",
",",
"265",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"3",
",",
"20",
",",
"260",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"4",
",",
"20",
",",
"255",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"5",
",",
"20",
",",
"250",
")",
",",
"self",
".",
"_move",
"(",
"'Up'",
",",
"6",
",",
"20",
",",
"250",
")",
")"
] |
Press key up.
|
[
"Press",
"key",
"up",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/__init__.py#L94-L103
|
15,397
|
postlund/pyatv
|
pyatv/dmap/__init__.py
|
DmapRemoteControl.down
|
async def down(self):
"""Press key down."""
await self._send_commands(
self._move('Down', 0, 20, 250),
self._move('Move', 1, 20, 255),
self._move('Move', 2, 20, 260),
self._move('Move', 3, 20, 265),
self._move('Move', 4, 20, 270),
self._move('Move', 5, 20, 275),
self._move('Up', 6, 20, 275))
|
python
|
async def down(self):
"""Press key down."""
await self._send_commands(
self._move('Down', 0, 20, 250),
self._move('Move', 1, 20, 255),
self._move('Move', 2, 20, 260),
self._move('Move', 3, 20, 265),
self._move('Move', 4, 20, 270),
self._move('Move', 5, 20, 275),
self._move('Up', 6, 20, 275))
|
[
"async",
"def",
"down",
"(",
"self",
")",
":",
"await",
"self",
".",
"_send_commands",
"(",
"self",
".",
"_move",
"(",
"'Down'",
",",
"0",
",",
"20",
",",
"250",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"1",
",",
"20",
",",
"255",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"2",
",",
"20",
",",
"260",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"3",
",",
"20",
",",
"265",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"4",
",",
"20",
",",
"270",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"5",
",",
"20",
",",
"275",
")",
",",
"self",
".",
"_move",
"(",
"'Up'",
",",
"6",
",",
"20",
",",
"275",
")",
")"
] |
Press key down.
|
[
"Press",
"key",
"down",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/__init__.py#L105-L114
|
15,398
|
postlund/pyatv
|
pyatv/dmap/__init__.py
|
DmapRemoteControl.left
|
async def left(self):
"""Press key left."""
await self._send_commands(
self._move('Down', 0, 75, 100),
self._move('Move', 1, 70, 100),
self._move('Move', 3, 65, 100),
self._move('Move', 4, 60, 100),
self._move('Move', 5, 55, 100),
self._move('Move', 6, 50, 100),
self._move('Up', 7, 50, 100))
|
python
|
async def left(self):
"""Press key left."""
await self._send_commands(
self._move('Down', 0, 75, 100),
self._move('Move', 1, 70, 100),
self._move('Move', 3, 65, 100),
self._move('Move', 4, 60, 100),
self._move('Move', 5, 55, 100),
self._move('Move', 6, 50, 100),
self._move('Up', 7, 50, 100))
|
[
"async",
"def",
"left",
"(",
"self",
")",
":",
"await",
"self",
".",
"_send_commands",
"(",
"self",
".",
"_move",
"(",
"'Down'",
",",
"0",
",",
"75",
",",
"100",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"1",
",",
"70",
",",
"100",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"3",
",",
"65",
",",
"100",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"4",
",",
"60",
",",
"100",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"5",
",",
"55",
",",
"100",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"6",
",",
"50",
",",
"100",
")",
",",
"self",
".",
"_move",
"(",
"'Up'",
",",
"7",
",",
"50",
",",
"100",
")",
")"
] |
Press key left.
|
[
"Press",
"key",
"left",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/__init__.py#L116-L125
|
15,399
|
postlund/pyatv
|
pyatv/dmap/__init__.py
|
DmapRemoteControl.right
|
async def right(self):
"""Press key right."""
await self._send_commands(
self._move('Down', 0, 50, 100),
self._move('Move', 1, 55, 100),
self._move('Move', 3, 60, 100),
self._move('Move', 4, 65, 100),
self._move('Move', 5, 70, 100),
self._move('Move', 6, 75, 100),
self._move('Up', 7, 75, 100))
|
python
|
async def right(self):
"""Press key right."""
await self._send_commands(
self._move('Down', 0, 50, 100),
self._move('Move', 1, 55, 100),
self._move('Move', 3, 60, 100),
self._move('Move', 4, 65, 100),
self._move('Move', 5, 70, 100),
self._move('Move', 6, 75, 100),
self._move('Up', 7, 75, 100))
|
[
"async",
"def",
"right",
"(",
"self",
")",
":",
"await",
"self",
".",
"_send_commands",
"(",
"self",
".",
"_move",
"(",
"'Down'",
",",
"0",
",",
"50",
",",
"100",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"1",
",",
"55",
",",
"100",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"3",
",",
"60",
",",
"100",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"4",
",",
"65",
",",
"100",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"5",
",",
"70",
",",
"100",
")",
",",
"self",
".",
"_move",
"(",
"'Move'",
",",
"6",
",",
"75",
",",
"100",
")",
",",
"self",
".",
"_move",
"(",
"'Up'",
",",
"7",
",",
"75",
",",
"100",
")",
")"
] |
Press key right.
|
[
"Press",
"key",
"right",
"."
] |
655dfcda4e2f9d1c501540e18da4f480d8bf0e70
|
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/__init__.py#L127-L136
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.