def test_consumer_should_be_able_to_encrypt_segments(tmpdir):
    plain_dir = tmpdir.join('plain')
    hlsclient.consumer.consume(M3U8_SERVER + '/low.m3u8', str(plain_dir))

    encrypted_dir = tmpdir.join('encrypted')
    hlsclient.consumer.consume(M3U8_SERVER + '/low.m3u8', str(encrypted_dir), True)

    plain = plain_dir.join('low1.ts').read()
    encrypted = encrypted_dir.join('low1.ts').read()
    m3u8_content = encrypted_dir.join('low.m3u8').read()

    assert encrypted_dir.join("low.bin").check()
    assert 'URI="low.bin"' in m3u8_content
    assert "#EXT-X-VERSION:2" in m3u8_content

    new_key = crypto.get_key_from_disk("low.bin", str(encrypted_dir))
    assert plain == crypto.decrypt(encrypted, new_key)
def test_consumer_should_be_able_to_change_segments_encryption(tmpdir):
    m3u8_uri = M3U8_SERVER + '/crypto.m3u8'
    playlist = m3u8.load(m3u8_uri)

    original_dir = tmpdir.join('original')
    hlsclient.consumer.consume(m3u8_uri, str(original_dir))
    playlist.key.key_value = original_dir.join('key.bin').read()

    new_dir = tmpdir.join('new')
    hlsclient.consumer.consume(m3u8_uri, str(new_dir), True)

    original = original_dir.join('encrypted1.ts').read()
    new = new_dir.join('encrypted2.ts').read()
    m3u8_content = new_dir.join('crypto.m3u8').read()

    assert new_dir.join("crypto.bin").check()
    assert 'URI="crypto.bin"' in m3u8_content

    new_key = crypto.get_key_from_disk("crypto.bin", str(new_dir))
    assert crypto.decrypt(original, playlist.key) == crypto.decrypt(new, new_key)