date_collected
stringclasses 1
value | repo_name
stringlengths 6
116
| file_name
stringlengths 2
220
| file_contents
stringlengths 13
357k
| prompts
sequence |
---|---|---|---|---|
2024-01-10 | TCU-ClassifAI/classifAI-engine | src~services~summarize~summarize_transcript.py | import os
import openai
from datetime import datetime
# Load .env file if it exists
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.environ["OPENAI_API_KEY"]
# Open text files
# Specify the file path
file_path = "file.txt" # Replace with the path to your text file
# Initialize an empty string to store the file content
file_content = ""
# Open the file in 'read' mode
try:
with open(file_path, "r") as file:
# Read the entire content of the file into the string
file_content = file.read()
except FileNotFoundError:
print(f"The file '{file_path}' was not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
gpt_instructions = """You will be provided with the text of a transcript. Your goal is to summarize the text in 1-2 sentences.
Your response should be detailed, concise, and clear. The tone should be that of a clinical diagnosis.
Use as few words as necessary without sacrificing quality. """
prompt = gpt_instructions + "Here are the texts:" + "\n\n" + file_content
response = openai.ChatCompletion.create(
model="gpt-4-1106-preview",
messages=[{"role": "user", "content": prompt}],
temperature=0.7,
# '''Temperature is a number between 0 and 2, with a default value of 1 or 0.7
# depending on the model you choose. The temperature is used to control the randomness
# of the output. When you set it higher, you'll get more random outputs.
# When you set it lower, towards 0, the values are more deterministic.'''
)
print(response)
print(response["choices"][0]["message"]["content"])
# Get current time
now = datetime.now() # current date and time
# Set the name for the response file
names = file_path.rsplit(".", 1)
# response_file_name = names[0] + "-Response" + + ".txt"
response_file_name = names[0] + ";" + now.strftime("%m-%d-%Y;%H:%M:%S") + ".txt"
# Create the response file if it doesn't exist
if not os.path.exists(response_file_name):
open(response_file_name, "w").close()
with open(response_file_name, "w") as file:
# Write some text to the file
# file.write(gpt_instructions)
file.write(gpt_instructions + "\n\n")
file.write(response["choices"][0]["message"]["content"])
# Previous prompt
# gpt_instructions = """ You will be provided with texts.
# Find emotion related words.
# Your response should be detailed, concise, and clear.
# The tone should be that of a clinical diagnosis.
# Use as few words as necessary without sacrificing quality.
# Explain why do you identify them as emotion words.
# Here are the texts: """
| [
"You will be provided with the text of a transcript. Your goal is to summarize the text in 1-2 sentences.\n Your response should be detailed, concise, and clear. The tone should be that of a clinical diagnosis.\n Use as few words as necessary without sacrificing quality. Here are the texts:\n\n",
"You will be provided with the text of a transcript. Your goal is to summarize the text in 1-2 sentences.\n Your response should be detailed, concise, and clear. The tone should be that of a clinical diagnosis.\n Use as few words as necessary without sacrificing quality. Here are the texts:\n\nfile_content5e71df8a-ee14-44dc-91cd-9725c62feff1"
] |
2024-01-10 | TCU-ClassifAI/classifAI-engine | src~services~summarize~topics.py | import os
from openai import OpenAI
from datetime import datetime
# Load .env file if it exists
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(
# This is the default and can be omitted
api_key=os.environ.get("OPENAI_API_KEY"),
)
# Open text files
# Specify the file path
file_path = "file.txt" # Replace with the path to your text file
# Initialize an empty string to store the file content
file_content = ""
# Open the file in 'read' mode
try:
with open(file_path, "r") as file:
# Read the entire content of the file into the string
file_content = file.read()
except FileNotFoundError:
print(f"The file '{file_path}' was not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
gpt_instructions = """You will be provided with the text of a transcript. Your goal is to summarize the text in 1-2 sentences.
Your response should be detailed, concise, and clear. The tone should be that of a clinical diagnosis.
Use as few words as necessary without sacrificing quality. """
prompt = gpt_instructions + "Here are the texts:" + "\n\n" + "dummy" # file_content
response = client.chat.completions.create(
model="gpt-4-1106-preview",
messages=[{"role": "user", "content": prompt}],
temperature=0.7,
# '''Temperature is a number between 0 and 2, with a default value of 1 or 0.7
# depending on the model you choose. The temperature is used to control the randomness
# of the output. When you set it higher, you'll get more random outputs.
# When you set it lower, towards 0, the values are more deterministic.'''
)
print(response)
print(response["choices"])
# Get current time
now = datetime.now() # current date and time
# Set the name for the response file
names = file_path.rsplit(".", 1)
# response_file_name = names[0] + "-Response" + + ".txt"
response_file_name = names[0] + ";" + now.strftime("%m-%d-%Y;%H:%M:%S") + ".txt"
# Create the response file if it doesn't exist
if not os.path.exists(response_file_name):
open(response_file_name, "w").close()
with open(response_file_name, "w") as file:
# Write some text to the file
# file.write(gpt_instructions)
file.write(gpt_instructions + "\n\n")
file.write(response["choices"][0]["message"]["content"])
# Previous prompt
# gpt_instructions = """ You will be provided with texts.
# Find emotion related words.
# Your response should be detailed, concise, and clear.
# The tone should be that of a clinical diagnosis.
# Use as few words as necessary without sacrificing quality.
# Explain why do you identify them as emotion words.
# Here are the texts: """
| [
"You will be provided with the text of a transcript. Your goal is to summarize the text in 1-2 sentences.\n Your response should be detailed, concise, and clear. The tone should be that of a clinical diagnosis.\n Use as few words as necessary without sacrificing quality. Here are the texts:\n\ndummy"
] |
2024-01-10 | TCU-ClassifAI/classifAI-engine | src~services~categorize.py | from flask import Blueprint, make_response, jsonify
from openai import AsyncOpenAI
from dotenv import load_dotenv
import json
import asyncio
load_dotenv()
client = AsyncOpenAI()
categorize = Blueprint("categorize", __name__)
@categorize.route("/healthcheck")
def healthcheck():
return make_response("OK", 200)
@categorize.route("/categorize", methods=["POST"])
def categorize_endpoint():
"""Given a transcript, return the question type and Costa's level of reasoning for each question.
Returns:
dict: A dictionary containing the question type and Costa's level of reasoning for each question.
"""
pass
def validate_category_output(output):
"""
Validate the output of the categorize function.
Args:
output (dict): Output of the categorize function.
Returns:
(bool, str): A tuple containing a boolean indicating whether the output is valid and an error message if is not valid.
"""
# Ensure the output JSON has the required fields
required_fields = ["question_type", "question_level"]
if not all(field in output for field in required_fields):
return (False, "Output JSON must contain question_type and question_level")
# Ensure the question level is an integer
if not isinstance(output["question_level"], int):
return (False, "question_level must be an integer")
# Ensure the question level is between 0 and 3
if not 0 <= output["question_level"] <= 3:
return (False, "question_level must be between 0 and 3")
# Ensure the question type is a string and is one of the allowed values
if not isinstance(output["question_type"], str):
return (False, "question_type must be a string")
allowed_question_types = [
"Knowledge",
"Analyze",
"Apply",
"Create",
"Evaluate",
"Understand",
"Rhetorical",
"Unknown",
]
if output["question_type"] not in allowed_question_types:
return (False, f"question_type must be one of {allowed_question_types}")
return True, None
async def categorize_question(data) -> dict:
"""
Categorize the question type and Costa's level of reasoning of a question given the context, using GPT-4.
Args:
summary (str): Summary of the question.
previous_sentence (str): Previous sentence in the context.
previous_speaker (str): Speaker of the previous sentence.
question (str): Question to categorize.
question_speaker (str): Speaker of the question.
next_sentence (str): Next sentence in the context.
next_speaker (str): Speaker of the next sentence.
Returns:
dict: A dictionary containing the question type and Costa's level of reasoning.
"""
# Basic input validation
required_fields = [
"summary",
"previous_sentence",
"previous_speaker",
"question",
"question_speaker",
"next_sentence",
"next_speaker",
]
if not all(field in data for field in required_fields):
return jsonify({"error": "Missing required fields"}), 400
# Construct the messages to send to the language model
system_role = """
Given the following context and question from the speaker, determine the question type and Costa's level of reasoning.
The question type should be categorized as Knowledge, Analyze, Apply, Create, Evaluate, Understand, Rhetorical, or Unknown.
Costa's levels of reasoning should be categorized as 1 (gathering), 2 (processing), 3 (applying), or 0 (n/a).
Provide the analysis in JSON format as specified.
--- BEGIN USER MESSAGE ---
Context: "$SUMMARY"
Previous Sentence: "$PREVIOUS_SENTENCE"
Speaker of Previous Sentence: "$PREVIOUS_SPEAKER"
Question: "$QUESTION"
Speaker of Question: "$QUESTION_SPEAKER"
Next Sentence: "$NEXT_SENTENCE"
Speaker of Next Sentence: "$NEXT_SPEAKER"
--- END USER MESSAGE ---
Analyze the question and output the results in the following JSON format,
where QUESTION_TYPE is a str and QUESTION_LEVEL is an int (1, 2, 3, or 0):
---BEGIN FORMAT---
{
"question_type":"$QUESTION_TYPE",
"question_level":"$QUESTION_LEVEL"
}
---END FORMAT---
"""
user_message = f"""
Context: {data['summary']}
Previous Sentence: {data['previous_sentence']}
Speaker of Previous Sentence: {data['previous_speaker']}
Question: {data['question']}
Speaker of Question: {data['question_speaker']}
Next Sentence: {data['next_sentence']}
Speaker of Next Sentence: {data['next_speaker']}
"""
messages = [
{"role": "system", "content": system_role},
{"role": "user", "content": user_message},
]
# Call the OpenAI API with the prompt
response = await client.chat.completions.create(
model="gpt-3.5-turbo-1106",
response_format={"type": "json_object"},
messages=messages,
temperature=0,
)
print(str(response.choices[0].message.content))
# Extract the response and format it as JSON
output = str(response.choices[0].message.content)
# Parse the output JSON
output = json.loads(output)
# Validate the output JSON
valid, error = validate_category_output(output)
if not valid: # If the output JSON is not valid, return that we don't know the question type or level
return {
"question_type": "Unknown",
"question_level": 0,
}
# Return the output JSON
return output
# async def test_categorize_question():
# """
# Test the categorize_question function.
# """
# # Define the sample input data
# sample_data = {
# "summary": "Context summary",
# "previous_sentence": "Previous sentence",
# "previous_speaker": "Speaker A",
# "question": "What is the capital of France?",
# "question_speaker": "Speaker B",
# "next_sentence": "Next sentence",
# "next_speaker": "Speaker C",
# }
# tasks = [categorize_question(sample_data) for _ in range(10)]
# results = asyncio.run(asyncio.gather(*tasks))
# print(results)
# asyncio.run(test_categorize_question())
sample_data = {
"summary": "Context summary",
"previous_sentence": "Previous sentence",
"previous_speaker": "Speaker A",
"question": "What is the capital of France?",
"question_speaker": "Speaker B",
"next_sentence": "Next sentence",
"next_speaker": "Speaker C",
}
loop = asyncio.get_event_loop()
ret_val = loop.run_until_complete(categorize_question(sample_data))
print(ret_val)
| [
"\n Given the following context and question from the speaker, determine the question type and Costa's level of reasoning.\n The question type should be categorized as Knowledge, Analyze, Apply, Create, Evaluate, Understand, Rhetorical, or Unknown.\n Costa's levels of reasoning should be categorized as 1 (gathering), 2 (processing), 3 (applying), or 0 (n/a).\n Provide the analysis in JSON format as specified.\n --- BEGIN USER MESSAGE ---\n Context: \"$SUMMARY\"\n Previous Sentence: \"$PREVIOUS_SENTENCE\"\n Speaker of Previous Sentence: \"$PREVIOUS_SPEAKER\"\n Question: \"$QUESTION\"\n Speaker of Question: \"$QUESTION_SPEAKER\"\n Next Sentence: \"$NEXT_SENTENCE\"\n Speaker of Next Sentence: \"$NEXT_SPEAKER\"\n --- END USER MESSAGE ---\n Analyze the question and output the results in the following JSON format,\n where QUESTION_TYPE is a str and QUESTION_LEVEL is an int (1, 2, 3, or 0):\n\n ---BEGIN FORMAT---\n {\n \"question_type\":\"$QUESTION_TYPE\",\n \"question_level\":\"$QUESTION_LEVEL\"\n }\n ---END FORMAT---\n ",
"\n Context: PLACEHOLDER\n Previous Sentence: PLACEHOLDER\n Speaker of Previous Sentence: PLACEHOLDER\n Question: PLACEHOLDER\n Speaker of Question: PLACEHOLDER\n Next Sentence: PLACEHOLDER\n Speaker of Next Sentence: PLACEHOLDER\n "
] |
2024-01-10 | sthory/LLM_OpenAI_GPT | Mastering%20OpenAI%20Python%20APIs%20Unleash%20ChatGPT%20and%20GPT4~11.%20GPT-4%20AI%20Spotify%20Playlist%20Generator%20Project~final.py | import argparse
import datetime
import logging
import os
import json
import openai
import spotipy
from dotenv import load_dotenv
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def main():
parser = argparse.ArgumentParser(description="Simple command line utility")
parser.add_argument("-p", type=str, help="The prompt to describing the playlist.")
parser.add_argument("-n", type=int, default="12", help="The number of songs to be added.")
parser.add_argument("-envfile", type=str, default=".env", required=False, help='A dotenv file with your environment variables: "SPOTIFY_CLIENT_ID", "SPOTIFY_CLIENT_SECRET", "OPENAI_API_KEY"')
args = parser.parse_args()
load_dotenv(args.envfile)
if any([x not in os.environ for x in ("SPOTIFY_CLIENT_ID", "SPOTIFY_CLIENT_SECRET", "OPENAI_API_KEY")]):
raise ValueError("Error: missing environment variables. Please check your env file.")
if args.n not in range(1,50):
raise ValueError("Error: n should be between 0 and 50")
openai.api_key = os.environ["OPENAI_API_KEY"]
playlist_prompt = args.p
count = args.n
playlist = get_playlist(playlist_prompt, count)
add_songs_to_spotify(playlist_prompt, playlist)
def get_playlist(prompt, count=8):
example_json = """
[
{"song": "Everybody Hurts", "artist": "R.E.M."},
{"song": "Nothing Compares 2 U", "artist": "Sinead O'Connor"},
{"song": "Tears in Heaven", "artist": "Eric Clapton"},
{"song": "Hurt", "artist": "Johnny Cash"},
{"song": "Yesterday", "artist": "The Beatles"}
]
"""
messages = [
{"role": "system", "content": """You are a helpful playlist generating assistant.
You should generate a list of songs and their artists according to a text prompt.
Your should return a JSON array, where each element follows this format: {"song": <song_title>, "artist": <artist_name>}
"""
},
{"role": "user", "content": "Generate a playlist of 5 songs based on this prompt: super super sad songs"},
{"role": "assistant", "content": example_json},
{"role": "user", "content": f"Generate a playlist of {count} songs based on this prompt: {prompt}"},
]
response = openai.ChatCompletion.create(
messages=messages,
model="gpt-4",
max_tokens=400
)
playlist = json.loads(response["choices"][0]["message"]["content"])
return playlist
def add_songs_to_spotify(playlist_prompt, playlist):
# Sign up as a developer and register your app at https://developer.spotify.com/dashboard/applications
# Step 1. Create an Application.
# Step 2. Copy your Client ID and Client Secret.
spotipy_client_id = os.environ["SPOTIFY_CLIENT_ID"] # Use your Spotify API's keypair's Client ID
spotipy_client_secret = os.environ["SPOTIFY_CLIENT_SECRET"] # Use your Spotify API's keypair's Client Secret
# Step 3. Click `Edit Settings`, add `http://localhost:9999` as as a "Redirect URI"
spotipy_redirect_url = "http://localhost:9999" # Your browser will return page not found at this step. We'll grab the URL and paste back in to our console
# Step 4. Click `Users and Access`. Add your Spotify account to the list of users (identified by your email address)
# Spotipy Documentation
# https://spotipy.readthedocs.io/en/2.22.1/#getting-started
sp = spotipy.Spotify(
auth_manager=spotipy.SpotifyOAuth(
client_id=spotipy_client_id,
client_secret=spotipy_client_secret,
redirect_uri=spotipy_redirect_url,
scope="playlist-modify-private",
)
)
current_user = sp.current_user()
assert current_user is not None
track_uris = []
for item in playlist:
artist, song = item["artist"], item["song"]
# https://developer.spotify.com/documentation/web-api/reference/#/operations/search
advanced_query = f"artist:({artist}) track:({song})"
basic_query = f"{song} {artist}"
for query in [advanced_query, basic_query]:
log.debug(f"Searching for query: {query}")
search_results = sp.search(q=query, limit=10, type="track") # , market=market)
if not search_results["tracks"]["items"] or search_results["tracks"]["items"][0]["popularity"] < 20:
continue
else:
good_guess = search_results["tracks"]["items"][0]
print(f"Found: {good_guess['name']} [{good_guess['id']}]")
# print(f"FOUND USING QUERY: {query}")
track_uris.append(good_guess["id"])
break
else:
print(f"Queries {advanced_query} and {basic_query} returned no good results. Skipping.")
created_playlist = sp.user_playlist_create(
current_user["id"],
public=False,
name=f"{playlist_prompt} ({datetime.datetime.now().strftime('%c')})",
)
sp.user_playlist_add_tracks(current_user["id"], created_playlist["id"], track_uris)
print("\n")
print(f"Created playlist: {created_playlist['name']}")
print(created_playlist["external_urls"]["spotify"])
if __name__ == "__main__":
main()
| [
"Generate a playlist of PLACEHOLDER songs based on this prompt: PLACEHOLDER",
"You are a helpful playlist generating assistant. \n You should generate a list of songs and their artists according to a text prompt.\n Your should return a JSON array, where each element follows this format: {\"song\": <song_title>, \"artist\": <artist_name>}\n ",
"Generate a playlist of 5 songs based on this prompt: super super sad songs",
"\n [\n {\"song\": \"Everybody Hurts\", \"artist\": \"R.E.M.\"},\n {\"song\": \"Nothing Compares 2 U\", \"artist\": \"Sinead O'Connor\"},\n {\"song\": \"Tears in Heaven\", \"artist\": \"Eric Clapton\"},\n {\"song\": \"Hurt\", \"artist\": \"Johnny Cash\"},\n {\"song\": \"Yesterday\", \"artist\": \"The Beatles\"}\n ]\n "
] |
2024-01-10 | sthory/LLM_OpenAI_GPT | Mastering%20OpenAI%20Python%20APIs%20Unleash%20ChatGPT%20and%20GPT4~10.%20GPT-4%20Automatic%20Code%20Reviewer~reviewer.py | from ast import parse
import openai
from dotenv import load_dotenv
import os
import argparse
PROMPT = """
You will receive a file's contents as text.
Generate a code review for the file. Indicate what changes should be made to improve its style, performance, readability, and maintainability. If there are any reputable libraries that could be introduced to improve the code, suggest them. Be kind and constructive. For each suggested change, include line numbers to which you are referring
"""
def code_review(file_path, model):
with open(file_path, "r") as file:
content = file.read()
generated_code_review = make_code_review_request(content, model)
print(generated_code_review)
def make_code_review_request(filecontent, model):
messages = [
{"role": "system", "content": PROMPT},
{"role": "user", "content": f"Code review the following file: {filecontent}"}
]
res = openai.ChatCompletion.create(
model=model,
messages=messages
)
return res["choices"][0]["message"]["content"]
def main():
parser = argparse.ArgumentParser(description="Simple code reviewer for a file")
parser.add_argument("file")
#parser.add_argument("--model", default="gpt-4")
parser.add_argument("--model", default="gpt-3.5-turbo")
args = parser.parse_args()
code_review(args.file, args.model)
if __name__ == "__main__":
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
main()
| [
"Code review the following file: PLACEHOLDER",
"\nYou will receive a file's contents as text.\nGenerate a code review for the file. Indicate what changes should be made to improve its style, performance, readability, and maintainability. If there are any reputable libraries that could be introduced to improve the code, suggest them. Be kind and constructive. For each suggested change, include line numbers to which you are referring\n"
] |
2024-01-10 | DimaGutierrez/GPT3Chatbot | gpt3-grader-v1.py | import openai
openai.api_key = "YOUR_API_KEY_HERE"
def grade_essay(prompt, response):
model_engine = "text-davinci-003"
prompt = (f"Essay prompt: {prompt}\nEssay response: {response}\n"
"Please grade the essay response and provide feedback.")
completions = openai.Completion.create(engine=model_engine, prompt=prompt, max_tokens=1024, n=1,stop=None,temperature=0.5)
message = completions.choices[0].text
return message
prompt = "Write an essay on the impact of technology on society."
response = "Technology has had a significant impact on society in recent years. It has transformed the way we communicate, access information, and do business. One of the main benefits of technology is the ability to connect people from all around the world through social media and other platforms. It has also made it easier for people to access education and job opportunities online. However, technology has also had negative impacts on society. It has contributed to a decrease in face-to-face communication and an increase in cyberbullying. In addition, the reliance on technology has led to a decrease in critical thinking skills and an increase in misinformation. Overall, while technology has brought many benefits to society, it is important to use it responsibly and consider the potential downsides."
print(grade_essay(prompt, response))
| [
"Write an essay on the impact of technology on society.",
"Essay prompt: Write an essay on the impact of technology on society.\nEssay response: Technology has had a significant impact on society in recent years. It has transformed the way we communicate, access information, and do business. One of the main benefits of technology is the ability to connect people from all around the world through social media and other platforms. It has also made it easier for people to access education and job opportunities online. However, technology has also had negative impacts on society. It has contributed to a decrease in face-to-face communication and an increase in cyberbullying. In addition, the reliance on technology has led to a decrease in critical thinking skills and an increase in misinformation. Overall, while technology has brought many benefits to society, it is important to use it responsibly and consider the potential downsides.\nPlease grade the essay response and provide feedback."
] |
2024-01-10 | DimaGutierrez/GPT3Chatbot | GPT3Chatbot.py | import openai
openai.api_key = "YOUR API KEY HERE"
model_engine = "text-davinci-003"
chatbot_prompt = """
As an advanced chatbot, your primary goal is to assist users to the best of your ability. This may involve answering questions, providing helpful information, or completing tasks based on user input. In order to effectively assist users, it is important to be detailed and thorough in your responses. Use examples and evidence to support your points and justify your recommendations or solutions.
<conversation history>
User: <user input>
Chatbot:"""
def get_response(conversation_history, user_input):
prompt = chatbot_prompt.replace(
"<conversation_history>", conversation_history).replace("<user input>", user_input)
# Get the response from GPT-3
response = openai.Completion.create(
engine=model_engine, prompt=prompt, max_tokens=2048, n=1, stop=None, temperature=0.5)
# Extract the response from the response object
response_text = response["choices"][0]["text"]
chatbot_response = response_text.strip()
return chatbot_response
def main():
conversation_history = ""
while True:
user_input = input("> ")
if user_input == "exit":
break
chatbot_response = get_response(conversation_history, user_input)
print(f"Chatbot: {chatbot_response}")
conversation_history += f"User: {user_input}\nChatbot: {chatbot_response}\n"
main()
| [
"<conversation_history>",
"\nAs an advanced chatbot, your primary goal is to assist users to the best of your ability. This may involve answering questions, providing helpful information, or completing tasks based on user input. In order to effectively assist users, it is important to be detailed and thorough in your responses. Use examples and evidence to support your points and justify your recommendations or solutions.\n<conversation history>\nUser: <user input>\nChatbot:",
"<user input>"
] |
2024-01-10 | DimaGutierrez/GPT3Chatbot | gpt3-grader-v2.py | import openai
openai.api_key = "YOUR_API_KEY_HERE"
gpt3_prompt = """
Grade the following essay and output a thorough analysis with examples and justifications. Output in the following JSON format:
{ "grade": ${grade}, "analysis": ${tone} }
PROMPT: <PROMPT>
ESSAY: <ESSAY>
"""
def grade_essay(prompt, response):
model_engine = "text-davinci-003"
prompt = gpt3_prompt.replace("<PROMPT>", prompt).replace("<ESSAY>", response)
completions = openai.Completion.create(engine=model_engine, prompt=prompt, max_tokens=1024, n=1,stop=None,temperature=0.5)
message = completions.choices[0].text
return message
prompt = "Write an essay on the impact of technology on society."
response = "Technology has had a significant impact on society in recent years. It has transformed the way we communicate, access information, and do business. One of the main benefits of technology is the ability to connect people from all around the world through social media and other platforms. It has also made it easier for people to access education and job opportunities online. However, technology has also had negative impacts on society. It has contributed to a decrease in face-to-face communication and an increase in cyberbullying. In addition, the reliance on technology has led to a decrease in critical thinking skills and an increase in misinformation. Overall, while technology has brought many benefits to society, it is important to use it responsibly and consider the potential downsides."
print(grade_essay(prompt, response))
| [
"Write an essay on the impact of technology on society.",
"\nGrade the following essay and output a thorough analysis with examples and justifications. Output in the following JSON format: \n{ \"grade\": ${grade}, \"analysis\": ${tone} }\nPROMPT: Write an essay on the impact of technology on society.\nESSAY: Technology has had a significant impact on society in recent years. It has transformed the way we communicate, access information, and do business. One of the main benefits of technology is the ability to connect people from all around the world through social media and other platforms. It has also made it easier for people to access education and job opportunities online. However, technology has also had negative impacts on society. It has contributed to a decrease in face-to-face communication and an increase in cyberbullying. In addition, the reliance on technology has led to a decrease in critical thinking skills and an increase in misinformation. Overall, while technology has brought many benefits to society, it is important to use it responsibly and consider the potential downsides.\n",
"\nGrade the following essay and output a thorough analysis with examples and justifications. Output in the following JSON format: \n{ \"grade\": ${grade}, \"analysis\": ${tone} }\nPROMPT: <PROMPT>\nESSAY: <ESSAY>\n"
] |
2024-01-10 | EvgeniBondarev/ContextKeeper | save_code.py | import openai
openai.api_key = "Ваш openai токет"
def get_response(prompt: str, context:str) -> str:
"""
Функция для запроса ответа от OpenAI.
Args:
prompt (str): Текст от пользователя для передачи в модель.
context (str): Текущий контекст для передачи в модель.
Returns:
str: Ответ от модели.
"""
response = openai.Completion.create(
model="text-davinci-003",
prompt=f"Продолжи общение: {context}Пользователь: {prompt}\n",
temperature=0,
max_tokens=3000,
top_p=1.0,
frequency_penalty=0.2,
presence_penalty=0.0,
stop=None
)
return response.choices[0].text.lstrip()
def main():
"""
Основная функция, которая обрабатывает ввод пользователя и выводит ответы модели.
"""
context = "" # Начальный контекст - пустая строка
while True:
prompt = input("Вы: ")
if not prompt.strip(): # Валидация, если строка пустая, то запросить ввод еще раз
print("Пожалуйста, введите текст")
continue
context += f"Пользователь: {prompt}\n" # Добавление текста пользователя в контекст
ans = get_response(prompt, context) # Получение ответа от модели
context += f"{ans}\n" # Добавление ответа модели в контекст
print(ans)
if __name__ == '__main__':
main()
| [
"Вы: ",
"Продолжи общение: PLACEHOLDERПользователь: PLACEHOLDER\n"
] |
2024-01-10 | facebookresearch/holo_diffusion | holo_diffusion~utils~diffusion_utils.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
"""This module adapts the diffusion functionality
from OpenAI's guided diffusion package to work with implicitron. Please note
that we have made some changes to the guided_diffusion code as well"""
import torch
from pytorch3d.implicitron.tools.config import registry, ReplaceableBase, Configurable
from pytorch3d.implicitron.models.implicit_function.decoding_functions import (
_xavier_init,
)
from typing import Optional, Tuple
from ..guided_diffusion.unet import UNetModel
from ..guided_diffusion.timestep_sampler import create_named_schedule_sampler
from ..guided_diffusion.gaussian_diffusion import (
ModelMeanType,
LossType,
ModelVarType,
GaussianDiffusion,
get_named_beta_schedule,
)
class Unet3DBase(ReplaceableBase, torch.nn.Module):
def forward(
self,
x: torch.Tensor,
timesteps: torch.Tensor,
cond_features: Optional[torch.Tensor] = None,
**kwargs
) -> torch.Tensor:
raise NotImplementedError()
@registry.register
class SimpleUnet3D(Unet3DBase):
image_size: int = 64
in_channels: int = 128
out_channels: int = 128
model_channels: int = 128
num_res_blocks: int = 2
channel_mult: Tuple[int, ...] = (1, 2, 4, 8)
attention_resolutions: Tuple[int, ...] = (8, 16)
num_heads: int = 2
dropout: float = 0.0
# 3d down/upsamples have the same size in all 3 dims
homogeneous_resample: bool = True
def __post_init__(self):
self._net = UNetModel(
dims=3,
image_size=self.image_size,
in_channels=self.in_channels,
model_channels=self.model_channels,
out_channels=self.out_channels,
num_res_blocks=self.num_res_blocks,
attention_resolutions=self.attention_resolutions,
dropout=self.dropout,
channel_mult=self.channel_mult,
num_classes=None,
use_checkpoint=False,
num_heads=self.num_heads,
num_head_channels=-1,
num_heads_upsample=-1,
use_scale_shift_norm=True,
resblock_updown=False,
zero_last_conv=False,
homogeneous_resample=self.homogeneous_resample,
)
for m in self._net.modules():
if isinstance(m, (torch.nn.Conv3d, torch.nn.Linear)):
_xavier_init(m)
m.bias.data[:] = 0.0
def forward(self, x, timesteps, cond_features=None):
if cond_features is not None:
x = torch.cat([x, cond_features], dim=1)
y = self._net(x, timesteps=timesteps)
return y
class ImplicitronGaussianDiffusion(Configurable):
beta_schedule_type: str = "linear"
num_steps: int = 1000
beta_start_unscaled: float = 0.0001
beta_end_unscaled: float = 0.02
# Note that we use START_X here because of the photometric-loss we use
model_mean_type: ModelMeanType = ModelMeanType.START_X
model_var_type: ModelVarType = ModelVarType.FIXED_SMALL
schedule_sampler_type: str = "uniform"
def __post_init__(self):
self._diffusion = GaussianDiffusion(
betas=get_named_beta_schedule(
self.beta_schedule_type,
self.num_steps,
self.beta_start_unscaled,
self.beta_end_unscaled,
),
model_mean_type=self.model_mean_type,
model_var_type=self.model_var_type,
# LossType is not used in holo_diffusion. We define our own loss
loss_type=LossType.MSE,
rescale_timesteps=False,
)
self._schedule_sampler = create_named_schedule_sampler(
self.schedule_sampler_type, self._diffusion
)
def training_losses(self, *args, **kwargs):
# We don't use the loss from the diffusion model, but
# this has been exposed just in case.
return self._diffusion.training_losses(*args, **kwargs)
# diffusion related methods:
def q_sample(self, *args, **kwargs):
return self._diffusion.q_sample(*args, **kwargs)
def p_mean_variance(self, *args, **kwargs):
return self._diffusion.p_mean_variance(*args, **kwargs)
def p_sample(self, *args, **kwargs):
return self._diffusion.p_sample(*args, **kwargs)
def p_sample_loop(self, *args, **kwargs):
return self._diffusion.p_sample_loop(*args, **kwargs)
def p_sample_loop_progressive(self, *args, **kwargs):
return self._diffusion.p_sample_loop_progressive(*args, **kwargs)
# schedule sampler related methods:
def sample_timesteps(self, *args, **kwargs):
return self._schedule_sampler.sample(*args, **kwargs)
| [] |
2024-01-10 | ShreyJ1729/autobuild-experiments | experiments~misc~experiments~embedding-search~instruct_embeddings.py | import os
import test
from langchain.embeddings import HuggingFaceInstructEmbeddings
from openai.embeddings_utils import cosine_similarity
query_embedding = HuggingFaceInstructEmbeddings(
query_instruction="Represent the query for retrieving details from product reviews; Input: "
)
doc_embeddings = HuggingFaceInstructEmbeddings(
query_instruction="Represent the product review for product details and quality; Input: "
)
# load INSTRUCTOR_Transformer
# max_seq_length 512
good_review = "It ended up fitting me just fine. Overall this is a great jacket! I live in Idaho and it is a great in between jacket for cold weather. I really like the tactical look and the ability to change out the patches whenever I want (of course, you have to order those separately). Will most likely order another color! Would definitely recommend."
bad_review = "Seemed to be good quality then the first wash the zipper came apart. Terrible quality. I would not recommend this jacket."
bad_review2 = "very bad thing! dont by ever in ur life it is not good thing at all!"
good_embed = doc_embeddings.embed_query(good_review)
bad_embed = doc_embeddings.embed_query(bad_review)
bad_embed2 = doc_embeddings.embed_query(bad_review2)
# get cosine similarity using openai
print(cosine_similarity(good_embed, bad_embed))
print(cosine_similarity(good_embed, bad_embed2))
print(cosine_similarity(bad_embed, bad_embed2))
# prompt
query = "What is the quality of the jacket?"
prompt = query_embedding.embed_query(query)
# get cosine similarity between prompt and reviews.
# higher number = more relevant the review is to the query (more details)
print(cosine_similarity(prompt, good_embed))
print(cosine_similarity(prompt, bad_embed))
print(cosine_similarity(prompt, bad_embed2))
"""
chapters:
- 1
- p1
- p2
- p3
- 2
- p1
- p2
- p3
- 3
- p1
- p2
- p3
cosine(query, c1) vs cosine(query, c2) vs cosine(query, c3)
extract top n chapters, for each:
cosine(query, p1) vs cosine(query, p2) vs cosine(query, p3)
extract top m paragraphs, for each:
cosine(query, s1) vs cosine(query, s2) vs cosine(query, s3)
extract top k sentences
combine all information into gpt model for summarization
"""
| [] |
2024-01-10 | ShreyJ1729/autobuild-experiments | experiments~v2.py | import openai
import os
import subprocess
import dotenv
import json
def load_openai_key():
dotenv.load_dotenv("../.env")
openai.api_key = os.getenv("OPENAI_API_KEY")
print(openai.api_key)
def run_prompt(messageList):
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo", messages=messageList
)
return completion
load_openai_key()
# read in data from ./prompt.txt to use as prompt
with open("./prompts/mermaid_editor.txt", "r") as f:
prompt = f.read()
messageList = [
{
"role": "user",
"content": "You101877033913227971761295070160980610187703391322797176129507016098066813880175468350861773670223418357902358559237000913340905612021789257704507741610564402683381674977935613929034615038555687041872443554849035151760389068636843314198097475701831888541063127905166958647781016507096192284975841074310739605354101661126126923623416451293057912405859004311205310171073063185071160152794414213983826703489527535675419697941563708241440829547386864211092665142518817412746672206022620984205851972985122785965686658502083732524003660438264025294320109717420284262205758311616389932918034259099929912924225760028766615333297226151361123438340314337698226224239238149480472928818827888349198387464415685416884696103258921142433879147922501611128367596770598779709072839852226973632700884336475718023603858517298404204956900259871490045527075083603003749322815143650015895204110421454028929833503693485156332043073173917033716861596254543920704308790544201822505259164895453787693332036988364497914214961915545962366836285416268098805627028342477216697229540012183544597267498709205575348947003460069726143116851892334311538164126840707507532632297247135053825270138478271375821935072652737869020514489272082691008268478267989260555236255972704257838672573602907831471834593106813880175468350861773670223418357902358559237000913340905612021789257704507741610564402683381674977935613929034615038555687041872443554849035151760389068636843314198097475701831888541063127905166958647781016507096192284975841074310739605354101661126126923623416451293057912405859004311205310171073063185071160152794414213983826703489527535675419697941563708241440829547386864211092665142518817412746672206022620984205851972985122785965686658502083732524003660438264025294320109717420284262205758311616389932918034259099929912924225760028766615333297226151361123438340314337698226224239238149480472928818827888349198387464415685416884696103258921142433879147922501611128367596770598779709072839852226973632700884336475718023603858517298404204956900259871490045527075083603003749322815143650015895204110421454028929833503693485156332043073173917033716861596254543920704308790544201822505259164895453787693332036988364497914214961915545962366836285416268098805627028342477216697229540012183544597267498709205575348947003460069726143116851892334311538164126840707507532632297247135053825270138478271375821935072652737869020514489272082691008268478267989260555236255972704257838672573602907831471834593101018770339132279717612950701609806681388017546835086177367022341835790235855923700091334090561202178925770450774161056440268338167497793561392903461503855568704187244355484903515176038906863684331419809747570183188854106312790516695864778101650709619228497584107431073960535410166112612692362341645129305791240585900431120531017107306318507116015279441421398382670348952753567541969794156370824144082954738686421109266514251881741274667220602262098420585197298512278596568665850208373252400366043826402529432010971742028426220575831161638993291803425909992991292422576002876661533329722615136112343834031433769822622423923814948047292881882788834919838746441568541688469610325892114243387914792250161112836759677059877970907283985222697363270088433647571802360385851729840420495690025987149004552707508360300374932281514365001589520411042145402892983350369348515633204307317391703371686159625454392070430879054420182250525916489545378769333203698836449791421496191554596236683628541626809880562702834247721669722954001218354459726749870920557534894700346006972614311685189233431153816412684070750753263229724713505382527013847827137582193507265273786902051448927208269100826847826798926055523625597270425783867257360290783147183459310 are a helpful code-genera1018770339132279717612950701609806681388017546835086177367022341835790235855923700091334090561202178925770450774161056440268338167497793561392903461503855568704187244355484903515176038906863684331419809747570183188854106312790516695864778101650709619228497584107431073960535410166112612692362341645129305791240585900431120531017107306318507116015279441421398382670348952753567541969794156370824144082954738686421109266514251881741274667220602262098420585197298512278596568665850208373252400366043826402529432010971742028426220575831161638993291803425909992991292422576002876661533329722615136112343834031433769822622423923814948047292881882788834919838746441568541688469610325892114243387914792250161112836759677059877970907283985222697363270088433647571802360385851729840420495690025987149004552707508360300374932281514365001589520411042145402892983350369348515633204307317391703371686159625454392070430879054420182250525916489545378769333203698836449791421496191554596236683628541626809880562702834247721669722954001218354459726749870920557534894700346006972614311685189233431153816412684070750753263229724713505382527013847827137582193507265273786902051448927208269100826847826798926055523625597270425783867257360290783147183459310tion bot. You help users architect and write programs in any language. You retain conversation history, so the user can mention things previously said in the conversation.",
},
{
"role": "assistant",
"content": "Got i1018770339132279717612950701609806681388017546835086177367022341835790235855923700091334090561202178925770450774161056440268338167497793561392903461503855568704187244355484903515176038906863684331419809747570183188854106312790516695864778101650709619228497584107431073960535410166112612692362341645129305791240585900431120531017107306318507116015279441421398382670348952753567541969794156370824144082954738686421109266514251881741274667220602262098420585197298512278596568665850208373252400366043826402529432010971742028426220575831161638993291803425909992991292422576002876661533329722615136112343834031433769822622423923814948047292881882788834919838746441568541688469610325892114243387914792250161112836759677059877970907283985222697363270088433647571802360385851729840420495690025987149004552707508360300374932281514365001589520411042145402892983350369348515633204307317391703371686159625454392070430879054420182250525916489545378769333203698836449791421496191554596236683628541626809880562702834247721669722954001218354459726749870920557534894700346006972614311685189233431153816412684070750753263229724713505382527013847827137582193507265273786902051448927208269100826847826798926055523625597270425783867257360290783147183459310t!",
},
{
"role": "user",
"content": prompt
+ "m 10187703391322797176129507016098066813880sslfkmvslmfvslkfvlsmfksldfssldflkdmfsmdfsldfmskdsfldmlsdksdlfksldkfslkdfsmklsdmfksldfsmdfklskdm1754sk6835086177367022341835790235855923700091334090561202178925770450774161056440268338167497793561392903461503855568704187244355484903515176038906863684331419809747570183188854106312790516695864778101650709619228497584107431073960535410166112612692362341645129305791240585900431120531017107306318507116015279441421398382670348952753567541969794156370824144082954738686421109266514251881741274667220602262098420585197298512278596568665850208373252400366043826402529432010971742028426220575831161638993291803425909992991292422576002876661533329722615136112343834031433769822622423923814948047292881882788834919838746441568541688469610325892114243387914792250161112836759677059877970907283985222697363270088433647571802360385851729840420495690025987149004552707508360300374932281514365001589520411042145402892983350369348515633204307317391703371686159625454392070430879054420182250525916489545378769333203698836449791421496191554596236683628541626809880562702834247721669722954001218354459726749870920557534894700346006972614311685189233431153816412684070750753263229724713505382527013847827137582193507265273786902051448927208269100826847826798926055523625597270425783867257360290783147183459310",
},
]
print(run_prompt(messageList))
| [
"PLACEHOLDERm 10187703391322797176129507016098066813880sslfkmvslmfvslkfvlsmfksldfssldflkdmfsmdfsldfmskdsfldmlsdksdlfksldkfslkdfsmklsdmfksldfsmdfklskdm1754sk6835086177367022341835790235855923700091334090561202178925770450774161056440268338167497793561392903461503855568704187244355484903515176038906863684331419809747570183188854106312790516695864778101650709619228497584107431073960535410166112612692362341645129305791240585900431120531017107306318507116015279441421398382670348952753567541969794156370824144082954738686421109266514251881741274667220602262098420585197298512278596568665850208373252400366043826402529432010971742028426220575831161638993291803425909992991292422576002876661533329722615136112343834031433769822622423923814948047292881882788834919838746441568541688469610325892114243387914792250161112836759677059877970907283985222697363270088433647571802360385851729840420495690025987149004552707508360300374932281514365001589520411042145402892983350369348515633204307317391703371686159625454392070430879054420182250525916489545378769333203698836449791421496191554596236683628541626809880562702834247721669722954001218354459726749870920557534894700346006972614311685189233431153816412684070750753263229724713505382527013847827137582193507265273786902051448927208269100826847826798926055523625597270425783867257360290783147183459310",
"Got i1018770339132279717612950701609806681388017546835086177367022341835790235855923700091334090561202178925770450774161056440268338167497793561392903461503855568704187244355484903515176038906863684331419809747570183188854106312790516695864778101650709619228497584107431073960535410166112612692362341645129305791240585900431120531017107306318507116015279441421398382670348952753567541969794156370824144082954738686421109266514251881741274667220602262098420585197298512278596568665850208373252400366043826402529432010971742028426220575831161638993291803425909992991292422576002876661533329722615136112343834031433769822622423923814948047292881882788834919838746441568541688469610325892114243387914792250161112836759677059877970907283985222697363270088433647571802360385851729840420495690025987149004552707508360300374932281514365001589520411042145402892983350369348515633204307317391703371686159625454392070430879054420182250525916489545378769333203698836449791421496191554596236683628541626809880562702834247721669722954001218354459726749870920557534894700346006972614311685189233431153816412684070750753263229724713505382527013847827137582193507265273786902051448927208269100826847826798926055523625597270425783867257360290783147183459310t!",
"You101877033913227971761295070160980610187703391322797176129507016098066813880175468350861773670223418357902358559237000913340905612021789257704507741610564402683381674977935613929034615038555687041872443554849035151760389068636843314198097475701831888541063127905166958647781016507096192284975841074310739605354101661126126923623416451293057912405859004311205310171073063185071160152794414213983826703489527535675419697941563708241440829547386864211092665142518817412746672206022620984205851972985122785965686658502083732524003660438264025294320109717420284262205758311616389932918034259099929912924225760028766615333297226151361123438340314337698226224239238149480472928818827888349198387464415685416884696103258921142433879147922501611128367596770598779709072839852226973632700884336475718023603858517298404204956900259871490045527075083603003749322815143650015895204110421454028929833503693485156332043073173917033716861596254543920704308790544201822505259164895453787693332036988364497914214961915545962366836285416268098805627028342477216697229540012183544597267498709205575348947003460069726143116851892334311538164126840707507532632297247135053825270138478271375821935072652737869020514489272082691008268478267989260555236255972704257838672573602907831471834593106813880175468350861773670223418357902358559237000913340905612021789257704507741610564402683381674977935613929034615038555687041872443554849035151760389068636843314198097475701831888541063127905166958647781016507096192284975841074310739605354101661126126923623416451293057912405859004311205310171073063185071160152794414213983826703489527535675419697941563708241440829547386864211092665142518817412746672206022620984205851972985122785965686658502083732524003660438264025294320109717420284262205758311616389932918034259099929912924225760028766615333297226151361123438340314337698226224239238149480472928818827888349198387464415685416884696103258921142433879147922501611128367596770598779709072839852226973632700884336475718023603858517298404204956900259871490045527075083603003749322815143650015895204110421454028929833503693485156332043073173917033716861596254543920704308790544201822505259164895453787693332036988364497914214961915545962366836285416268098805627028342477216697229540012183544597267498709205575348947003460069726143116851892334311538164126840707507532632297247135053825270138478271375821935072652737869020514489272082691008268478267989260555236255972704257838672573602907831471834593101018770339132279717612950701609806681388017546835086177367022341835790235855923700091334090561202178925770450774161056440268338167497793561392903461503855568704187244355484903515176038906863684331419809747570183188854106312790516695864778101650709619228497584107431073960535410166112612692362341645129305791240585900431120531017107306318507116015279441421398382670348952753567541969794156370824144082954738686421109266514251881741274667220602262098420585197298512278596568665850208373252400366043826402529432010971742028426220575831161638993291803425909992991292422576002876661533329722615136112343834031433769822622423923814948047292881882788834919838746441568541688469610325892114243387914792250161112836759677059877970907283985222697363270088433647571802360385851729840420495690025987149004552707508360300374932281514365001589520411042145402892983350369348515633204307317391703371686159625454392070430879054420182250525916489545378769333203698836449791421496191554596236683628541626809880562702834247721669722954001218354459726749870920557534894700346006972614311685189233431153816412684070750753263229724713505382527013847827137582193507265273786902051448927208269100826847826798926055523625597270425783867257360290783147183459310 are a helpful code-genera1018770339132279717612950701609806681388017546835086177367022341835790235855923700091334090561202178925770450774161056440268338167497793561392903461503855568704187244355484903515176038906863684331419809747570183188854106312790516695864778101650709619228497584107431073960535410166112612692362341645129305791240585900431120531017107306318507116015279441421398382670348952753567541969794156370824144082954738686421109266514251881741274667220602262098420585197298512278596568665850208373252400366043826402529432010971742028426220575831161638993291803425909992991292422576002876661533329722615136112343834031433769822622423923814948047292881882788834919838746441568541688469610325892114243387914792250161112836759677059877970907283985222697363270088433647571802360385851729840420495690025987149004552707508360300374932281514365001589520411042145402892983350369348515633204307317391703371686159625454392070430879054420182250525916489545378769333203698836449791421496191554596236683628541626809880562702834247721669722954001218354459726749870920557534894700346006972614311685189233431153816412684070750753263229724713505382527013847827137582193507265273786902051448927208269100826847826798926055523625597270425783867257360290783147183459310tion bot. You help users architect and write programs in any language. You retain conversation history, so the user can mention things previously said in the conversation."
] |
2024-01-10 | Rogger-Ortiz/TheEntity | cogs~themes.py | import discord
from discord.ext import commands
import os
import random
import openai
defaultEmbedColor=discord.Color(0xe67e22)
green = discord.Color(0x00FF00)
red = discord.Color(0xFF0000)
openai.api_key = os.getenv("DALLE_key")
async def setStatus(self):
theme = ""
with open('/home/captain/boot/NTT/files/theme.txt', 'r') as t:
theme = t.readlines()[0].strip()
status = random.randint(1,3)
response = ""
match theme:
case "default":
match status:
case 1:
await self.bot.change_presence(activity=discord.Game(name=str("with the bugs in my code")))
# response = openai.ChatCompletion.create(
# model="gpt-3.5-turbo",
# messages=[
# {"role": "system", "content": "You are a Discord status generator"},
# {"role": "user", "content": "Generate a short but witty discord status for a Bot that is doing nothing that starts with the word \"Playing\""}
# ]
# )
# response = response['choices'][0]['message']['content']
# response = response.split("\"")
# await self.bot.change_presence(activity=discord.Game(name=str(response[1].split("Playing")[1])))
# response = ""
case 2:
await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=str("the birds chirp")))
# response = openai.ChatCompletion.create(
# model="gpt-3.5-turbo",
# messages=[
# {"role": "system", "content": "You are a Discord status generator"},
# {"role": "user", "content": "Generate a short but witty discord status for a Bot that is doing nothing that starts with the words \"Listening to\""}
# ]
# )
# response = response['choices'][0]['message']['content']
# response = response.split("\"")
# await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=str(response[1].split("Listening to")[1])))
# response = ""
case 3:
await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=str("the day go by")))
# response = openai.ChatCompletion.create(
# model="gpt-3.5-turbo",
# messages=[
# {"role": "system", "content": "You are a Discord status generator"},
# {"role": "user", "content": "Generate a short but witty discord status for a Bot that is doing nothing that starts with the word \"Watching\""}
# ]
# )
# response = response['choices'][0]['message']['content']
# response = response.split("\"")
# await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=str(response[1].split("Watching")[1])))
# response = ""
case "winter":
match status:
case 1:
await self.bot.change_presence(activity=discord.Game(name="with my new toys!"))
case 2:
await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="carols!"))
case 3:
await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="the snow fall!"))
class ThemesCog(commands.Cog):
def __init__(self,bot):
self.bot = bot
async def changeStatus(self):
await setStatus(self)
#return
@commands.Cog.listener()
async def on_ready(self):
print("Online!")
await setStatus(self)
print("Set status!")
# Print code here
@commands.command(name="theme", hidden=True)
@commands.cooldown(1, 600, commands.BucketType.guild)
@commands.has_permissions(administrator = True)
async def theme(self, ctx, arg=None):
theme = str(arg)
match arg:
case None:
defaultEmbed = discord.Embed(color=defaultEmbedColor)
dirs = ""
for dir in os.listdir('/home/captain/boot/NTT/files/themes/'):
dirs+=str(dir)+'\n'
defaultEmbed.add_field(name="Available themes:", value=dirs)
await ctx.reply(embed=defaultEmbed)
case "default":
themesEmbed = discord.Embed(color=green,description=":white_check_mark: Done! Welcome to The Campfire!")
with open('/home/captain/boot/NTT/files/themes/default/TheIcon.gif', 'rb') as icon:
await ctx.guild.edit(icon=icon.read())
with open('/home/captain/boot/NTT/files/themes/default/TheCampfire.jpg', 'rb') as banner:
await ctx.guild.edit(banner=banner.read())
with open('/home/captain/boot/NTT/files/themes/default/TheEntity.jpg', 'rb') as pfp:
await self.bot.user.edit(avatar=pfp.read())
with open('/home/captain/boot/NTT/files/theme.txt', 'w') as theme:
theme.write("default")
await ctx.reply(embed=themesEmbed)
case "winter":
themesEmbed = discord.Embed(color=green,description=":white_check_mark: Done! Happy Holidays!")
with open('/home/captain/boot/NTT/files/themes/winter/XmasIcon.gif', 'rb') as icon:
await ctx.guild.edit(icon=icon.read())
with open('/home/captain/boot/NTT/files/themes/winter/XmasCampfire.jpg', 'rb') as banner:
await ctx.guild.edit(banner=banner.read())
with open('/home/captain/boot/NTT/files/themes/winter/XmasEntity.jpg', 'rb') as pfp:
await self.bot.user.edit(avatar=pfp.read())
with open('/home/captain/boot/NTT/files/theme.txt', 'w') as theme:
theme.write("winter")
await ctx.reply(embed=themesEmbed)
await setStatus(self)
async def setup(bot):
await bot.add_cog(ThemesCog(bot))
| [] |
2024-01-10 | Rogger-Ortiz/TheEntity | entity.py | import discord
from discord.ext import tasks, commands
import nest_asyncio
import os
import random
import time
from os.path import exists
import subprocess
from time import sleep
import datetime
import asyncio
import openai
import json
from lxml import html
from lxml import etree
import requests
import threading
from threading import Thread
import cogs.themes
from pytz import timezone
#############################################################################################
###################### Global Initializations #############################
#############################################################################################
intents = discord.Intents.all()
nest_asyncio.apply()
bot = commands.Bot(command_prefix='$', intents=intents)
client = discord.Client(intents=intents)
blank = ""
defaultEmbedColor=discord.Color(0xe67e22)
green = discord.Color(0x00FF00)
red = discord.Color(0xFF0000)
initial_extensions = ['cogs.help',
'cogs.themes',
'cogs.birthday',
'cogs.role',
'cogs.dev',
'cogs.ai',
'cogs.service',
#'cogs.tiktok', #Retired due to being IP banned.
'cogs.riot', #Retired due to incompleteness/underuse of features
'cogs.events',
'cogs.qrcode',
'cogs.fun',
'cogs.moderation',
'cogs.vc',
'cogs.gifs',
#'cogs.warframe', #Retired due to no solid API being available
'cogs.gm',
'cogs.dm',
'cogs.lyrics',
'cogs.tasks',
#'cogs.trickrtreat', #Retired until October 2024
'cogs.youtube']
###########################################################
###########################################################
@bot.command(name="enable", hidden=True)
@commands.has_permissions(administrator = True)
async def enable(ctx, arg=None):
if arg == None:
errorEmbed = discord.Embed(color=red)
errorEmbed.add_field(name=":x: Please specify a cog to add!",value="(use $cogs to view them all)")
await ctx.reply(embed=errorEmbed)
try:
await bot.load_extension("cogs."+arg)
successEmbed = discord.Embed(color=green)
successEmbed.add_field(name=f":white_check_mark: {arg} Cog enabled!", value="Enjoy the functionality!")
await ctx.reply(embed=successEmbed)
except:
errorEmbed = discord.Embed(color=red)
errorEmbed.add_field(name=":x: That is not a valid Cog!",value="(use $cogs to view them all)")
await ctx.reply(embed=errorEmbed)
@bot.command(name="disable", hidden=True)
@commands.has_permissions(administrator = True)
async def diable(ctx, arg=None):
if arg == None:
errorEmbed = discord.Embed(color=red)
errorEmbed.add_field(name=":x: Please specify a cog to remove!",value="(use $cogs to view them all)")
await ctx.reply(embed=errorEmbed)
try:
await bot.unload_extension("cogs."+arg)
successEmbed = discord.Embed(color=green)
successEmbed.add_field(name=f":white_check_mark: {arg} Cog disabled!", value="Hold tight while we conduct maintenance")
await ctx.reply(embed=successEmbed)
except:
errorEmbed = discord.Embed(color=red)
errorEmbed.add_field(name=":x: That is not a valid Cog!",value="(use $cogs to view them all)")
await ctx.reply(embed=errorEmbed)
@bot.command(name="cogs", hidden=True)
@commands.has_permissions(administrator = True)
async def cogs(ctx):
value = ""
for ext in initial_extensions:
name = str(ext).replace("cogs.","")
value += name+'\n'
cogEmbed = discord.Embed(color=defaultEmbedColor)
cogEmbed.add_field(name="List of Cogs:", value=value)
await ctx.reply(embed=cogEmbed)
###########################################################
async def loadall():
for ext in initial_extensions:
await bot.load_extension(ext)
bot.remove_command('help')
asyncio.run(loadall())
@bot.event
async def on_ready():
print('Logged on as {0}!'.format(bot.user))
print("Discord.py Version: "+discord.__version__)
themes = bot.get_cog("ThemesCog")
await themes.changeStatus()
bot.run(os.getenv("DPY_key"))
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~playlist_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# a backend
# Copyright 2007, Frank Scholz <[email protected]>
# Copyright 2008, Jean-Michel Sizun <[email protected]>
from twisted.internet import defer
from coherence.upnp.core import utils
from coherence.upnp.core import DIDLLite
from coherence.upnp.core.DIDLLite import classChooser, Container, Resource, DIDLElement
import coherence.extern.louie as louie
from coherence.extern.simple_plugin import Plugin
from coherence import log
from urlparse import urlsplit
import re
from coherence.upnp.core.utils import getPage
from coherence.backend import BackendStore, BackendItem, Container, LazyContainer, \
AbstractBackendStore
class PlaylistItem(BackendItem):
logCategory = 'playlist_store'
def __init__(self, title, stream_url, mimetype):
self.name = title
self.stream_url = stream_url
self.mimetype = mimetype
self.url = stream_url
self.item = None
def get_id(self):
return self.storage_id
def get_item(self):
if self.item == None:
upnp_id = self.get_id()
upnp_parent_id = self.parent.get_id()
if (self.mimetype.startswith('video/')):
item = DIDLLite.VideoItem(upnp_id, upnp_parent_id, self.name)
else:
item = DIDLLite.AudioItem(upnp_id, upnp_parent_id, self.name)
# what to do with MMS:// feeds?
protocol = "http-get"
if self.stream_url.startswith("rtsp://"):
protocol = "rtsp-rtp-udp"
res = Resource(self.stream_url, '%s:*:%s:*' % (protocol,self.mimetype))
res.size = None
item.res.append(res)
self.item = item
return self.item
def get_url(self):
return self.url
class PlaylistStore(AbstractBackendStore):
logCategory = 'playlist_store'
implements = ['MediaServer']
wmc_mapping = {'16': 1000}
description = ('Playlist', 'exposes the list of video/audio streams from a m3u playlist (e.g. web TV listings published by french ISPs such as Free, SFR...).', None)
options = [{'option':'name', 'text':'Server Name:', 'type':'string','default':'my media','help': 'the name under this MediaServer shall show up with on other UPnP clients'},
{'option':'version','text':'UPnP Version:','type':'int','default':2,'enum': (2,1),'help': 'the highest UPnP version this MediaServer shall support','level':'advance'},
{'option':'uuid','text':'UUID Identifier:','type':'string','help':'the unique (UPnP) identifier for this MediaServer, usually automatically set','level':'advance'},
{'option':'playlist_url','text':'Playlist file URL:','type':'string','help':'URL to the playlist file (M3U).'},
]
playlist_url = None;
def __init__(self, server, **kwargs):
AbstractBackendStore.__init__(self, server, **kwargs)
self.playlist_url = self.config.get('playlist_url', 'http://mafreebox.freebox.fr/freeboxtv/playlist.m3u')
self.name = self.config.get('name', 'playlist')
self.init_completed()
def __repr__(self):
return self.__class__.__name__
def append( self, obj, parent):
if isinstance(obj, basestring):
mimetype = 'directory'
else:
mimetype = obj['mimetype']
UPnPClass = classChooser(mimetype)
id = self.getnextID()
update = False
if hasattr(self, 'update_id'):
update = True
item = PlaylistItem( id, obj, parent, mimetype, self.urlbase,
UPnPClass, update=update)
self.store[id] = item
self.store[id].store = self
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
if parent:
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
if mimetype == 'directory':
return self.store[id]
return None
def upnp_init(self):
self.current_connection_id = None
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
['rtsp-rtp-udp:*:video/mpeg:*',
'http-get:*:video/mpeg:*',
'rtsp-rtp-udp:*:audio/mpeg:*',
'http-get:*:audio/mpeg:*'],
default=True)
rootItem = Container(None, self.name)
self.set_root_item(rootItem)
self.retrievePlaylistItems(self.playlist_url, rootItem)
def retrievePlaylistItems (self, url, parent_item):
def gotPlaylist(playlist):
self.info("got playlist")
items = {}
if playlist :
content,header = playlist
lines = content.splitlines().__iter__()
line = lines.next()
while line is not None:
if re.search ( '#EXTINF', line):
channel = re.match('#EXTINF:.*,(.*)',line).group(1)
mimetype = 'video/mpeg'
line = lines.next()
while re.search ( '#EXTVLCOPT', line):
option = re.match('#EXTVLCOPT:(.*)',line).group(1)
if option == 'no-video':
mimetype = 'audio/mpeg'
line = lines.next()
url = line
item = PlaylistItem(channel, url, mimetype)
parent_item.add_child(item)
try:
line = lines.next()
except StopIteration:
line = None
return items
def gotError(error):
self.warning("Unable to retrieve playlist: %s" % url)
print "Error: %s" % error
return None
d = getPage(url)
d.addCallback(gotPlaylist)
d.addErrback(gotError)
return d
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~appletrailers_storage.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Benjamin Kampmann <[email protected]>
"""
This is a Media Backend that allows you to access the Trailers from Apple.com
"""
from coherence.backend import BackendItem, BackendStore
from coherence.upnp.core import DIDLLite
from coherence.upnp.core.utils import ReverseProxyUriResource
from twisted.web import client
from twisted.internet import task, reactor
from coherence.extern.et import parse_xml
XML_URL = "http://www.apple.com/trailers/home/xml/current.xml"
ROOT_ID = 0
class AppleTrailerProxy(ReverseProxyUriResource):
def __init__(self, uri):
ReverseProxyUriResource.__init__(self, uri)
def render(self, request):
request.responseHeaders['user-agent'] = 'QuickTime/7.6.2 (qtver=7.6.2;os=Windows NT 5.1Service Pack 3)'
return ReverseProxyUriResource.render(self, request)
class Trailer(BackendItem):
def __init__(self, parent_id, urlbase, id=None, name=None, cover=None,
url=None):
self.parentid = parent_id
self.id = id
self.name = name
self.cover = cover
if( len(urlbase) and urlbase[-1] != '/'):
urlbase += '/'
self.url = urlbase + str(self.id)
self.location = AppleTrailerProxy(url)
self.item = DIDLLite.VideoItem(id, parent_id, self.name)
self.item.albumArtURI = self.cover
def get_path(self):
return self.url
class Container(BackendItem):
logCategory = 'apple_trailers'
def __init__(self, id, parent_id, name, store=None, \
children_callback=None):
self.id = id
self.parent_id = parent_id
self.name = name
self.mimetype = 'directory'
self.update_id = 0
self.children = []
self.item = DIDLLite.Container(id, parent_id, self.name)
self.item.childCount = None #self.get_child_count()
def get_children(self, start=0, end=0):
if(end - start > 25 or
start - end == start or
end - start == 0):
end = start+25
if end != 0:
return self.children[start:end]
return self.children[start:]
def get_child_count(self):
return len(self.children)
def get_item(self):
return self.item
def get_name(self):
return self.name
def get_id(self):
return self.id
class AppleTrailersStore(BackendStore):
logCategory = 'apple_trailers'
implements = ['MediaServer']
def __init__(self, server, *args, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.next_id = 1000
self.name = kwargs.get('name','Apple Trailers')
self.refresh = int(kwargs.get('refresh', 8)) * (60 *60)
self.trailers = {}
self.wmc_mapping = {'15': 0}
dfr = self.update_data()
# first get the first bunch of data before sending init_completed
dfr.addCallback(lambda x: self.init_completed())
def queue_update(self, result):
reactor.callLater(self.refresh, self.update_data)
return result
def update_data(self):
dfr = client.getPage(XML_URL)
dfr.addCallback(parse_xml)
dfr.addCallback(self.parse_data)
dfr.addCallback(self.queue_update)
return dfr
def parse_data(self, xml_data):
def iterate(root):
for item in root.findall('./movieinfo'):
trailer = self._parse_into_trailer(item)
yield trailer
root = xml_data.getroot()
return task.coiterate(iterate(root))
def _parse_into_trailer(self, item):
"""
info = item.find('info')
for attr in ('title', 'runtime', 'rating', 'studio', 'postdate',
'releasedate', 'copyright', 'director', 'description'):
setattr(trailer, attr, info.find(attr).text)
"""
data = {}
data['id'] = item.get('id')
data['name'] = item.find('./info/title').text
data['cover'] = item.find('./poster/location').text
data['url'] = item.find('./preview/large').text
trailer = Trailer(ROOT_ID, self.urlbase, **data)
duration = None
try:
hours = 0
minutes = 0
seconds = 0
duration = item.find('./info/runtime').text
try:
hours,minutes,seconds = duration.split(':')
except ValueError:
try:
minutes,seconds = duration.split(':')
except ValueError:
seconds = duration
duration = "%d:%02d:%02d" % (int(hours), int(minutes), int(seconds))
except:
pass
try:
trailer.item.director = item.find('./info/director').text
except:
pass
try:
trailer.item.description = item.find('./info/description').text
except:
pass
res = DIDLLite.Resource(trailer.get_path(), 'http-get:*:video/quicktime:*')
res.duration = duration
try:
res.size = item.find('./preview/large').get('filesize',None)
except:
pass
trailer.item.res.append(res)
if self.server.coherence.config.get('transcoding', 'no') == 'yes':
dlna_pn = 'DLNA.ORG_PN=AVC_TS_BL_CIF15_AAC'
dlna_tags = DIDLLite.simple_dlna_tags[:]
dlna_tags[2] = 'DLNA.ORG_CI=1'
url = self.urlbase + str(trailer.id)+'?transcoded=mp4'
new_res = DIDLLite.Resource(url,
'http-get:*:%s:%s' % ('video/mp4', ';'.join([dlna_pn]+dlna_tags)))
new_res.size = None
res.duration = duration
trailer.item.res.append(new_res)
dlna_pn = 'DLNA.ORG_PN=JPEG_TN'
dlna_tags = DIDLLite.simple_dlna_tags[:]
dlna_tags[2] = 'DLNA.ORG_CI=1'
dlna_tags[3] = 'DLNA.ORG_FLAGS=00f00000000000000000000000000000'
url = self.urlbase + str(trailer.id)+'?attachment=poster&transcoded=thumb&type=jpeg'
new_res = DIDLLite.Resource(url,
'http-get:*:%s:%s' % ('image/jpeg', ';'.join([dlna_pn] + dlna_tags)))
new_res.size = None
#new_res.resolution = "160x160"
trailer.item.res.append(new_res)
if not hasattr(trailer.item, 'attachments'):
trailer.item.attachments = {}
trailer.item.attachments['poster'] = data['cover']
self.trailers[trailer.id] = trailer
def get_by_id(self, id):
try:
if int(id) == 0:
return self.container
else:
return self.trailers.get(id,None)
except:
return None
def upnp_init(self):
if self.server:
self.server.connection_manager_server.set_variable( \
0, 'SourceProtocolInfo', ['http-get:*:video/quicktime:*','http-get:*:video/mp4:*'])
self.container = Container(ROOT_ID, -1, self.name)
trailers = self.trailers.values()
trailers.sort(cmp=lambda x,y : cmp(x.get_name().lower(),y.get_name().lower()))
self.container.children = trailers
def __repr__(self):
return self.__class__.__name__
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~core~msearch.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
#
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006, Frank Scholz <[email protected]>
import socket
import time
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.internet import task
from coherence.upnp.core import utils
import coherence.extern.louie as louie
SSDP_PORT = 1900
SSDP_ADDR = '239.255.255.250'
SSDP_ADDR_6 = 'FF05::C'
from coherence import log
class MSearch(DatagramProtocol, log.Loggable):
logCategory = 'msearch'
def __init__(self, ssdp_server, ipv6=False, test=False):
self.ssdp_server = ssdp_server
self._isIPv6 = ipv6
if test == False:
iface = '::' if self._isIPv6 else ''
self.port = reactor.listenUDP(0, self, interface=iface)
self.double_discover_loop = task.LoopingCall(self.double_discover)
self.double_discover_loop.start(120.0)
def datagramReceived(self, data, (host, port)):
cmd, headers = utils.parse_http_response(data)
self.info('datagramReceived from %s:%d, protocol %s code %s' % (host, port, cmd[0], cmd[1]))
if cmd[0].startswith('HTTP/1.') and cmd[1] == '200':
self.msg('for %r', headers['usn'])
if not self.ssdp_server.isKnown(headers['usn']):
self.info('register as remote %s, %s, %s' % (headers['usn'], headers['st'], headers['location']))
self.ssdp_server.register('remote',
headers['usn'], headers['st'],
headers['location'],
headers.get('server', "Unknown Server"),
headers['cache-control'],
host=host)
else:
self.ssdp_server.known[headers['usn']]['last-seen'] = time.time()
self.debug('updating last-seen for %r' % headers['usn'])
# make raw data available
# send out the signal after we had a chance to register the device
louie.send('UPnP.SSDP.datagram_received', None, data, host, port)
def double_discover(self):
" Because it's worth it (with UDP's reliability) "
self.info('send out discovery for ssdp:all')
self.discover()
self.discover()
def _discover(self, addr, port):
req = [ 'M-SEARCH * HTTP/1.1',
'HOST: %s:%d' % (addr, port),
'MAN: "ssdp:discover"',
'MX: 5',
'ST: ssdp:all',
'USER-AGENT: Coherence UDAP/2.0',
'','']
req = '\r\n'.join(req)
try:
self.transport.write(req, (addr, port))
except socket.error, msg:
self.info("failure sending out the discovery message: %r" % msg)
def discover(self):
if self._isIPv6:
self._discover(SSDP_ADDR_6, SSDP_PORT)
else:
self._discover(SSDP_ADDR, SSDP_PORT)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~buzztard_control.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007, Frank Scholz <[email protected]>
from urlparse import urlsplit
from twisted.internet import reactor, protocol
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
from twisted.internet.defer import Deferred
from twisted.python import failure
from twisted.protocols.basic import LineReceiver
from coherence.upnp.core.soap_service import errorCode
from coherence.upnp.core import DIDLLite
from coherence.upnp.core.DIDLLite import classChooser, Container, Resource, DIDLElement
import coherence.extern.louie as louie
from coherence.extern.simple_plugin import Plugin
from coherence import log
class BzClient(LineReceiver, log.Loggable):
logCategory = 'buzztard_client'
def connectionMade(self):
self.info("connected to Buzztard")
self.factory.clientReady(self)
def lineReceived(self, line):
self.debug( "received:", line)
if line == 'flush':
louie.send('Buzztard.Response.flush', None)
elif line.find('event') == 0:
louie.send('Buzztard.Response.event', None, line)
elif line.find('volume') == 0:
louie.send('Buzztard.Response.volume', None, line)
elif line.find('mute') == 0:
louie.send('Buzztard.Response.mute', None, line)
elif line.find('repeat') == 0:
louie.send('Buzztard.Response.repeat', None, line)
elif line.find('playlist') == 0:
louie.send('Buzztard.Response.browse', None, line)
class BzFactory(protocol.ClientFactory, log.Loggable):
logCategory = 'buzztard_factory'
protocol = BzClient
def __init__(self,backend):
self.backend = backend
def clientConnectionFailed(self, connector, reason):
self.error('connection failed:', reason.getErrorMessage())
def clientConnectionLost(self, connector, reason):
self.error('connection lost:', reason.getErrorMessage())
def startFactory(self):
self.messageQueue = []
self.clientInstance = None
def clientReady(self, instance):
self.info("clientReady")
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self.backend)
self.clientInstance = instance
for msg in self.messageQueue:
self.sendMessage(msg)
def sendMessage(self, msg):
if self.clientInstance is not None:
self.clientInstance.sendLine(msg)
else:
self.messageQueue.append(msg)
def rebrowse(self):
self.backend.clear()
self.browse()
def browse(self):
self.sendMessage('browse')
class BzConnection(log.Loggable):
""" a singleton class
"""
logCategory = 'buzztard_connection'
def __new__(cls, *args, **kwargs):
self.debug("BzConnection __new__")
obj = getattr(cls,'_instance_',None)
if obj is not None:
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=kwargs['backend'])
return obj
else:
obj = super(BzConnection, cls).__new__(cls, *args, **kwargs)
cls._instance_ = obj
obj.connection = BzFactory(kwargs['backend'])
reactor.connectTCP( kwargs['host'], kwargs['port'], obj.connection)
return obj
def __init__(self,backend=None,host='localhost',port=7654):
self.debug("BzConnection __init__")
class BuzztardItem(log.Loggable):
logCategory = 'buzztard_item'
def __init__(self, id, name, parent, mimetype, urlbase, host, update=False):
self.id = id
self.name = name
self.mimetype = mimetype
self.parent = parent
if parent:
parent.add_child(self,update=update)
if parent == None:
parent_id = -1
else:
parent_id = parent.get_id()
UPnPClass = classChooser(mimetype, sub='music') # FIXME: this is stupid
self.item = UPnPClass(id, parent_id, self.name)
self.child_count = 0
self.children = []
if( len(urlbase) and urlbase[-1] != '/'):
urlbase += '/'
#self.url = urlbase + str(self.id)
self.url = self.name
if self.mimetype == 'directory':
self.update_id = 0
else:
res = Resource(self.url, 'internal:%s:%s:*' % (host,self.mimetype))
res.size = None
self.item.res.append(res)
self.item.artist = self.parent.name
def __del__(self):
self.debug("BuzztardItem __del__", self.id, self.name)
pass
def remove(self,store):
self.debug("BuzztardItem remove", self.id, self.name, self.parent)
while len(self.children) > 0:
child = self.children.pop()
self.remove_child(child)
del store[int(child.id)]
if self.parent:
self.parent.remove_child(self)
del store[int(self.id)]
del self.item
del self
def add_child(self, child, update=False):
self.children.append(child)
self.child_count += 1
if isinstance(self.item, Container):
self.item.childCount += 1
if update == True:
self.update_id += 1
def remove_child(self, child):
self.debug("remove_from %d (%s) child %d (%s)" % (self.id, self.get_name(), child.id, child.get_name()))
if child in self.children:
self.child_count -= 1
if isinstance(self.item, Container):
self.item.childCount -= 1
self.children.remove(child)
self.update_id += 1
def get_children(self,start=0,request_count=0):
if request_count == 0:
return self.children[start:]
else:
return self.children[start:request_count]
def get_child_count(self):
return self.child_count
def get_id(self):
return self.id
def get_update_id(self):
if hasattr(self, 'update_id'):
return self.update_id
else:
return None
def get_path(self):
return self.url
def get_name(self):
return self.name
def get_parent(self):
return self.parent
def get_item(self):
return self.item
def get_xml(self):
return self.item.toString()
def __repr__(self):
if self.parent == None:
parent = 'root'
else:
parent = str(self.parent.get_id())
return 'id: ' + str(self.id) +'/' + self.name + '/' + parent + ' ' + str(self.child_count) + ' @ ' + self.url
class BuzztardStore(log.Loggable,Plugin):
logCategory = 'buzztard_store'
implements = ['MediaServer']
def __init__(self, server, **kwargs):
self.next_id = 1000
self.config = kwargs
self.name = kwargs.get('name','Buzztard')
self.urlbase = kwargs.get('urlbase','')
if( len(self.urlbase)>0 and
self.urlbase[len(self.urlbase)-1] != '/'):
self.urlbase += '/'
self.host = kwargs.get('host','127.0.0.1')
self.port = int(kwargs.get('port',7654))
self.server = server
self.update_id = 0
self.store = {}
self.parent = None
louie.connect( self.add_content, 'Buzztard.Response.browse', louie.Any)
louie.connect( self.clear, 'Buzztard.Response.flush', louie.Any)
self.buzztard = BzConnection(backend=self,host=self.host,port=self.port)
def __repr__(self):
return str(self.__class__).split('.')[-1]
def add_content(self,line):
data = line.split('|')[1:]
parent = self.append(data[0], 'directory', self.parent)
i = 0
for label in data[1:]:
self.append(':'.join((label,str(i))), 'audio/mpeg', parent)
i += 1
def append( self, name, mimetype, parent):
id = self.getnextID()
update = False
if hasattr(self, 'update_id'):
update = True
self.store[id] = BuzztardItem( id, name, parent, mimetype,
self.urlbase,self.host,update=update)
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
if parent:
#value = '%d,%d' % (parent.get_id(),parent_get_update_id())
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
if mimetype == 'directory':
return self.store[id]
return None
def remove(self, id):
item = self.store[int(id)]
parent = item.get_parent()
item.remove(self.store)
try:
del self.store[int(id)]
except:
pass
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
def clear(self):
for item in self.get_by_id(1000).get_children():
self.remove(item.get_id())
self.buzztard.connection.browse()
def len(self):
return len(self.store)
def get_by_id(self,id):
id = int(id)
if id == 0:
id = 1000
try:
return self.store[id]
except:
return None
def getnextID(self):
ret = self.next_id
self.next_id += 1
return ret
def upnp_init(self):
self.current_connection_id = None
self.parent = self.append('Buzztard', 'directory', None)
source_protocols = ""
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
source_protocols,
default=True)
self.buzztard.connection.browse()
class BuzztardPlayer(log.Loggable):
logCategory = 'buzztard_player'
implements = ['MediaRenderer']
vendor_value_defaults = {'RenderingControl': {'A_ARG_TYPE_Channel':'Master'}}
vendor_range_defaults = {'RenderingControl': {'Volume': {'maximum':100}}}
def __init__(self, device, **kwargs):
self.name = kwargs.get('name','Buzztard MediaRenderer')
self.host = kwargs.get('host','127.0.0.1')
self.port = int(kwargs.get('port',7654))
self.player = None
self.playing = False
self.state = None
self.duration = None
self.view = []
self.tags = {}
self.server = device
self.poll_LC = LoopingCall( self.poll_player)
louie.connect( self.event, 'Buzztard.Response.event', louie.Any)
louie.connect( self.get_volume, 'Buzztard.Response.volume', louie.Any)
louie.connect( self.get_mute, 'Buzztard.Response.mute', louie.Any)
louie.connect( self.get_repeat, 'Buzztard.Response.repeat', louie.Any)
self.buzztard = BzConnection(backend=self,host=self.host,port=self.port)
def event(self,line):
infos = line.split('|')[1:]
self.debug(infos)
if infos[0] == 'playing':
transport_state = 'PLAYING'
if infos[0] == 'stopped':
transport_state = 'STOPPED'
if infos[0] == 'paused':
transport_state = 'PAUSED_PLAYBACK'
if self.server != None:
connection_id = self.server.connection_manager_server.lookup_avt_id(self.current_connection_id)
if self.state != transport_state:
self.state = transport_state
if self.server != None:
self.server.av_transport_server.set_variable(connection_id,
'TransportState', transport_state)
label = infos[1]
position = infos[2].split('.')[0]
duration = infos[3].split('.')[0]
if self.server != None:
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrack', 0)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackDuration', duration)
self.server.av_transport_server.set_variable(connection_id, 'CurrentMediaDuration', duration)
self.server.av_transport_server.set_variable(connection_id, 'RelativeTimePosition', position)
self.server.av_transport_server.set_variable(connection_id, 'AbsoluteTimePosition', position)
try:
self.server.rendering_control_server.set_variable(connection_id, 'Volume', int(infos[4]))
except:
pass
try:
if infos[5] in ['on','1','true','True','yes','Yes']:
mute = True
else:
mute = False
self.server.rendering_control_server.set_variable(connection_id, 'Mute', mute)
except:
pass
try:
if infos[6] in ['on','1','true','True','yes','Yes']:
self.server.av_transport_server.set_variable(connection_id, 'CurrentPlayMode', 'REPEAT_ALL')
else:
self.server.av_transport_server.set_variable(connection_id, 'CurrentPlayMode', 'NORMAL')
except:
pass
def __repr__(self):
return str(self.__class__).split('.')[-1]
def poll_player( self):
self.buzztard.connection.sendMessage('status')
def load( self, uri, metadata):
self.debug("load", uri, metadata)
self.duration = None
self.metadata = metadata
connection_id = self.server.connection_manager_server.lookup_avt_id(self.current_connection_id)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTransportActions','Play,Stop')
self.server.av_transport_server.set_variable(connection_id, 'NumberOfTracks',1)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURIMetaData',metadata)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackMetaData',metadata)
def start( self, uri):
self.load( uri)
self.play()
def stop(self):
self.buzztard.connection.sendMessage('stop')
def play( self):
connection_id = self.server.connection_manager_server.lookup_avt_id(self.current_connection_id)
label_id = self.server.av_transport_server.get_variable('CurrentTrackURI',connection_id).value
id = '0'
if ':' in label_id:
label,id = label_id.split(':')
self.buzztard.connection.sendMessage('play|%s' % id)
def pause( self):
self.buzztard.connection.sendMessage('pause')
def seek(self, location):
"""
@param location: simple number = time to seek to, in seconds
+nL = relative seek forward n seconds
-nL = relative seek backwards n seconds
"""
def mute(self):
self.buzztard.connection.sendMessage('set|mute|on')
def unmute(self):
self.buzztard.connection.sendMessage('set|mute|off')
def get_mute(self,line):
infos = line.split('|')[1:]
if infos[0] in ['on','1','true','True','yes','Yes']:
mute = True
else:
mute = False
self.server.rendering_control_server.set_variable(0, 'Mute', mute)
def get_repeat(self,line):
infos = line.split('|')[1:]
if infos[0] in ['on','1','true','True','yes','Yes']:
self.server.av_transport_server.set_variable(0, 'CurrentPlayMode', 'REPEAT_ALL')
else:
self.server.av_transport_server.set_variable(0, 'CurrentPlayMode', 'NORMAL')
def set_repeat(self, playmode):
if playmode in ['REPEAT_ONE','REPEAT_ALL']:
self.buzztard.connection.sendMessage('set|repeat|on')
else:
self.buzztard.connection.sendMessage('set|repeat|off')
def get_volume(self,line):
infos = line.split('|')[1:]
self.server.rendering_control_server.set_variable(0, 'Volume', int(infos[0]))
def set_volume(self, volume):
volume = int(volume)
if volume < 0:
volume=0
if volume > 100:
volume=100
self.buzztard.connection.sendMessage('set|volume|%d'% volume)
def upnp_init(self):
self.current_connection_id = None
self.server.connection_manager_server.set_variable(0, 'SinkProtocolInfo',
['internal:%s:audio/mpeg:*' % self.host],
default=True)
self.server.av_transport_server.set_variable(0, 'TransportState', 'NO_MEDIA_PRESENT', default=True)
self.server.av_transport_server.set_variable(0, 'TransportStatus', 'OK', default=True)
self.server.av_transport_server.set_variable(0, 'CurrentPlayMode', 'NORMAL', default=True)
self.server.av_transport_server.set_variable(0, 'CurrentTransportActions', '', default=True)
self.buzztard.connection.sendMessage('get|volume')
self.buzztard.connection.sendMessage('get|mute')
self.buzztard.connection.sendMessage('get|repeat')
self.poll_LC.start( 1.0, True)
def upnp_Play(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Speed = int(kwargs['Speed'])
self.play()
return {}
def upnp_Pause(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
self.pause()
return {}
def upnp_Stop(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
self.stop()
return {}
def upnp_SetAVTransportURI(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
CurrentURI = kwargs['CurrentURI']
CurrentURIMetaData = kwargs['CurrentURIMetaData']
local_protocol_info=self.server.connection_manager_server.get_variable('SinkProtocolInfo').value.split(',')
if len(CurrentURIMetaData)==0:
self.load(CurrentURI,CurrentURIMetaData)
return {}
else:
elt = DIDLLite.DIDLElement.fromString(CurrentURIMetaData)
print elt.numItems()
if elt.numItems() == 1:
item = elt.getItems()[0]
for res in item.res:
print res.protocolInfo,local_protocol_info
if res.protocolInfo in local_protocol_info:
self.load(CurrentURI,CurrentURIMetaData)
return {}
return failure.Failure(errorCode(714))
def upnp_SetMute(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Channel = kwargs['Channel']
DesiredMute = kwargs['DesiredMute']
if DesiredMute in ['TRUE', 'True', 'true', '1','Yes','yes']:
self.mute()
else:
self.unmute()
return {}
def upnp_SetVolume(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Channel = kwargs['Channel']
DesiredVolume = int(kwargs['DesiredVolume'])
self.set_volume(DesiredVolume)
return {}
def test_init_complete(backend):
print "Houston, we have a touchdown!"
backend.buzztard.sendMessage('browse')
def main():
louie.connect( test_init_complete, 'Coherence.UPnP.Backend.init_completed', louie.Any)
f = BuzztardStore(None)
f.parent = f.append('Buzztard', 'directory', None)
print f.parent
print f.store
f.add_content('playlist|test label|start|stop')
print f.store
f.clear()
print f.store
f.add_content('playlist|after flush label|flush-start|flush-stop')
print f.store
#def got_upnp_result(result):
# print "upnp", result
#f.upnp_init()
#print f.store
#r = f.upnp_Browse(BrowseFlag='BrowseDirectChildren',
# RequestedCount=0,
# StartingIndex=0,
# ObjectID=0,
# SortCriteria='*',
# Filter='')
#got_upnp_result(r)
if __name__ == '__main__':
from twisted.internet import reactor
reactor.callWhenRunning(main)
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~axiscam_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007, Frank Scholz <[email protected]>
# check http://www.iana.org/assignments/rtp-parameters
# for the RTP payload type identifier
#
from sets import Set
from coherence.upnp.core.DIDLLite import classChooser, Container, Resource, DIDLElement
from coherence.backend import BackendStore,BackendItem
class AxisCamItem(BackendItem):
logCategory = 'axis_cam_item'
def __init__(self, id, obj, parent, mimetype, urlbase, UPnPClass,update=False):
self.id = id
if mimetype == 'directory':
self.name = obj
self.mimetype = mimetype
else:
self.name = obj.get('name')
self.mimetype = mimetype
self.parent = parent
if parent:
parent.add_child(self,update=update)
if parent == None:
parent_id = -1
else:
parent_id = parent.get_id()
self.item = UPnPClass(id, parent_id, self.name)
if isinstance(self.item, Container):
self.item.childCount = 0
self.children = []
if( len(urlbase) and urlbase[-1] != '/'):
urlbase += '/'
if self.mimetype == 'directory':
self.url = urlbase + str(self.id)
else:
self.url = obj.get('url')
if self.mimetype == 'directory':
self.update_id = 0
else:
res = Resource(self.url, obj.get('protocol'))
res.size = None
self.item.res.append(res)
def __del__(self):
#print "AxisCamItem __del__", self.id, self.name
pass
def remove(self):
#print "AxisCamItem remove", self.id, self.name, self.parent
if self.parent:
self.parent.remove_child(self)
del self.item
def add_child(self, child, update=False):
self.children.append(child)
if isinstance(self.item, Container):
self.item.childCount += 1
if update == True:
self.update_id += 1
def remove_child(self, child):
self.info("remove_from %d (%s) child %d (%s)" % (self.id, self.get_name(), child.id, child.get_name()))
if child in self.children:
if isinstance(self.item, Container):
self.item.childCount -= 1
self.children.remove(child)
self.update_id += 1
def get_children(self,start=0,request_count=0):
if request_count == 0:
return self.children[start:]
else:
return self.children[start:request_count]
def get_child_count(self):
return len(self.children)
def get_id(self):
return self.id
def get_update_id(self):
if hasattr(self, 'update_id'):
return self.update_id
else:
return None
def get_path(self):
return self.url
def get_name(self):
return self.name
def get_parent(self):
return self.parent
def get_item(self):
return self.item
def get_xml(self):
return self.item.toString()
def __repr__(self):
return 'id: ' + str(self.id) + ' @ ' + self.url
class AxisCamStore(BackendStore):
logCategory = 'axis_cam_store'
implements = ['MediaServer']
def __init__(self, server, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.next_id = 1000
self.config = kwargs
self.name = kwargs.get('name','AxisCamStore')
self.update_id = 0
self.store = {}
self.wmc_mapping = {'8': 1000}
self.init_completed()
def __repr__(self):
return str(self.__class__).split('.')[-1]
def append( self, obj, parent):
if isinstance(obj, basestring):
mimetype = 'directory'
else:
protocol,network,content_type,info = obj['protocol'].split(':')
mimetype = content_type
UPnPClass = classChooser(mimetype)
id = self.getnextID()
update = False
if hasattr(self, 'update_id'):
update = True
self.store[id] = AxisCamItem( id, obj, parent, mimetype, self.urlbase,
UPnPClass, update=update)
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
if parent:
#value = '%d,%d' % (parent.get_id(),parent_get_update_id())
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
if mimetype == 'directory':
return self.store[id]
return None
def len(self):
return len(self.store)
def get_by_id(self,id):
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
id = int(id)
if id == 0:
id = 1000
try:
return self.store[id]
except:
return None
def getnextID(self):
ret = self.next_id
self.next_id += 1
return ret
def upnp_init(self):
self.current_connection_id = None
parent = self.append('AxisCam', None)
source_protocols = Set()
for k,v in self.config.items():
if isinstance(v,dict):
v['name'] = k
source_protocols.add(v['protocol'])
self.append(v, parent)
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
source_protocols,
default=True)
def main():
f = AxisCamStore(None)
def got_upnp_result(result):
print "upnp", result
#f.upnp_init()
#print f.store
#r = f.upnp_Browse(BrowseFlag='BrowseDirectChildren',
# RequestedCount=0,
# StartingIndex=0,
# ObjectID=0,
# SortCriteria='*',
# Filter='')
#got_upnp_result(r)
if __name__ == '__main__':
from twisted.internet import reactor
reactor.callWhenRunning(main)
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~youtube_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2009, Jean-Michel Sizun
# Copyright 2009 Frank Scholz <[email protected]>
import os.path
from twisted.internet import reactor, threads
from twisted.web import server, static
from twisted.web.error import PageRedirect
from coherence.upnp.core import utils
from coherence.upnp.core.utils import ReverseProxyUriResource, ReverseProxyResource
from coherence.upnp.core import DIDLLite
from coherence.backend import BackendStore,BackendItem
from coherence import log
from gdata.youtube.service import YouTubeService
from coherence.extern.youtubedl import FileDownloader,YoutubeIE,MetacafeIE,YoutubePlaylistIE
from coherence.backends.picasa_storage import Container, LazyContainer, AbstractBackendStore
MPEG4_MIMETYPE = 'video/mp4'
MPEG4_EXTENSION = 'mp4'
class TestVideoProxy(ReverseProxyUriResource, log.Loggable):
logCategory = 'internetVideoProxy'
def __init__(self, uri, id,
proxy_mode,
cache_directory,
cache_maxsize=100000000,
buffer_size=2000000,
fct=None, **kwargs):
ReverseProxyUriResource.__init__(self, uri)
self.id = id
if isinstance(self.id,int):
self.id = '%d' % self.id
self.proxy_mode = proxy_mode
self.cache_directory = cache_directory
self.cache_maxsize = int(cache_maxsize)
self.buffer_size = int(buffer_size)
self.downloader = None
self.video_url = None # the url we get from the youtube page
self.stream_url = None # the real video stream, cached somewhere
self.mimetype = None
self.filesize = 0
self.file_in_cache = False
self.url_extractor_fct = fct
self.url_extractor_params = kwargs
def requestFinished(self, result):
""" self.connection is set in utils.ReverseProxyResource.render """
self.info("ProxyStream requestFinished:",result)
if hasattr(self,'connection'):
self.connection.transport.loseConnection()
def render(self, request):
self.info("VideoProxy render", request, self.stream_url, self.video_url)
self.info("VideoProxy headers:", request.getAllHeaders())
self.info("VideoProxy id:", self.id)
d = request.notifyFinish()
d.addBoth(self.requestFinished)
if self.stream_url is None:
web_url = "http://%s%s" % (self.host,self.path)
self.info("Web_url: %s" % web_url)
def got_real_urls(real_urls):
if len(real_urls) == 0:
self.warning('Unable to retrieve any URL for video stream')
return self.requestFinished(None)
else:
got_real_url(real_urls[0])
def got_real_url(real_url):
self.info("Real URL is %s" % real_url)
self.stream_url = real_url
if self.stream_url is None:
self.warning('Unable to retrieve URL - inconsistent web page')
return self.requestFinished(None) #FIXME
self.stream_url = self.stream_url.encode('ascii', 'strict')
self.resetUri(self.stream_url)
self.info("Video URL: %s" % self.stream_url)
self.video_url = self.stream_url[:]
d = self.followRedirects(request)
d.addCallback(self.proxyURL)
d.addErrback(self.requestFinished)
if self.url_extractor_fct is not None:
d = self.url_extractor_fct(web_url, **self.url_extractor_params)
d.addCallback(got_real_urls)
else:
got_real_url(web_url)
return server.NOT_DONE_YET
reactor.callLater(0.05,self.proxyURL,request)
return server.NOT_DONE_YET
def followRedirects(self, request):
self.info("HTTP redirect ", request, self.stream_url)
d = utils.getPage(self.stream_url, method="HEAD", followRedirect=0)
def gotHeader(result,request):
data,header = result
self.info("finally got something %r", header)
#FIXME what do we do here if the headers aren't there?
self.filesize = int(header['content-length'][0])
self.mimetype = header['content-type'][0]
return request
def gotError(error,request):
# error should be a "Failure" instance at this point
self.info("gotError" % error)
error_value = error.value
if (isinstance(error_value,PageRedirect)):
self.info("got PageRedirect %r" % error_value.location)
self.stream_url = error_value.location
self.resetUri(self.stream_url)
return self.followRedirects(request)
else:
self.warning("Error while retrieving page header for URI ", self.stream_url)
self.requestFinished(None)
return error
d.addCallback(gotHeader, request)
d.addErrback(gotError,request)
return d
def proxyURL(self, request):
self.info("proxy_mode: %s, request %s" % (self.proxy_mode,request.method))
if self.proxy_mode == 'redirect':
# send stream url to client for redirection
request.redirect(self.stream_url)
request.finish()
elif self.proxy_mode in ('proxy',):
res = ReverseProxyResource.render(self,request)
if isinstance(res,int):
return res
request.write(res)
return
elif self.proxy_mode in ('buffer','buffered'):
# download stream to cache,
# and send it to the client in // after X bytes
filepath = os.path.join(self.cache_directory, self.id)
file_is_already_available = False
if (os.path.exists(filepath)
and os.path.getsize(filepath) == self.filesize):
res = self.renderFile(request, filepath)
if isinstance(res,int):
return res
request.write(res)
request.finish()
else:
if request.method != 'HEAD':
self.downloadFile(request, filepath, None)
range = request.getHeader('range')
if range is not None:
bytesrange = range.split('=')
assert bytesrange[0] == 'bytes',\
"Syntactically invalid http range header!"
start, end = bytesrange[1].split('-', 1)
#print "%r %r" %(start,end)
if start:
start = int(start)
if end:
end = int(end)
else:
end = self.filesize -1
# Are we requesting something beyond the current size of the file?
try:
size = os.path.getsize(filepath)
except OSError:
size = 0
if (start >= size and
end+10 > self.filesize and
end-start < 200000):
#print "let's hand that through, it is probably a mp4 index request"
res = ReverseProxyResource.render(self,request)
if isinstance(res,int):
return res
request.write(res)
return
res = self.renderBufferFile (request, filepath, self.buffer_size)
if res == '' and request.method != 'HEAD':
return server.NOT_DONE_YET
if not isinstance(res,int):
request.write(res)
if request.method == 'HEAD':
request.finish()
else:
self.warning("Unsupported Proxy Mode: %s" % self.proxy_mode)
return self.requestFinished(None)
def getMimetype(self):
type = MPEG4_MIMETYPE
if self.mimetype is not None:
type = self.mimetype
return type
def renderFile(self,request,filepath):
self.info('Cache file available %r %r ' %(request, filepath))
downloadedFile = utils.StaticFile(filepath, self.mimetype)
downloadedFile.type = self.getMimetype()
downloadedFile.encoding = None
return downloadedFile.render(request)
def renderBufferFile (self, request, filepath, buffer_size):
# Try to render file(if we have enough data)
self.info("renderBufferFile %s" % filepath)
rendering = False
if os.path.exists(filepath) is True:
filesize = os.path.getsize(filepath)
if ((filesize >= buffer_size) or (filesize == self.filesize)):
rendering = True
self.info("Render file", filepath, self.filesize, filesize, buffer_size)
bufferFile = utils.BufferFile(filepath, self.filesize, MPEG4_MIMETYPE)
bufferFile.type = self.getMimetype()
bufferFile.encoding = None
try:
return bufferFile.render(request)
except Exception,error:
self.info(error)
if request.method != 'HEAD':
self.info('Will retry later to render buffer file')
reactor.callLater(0.5, self.renderBufferFile, request,filepath,buffer_size)
return ''
def downloadFinished(self, result):
self.info('Download finished!')
self.downloader = None
def gotDownloadError(self, error, request):
self.info("Unable to download stream to file: %s" % self.stream_url)
self.info(request)
self.info(error)
def downloadFile(self, request, filepath, callback, *args):
if (self.downloader is None):
self.info("Proxy: download data to cache file %s" % filepath)
self.checkCacheSize()
self.downloader = utils.downloadPage(self.stream_url, filepath, supportPartial=1)
self.downloader.addCallback(self.downloadFinished)
self.downloader.addErrback(self.gotDownloadError, request)
if(callback is not None):
self.downloader.addCallback(callback, request, filepath, *args)
return self.downloader
def checkCacheSize(self):
cache_listdir = os.listdir(self.cache_directory)
cache_size = 0
for filename in cache_listdir:
path = "%s%s%s" % (self.cache_directory, os.sep, filename)
statinfo = os.stat(path)
cache_size += statinfo.st_size
self.info("Cache size: %d (max is %s)" % (cache_size, self.cache_maxsize))
if (cache_size > self.cache_maxsize):
cache_targetsize = self.cache_maxsize * 2/3
self.info("Cache above max size: Reducing to %d" % cache_targetsize)
def compare_atime(filename1, filename2):
path1 = "%s%s%s" % (self.cache_directory, os.sep, filename1)
path2 = "%s%s%s" % (self.cache_directory, os.sep, filename2)
cmp = int(os.stat(path1).st_atime - os.stat(path2).st_atime)
return cmp
cache_listdir = sorted(cache_listdir,compare_atime)
while (cache_size > cache_targetsize):
filename = cache_listdir.pop(0)
path = "%s%s%s" % (self.cache_directory, os.sep, filename)
cache_size -= os.stat(path).st_size
os.remove(path)
self.info("removed %s" % filename)
self.info("new cache size is %d" % cache_size)
class YoutubeVideoItem(BackendItem):
def __init__(self, external_id, title, url, mimetype, entry, store):
self.external_id = external_id
self.name = title
self.duration = None
self.size = None
self.mimetype = mimetype
self.description = None
self.date = None
self.item = None
self.youtube_entry = entry
self.store = store
def extractDataURL(url, quality):
if (quality == 'hd'):
format = '22'
else:
format = '18'
kwargs = {
'usenetrc': False,
'quiet': True,
'forceurl': True,
'forcetitle': False,
'simulate': True,
'format': format,
'outtmpl': u'%(id)s.%(ext)s',
'ignoreerrors': True,
'ratelimit': None,
}
if len(self.store.login) > 0:
kwargs['username'] = self.store.login
kwargs['password'] = self.store.password
fd = FileDownloader(kwargs)
youtube_ie = YoutubeIE()
fd.add_info_extractor(YoutubePlaylistIE(youtube_ie))
fd.add_info_extractor(MetacafeIE(youtube_ie))
fd.add_info_extractor(youtube_ie)
deferred = fd.get_real_urls([url])
return deferred
#self.location = VideoProxy(url, self.external_id,
# store.proxy_mode,
# store.cache_directory, store.cache_maxsize, store.buffer_size,
# extractDataURL, quality=self.store.quality)
self.location = TestVideoProxy(url, self.external_id,
store.proxy_mode,
store.cache_directory, store.cache_maxsize,store.buffer_size,
extractDataURL, quality=self.store.quality)
def get_item(self):
if self.item == None:
upnp_id = self.get_id()
upnp_parent_id = self.parent.get_id()
self.item = DIDLLite.VideoItem(upnp_id, upnp_parent_id, self.name)
self.item.description = self.description
self.item.date = self.date
# extract thumbnail from youtube entry
# we take the last one, hoping this is the bigger one
thumbnail_url = None
for image in self.youtube_entry.media.thumbnail:
thumbnail_url = image.url
if thumbnail_url is not None:
self.item.albumArtURI = thumbnail_url
res = DIDLLite.Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
res.duration = self.duration
res.size = self.size
self.item.res.append(res)
return self.item
def get_path(self):
self.url = self.store.urlbase + str(self.storage_id) + "." + MPEG4_EXTENSION
return self.url
def get_id(self):
return self.storage_id
class YouTubeStore(AbstractBackendStore):
logCategory = 'youtube_store'
implements = ['MediaServer']
description = ('Youtube', 'connects to the YouTube service and exposes the standard feeds (public) and the uploads/favorites/playlists/subscriptions of a given user.', None)
options = [{'option':'name', 'text':'Server Name:', 'type':'string','default':'my media','help': 'the name under this MediaServer shall show up with on other UPnP clients'},
{'option':'version','text':'UPnP Version:','type':'int','default':2,'enum': (2,1),'help': 'the highest UPnP version this MediaServer shall support','level':'advance'},
{'option':'uuid','text':'UUID Identifier:','type':'string','help':'the unique (UPnP) identifier for this MediaServer, usually automatically set','level':'advance'},
{'option':'refresh','text':'Refresh period','type':'string'},
{'option':'login','text':'User ID:','type':'string','group':'User Account'},
{'option':'password','text':'Password:','type':'string','group':'User Account'},
{'option':'location','text':'Locale:','type':'string'},
{'option':'quality','text':'Video quality:','type':'string', 'default':'sd','enum': ('sd','hd')},
{'option':'standard_feeds','text':'Include standard feeds:','type':'bool', 'default': True},
{'option':'proxy_mode','text':'Proxy mode:','type':'string', 'enum': ('redirect','proxy','cache','buffered')},
{'option':'buffer_size','text':'Buffering size:','type':'int'},
{'option':'cache_directory','text':'Cache directory:','type':'dir', 'group':'Cache'},
{'option':'cache_maxsize','text':'Cache max size:','type':'int', 'group':'Cache'},
]
def __init__(self, server, **kwargs):
AbstractBackendStore.__init__(self, server, **kwargs)
self.name = kwargs.get('name','YouTube')
self.login = kwargs.get('userid',kwargs.get('login',''))
self.password = kwargs.get('password','')
self.locale = kwargs.get('location',None)
self.quality = kwargs.get('quality','sd')
self.showStandardFeeds = (kwargs.get('standard_feeds','True') in ['Yes','yes','true','True','1'])
self.refresh = int(kwargs.get('refresh',60))*60
self.proxy_mode = kwargs.get('proxy_mode', 'redirect')
self.cache_directory = kwargs.get('cache_directory', '/tmp/coherence-cache')
try:
if self.proxy_mode != 'redirect':
os.mkdir(self.cache_directory)
except:
pass
self.cache_maxsize = kwargs.get('cache_maxsize', 100000000)
self.buffer_size = kwargs.get('buffer_size', 750000)
rootItem = Container(None, self.name)
self.set_root_item(rootItem)
if (self.showStandardFeeds):
standardfeeds_uri = 'http://gdata.youtube.com/feeds/api/standardfeeds'
if self.locale is not None:
standardfeeds_uri += "/%s" % self.locale
standardfeeds_uri += "/%s"
self.appendFeed('Most Viewed', standardfeeds_uri % 'most_viewed', rootItem)
self.appendFeed('Top Rated', standardfeeds_uri % 'top_rated', rootItem)
self.appendFeed('Recently Featured', standardfeeds_uri % 'recently_featured', rootItem)
self.appendFeed('Watch On Mobile', standardfeeds_uri % 'watch_on_mobile', rootItem)
self.appendFeed('Most Discussed', standardfeeds_uri % 'most_discussed', rootItem)
self.appendFeed('Top Favorites', standardfeeds_uri % 'top_favorites', rootItem)
self.appendFeed('Most Linked', standardfeeds_uri % 'most_linked', rootItem)
self.appendFeed('Most Responded', standardfeeds_uri % 'most_responded', rootItem)
self.appendFeed('Most Recent', standardfeeds_uri % 'most_recent', rootItem)
if len(self.login) > 0:
userfeeds_uri = 'http://gdata.youtube.com/feeds/api/users/%s/%s'
self.appendFeed('My Uploads', userfeeds_uri % (self.login,'uploads'), rootItem)
self.appendFeed('My Favorites', userfeeds_uri % (self.login,'favorites'), rootItem)
playlistsItem = LazyContainer(rootItem, 'My Playlists', None, self.refresh, self.retrievePlaylistFeeds)
rootItem.add_child(playlistsItem)
subscriptionsItem = LazyContainer(rootItem, 'My Subscriptions', None, self.refresh, self.retrieveSubscriptionFeeds)
rootItem.add_child(subscriptionsItem)
self.init_completed()
def __repr__(self):
return self.__class__.__name__
def appendFeed( self, name, feed_uri, parent):
item = LazyContainer(parent, name, None, self.refresh, self.retrieveFeedItems, feed_uri=feed_uri)
parent.add_child(item, external_id=feed_uri)
def appendVideoEntry(self, entry, parent):
external_id = entry.id.text.split('/')[-1]
title = entry.media.title.text
url = entry.media.player.url
mimetype = MPEG4_MIMETYPE
#mimetype = 'video/mpeg'
item = YoutubeVideoItem (external_id, title, url, mimetype, entry, self)
item.parent = parent
parent.add_child(item, external_id=external_id)
def upnp_init(self):
self.current_connection_id = None
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
['http-get:*:%s:*' % MPEG4_MIMETYPE],
default=True)
self.wmc_mapping = {'15': self.get_root_id()}
self.yt_service = YouTubeService()
self.yt_service.client_id = 'ytapi-JeanMichelSizun-youtubebackendpl-ruabstu7-0'
self.yt_service.developer_key = 'AI39si7dv2WWffH-s3pfvmw8fTND-cPWeqF1DOcZ8rwTgTPi4fheX7jjQXpn7SG61Ido0Zm_9gYR52TcGog9Pt3iG9Sa88-1yg'
self.yt_service.email = self.login
self.yt_service.password = self.password
self.yt_service.source = 'Coherence UPnP backend'
if len(self.login) > 0:
d = threads.deferToThread(self.yt_service.ProgrammaticLogin)
def retrieveFeedItems (self, parent=None, feed_uri=''):
feed = threads.deferToThread(self.yt_service.GetYouTubeVideoFeed, feed_uri)
def gotFeed(feed):
if feed is None:
self.warning("Unable to retrieve feed %s" % feed_uri)
return
for entry in feed.entry:
self.appendVideoEntry(entry, parent)
def gotError(error):
self.warning("ERROR: %s" % error)
feed.addCallbacks(gotFeed, gotError)
return feed
def retrievePlaylistFeedItems (self, parent, playlist_id):
feed = threads.deferToThread(self.yt_service.GetYouTubePlaylistVideoFeed,playlist_id=playlist_id)
def gotFeed(feed):
if feed is None:
self.warning("Unable to retrieve playlist items %s" % feed_uri)
return
for entry in feed.entry:
self.appendVideoEntry(entry, parent)
def gotError(error):
self.warning("ERROR: %s" % error)
feed.addCallbacks(gotFeed, gotError)
return feed
def retrieveSubscriptionFeedItems (self, parent, uri):
entry = threads.deferToThread(self.yt_service.GetYouTubeSubscriptionEntry,uri)
def gotEntry(entry):
if entry is None:
self.warning("Unable to retrieve subscription items %s" % uri)
return
feed_uri = entry.feed_link[0].href
return self.retrieveFeedItems(parent, feed_uri)
def gotError(error):
self.warning("ERROR: %s" % error)
entry.addCallbacks(gotEntry, gotError)
return entry
def retrievePlaylistFeeds(self, parent):
playlists_feed = threads.deferToThread(self.yt_service.GetYouTubePlaylistFeed, username=self.login)
def gotPlaylists(playlist_video_feed):
if playlist_video_feed is None:
self.warning("Unable to retrieve playlists feed")
return
for playlist_video_entry in playlist_video_feed.entry:
title = playlist_video_entry.title.text
playlist_id = playlist_video_entry.id.text.split("/")[-1] # FIXME find better way to retrieve the playlist ID
item = LazyContainer(parent, title, playlist_id, self.refresh, self.retrievePlaylistFeedItems, playlist_id=playlist_id)
parent.add_child(item, external_id=playlist_id)
def gotError(error):
self.warning("ERROR: %s" % error)
playlists_feed.addCallbacks(gotPlaylists, gotError)
return playlists_feed
def retrieveSubscriptionFeeds(self, parent):
playlists_feed = threads.deferToThread(self.yt_service.GetYouTubeSubscriptionFeed, username=self.login)
def gotPlaylists(playlist_video_feed):
if playlist_video_feed is None:
self.warning("Unable to retrieve subscriptions feed")
return
for entry in playlist_video_feed.entry:
type = entry.GetSubscriptionType()
title = entry.title.text
uri = entry.id.text
name = "[%s] %s" % (type,title)
item = LazyContainer(parent, name, uri, self.refresh, self.retrieveSubscriptionFeedItems, uri=uri)
item.parent = parent
parent.add_child(item, external_id=uri)
def gotError(error):
self.warning("ERROR: %s" % error)
playlists_feed.addCallbacks(gotPlaylists, gotError)
return playlists_feed | [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~core~soap_service.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007 - Frank Scholz <[email protected]>
from twisted.web import server, resource
from twisted.python import failure
from twisted.internet import defer
from coherence import log, SERVER_ID
from coherence.extern.et import ET, namespace_map_update
from coherence.upnp.core.utils import parse_xml
from coherence.upnp.core import soap_lite
import coherence.extern.louie as louie
class errorCode(Exception):
def __init__(self, status):
Exception.__init__(self)
self.status = status
class UPnPPublisher(resource.Resource, log.Loggable):
""" Based upon twisted.web.soap.SOAPPublisher and
extracted to remove the SOAPpy dependency
UPnP requires headers and OUT parameters to be returned
in a slightly
different way than the SOAPPublisher class does.
"""
logCategory = 'soap'
isLeaf = 1
encoding = "UTF-8"
envelope_attrib = None
def _sendResponse(self, request, response, status=200):
self.debug('_sendResponse', status, response)
if status == 200:
request.setResponseCode(200)
else:
request.setResponseCode(500)
if self.encoding is not None:
mimeType = 'text/xml; charset="%s"' % self.encoding
else:
mimeType = "text/xml"
request.setHeader("Content-type", mimeType)
request.setHeader("Content-length", str(len(response)))
request.setHeader("EXT", '')
request.setHeader("SERVER", SERVER_ID)
request.write(response)
request.finish()
def _methodNotFound(self, request, methodName):
response = soap_lite.build_soap_error(401)
self._sendResponse(request, response, status=401)
def _gotResult(self, result, request, methodName, ns):
self.debug('_gotResult', result, request, methodName, ns)
response = soap_lite.build_soap_call("{%s}%s" % (ns, methodName), result,
is_response=True,
encoding=None)
#print "SOAP-lite response", response
self._sendResponse(request, response)
def _gotError(self, failure, request, methodName, ns):
self.info('_gotError', failure, failure.value)
e = failure.value
status = 500
if isinstance(e, errorCode):
status = e.status
else:
failure.printTraceback()
response = soap_lite.build_soap_error(status)
self._sendResponse(request, response, status=status)
def lookupFunction(self, functionName):
function = getattr(self, "soap_%s" % functionName, None)
if not function:
function = getattr(self, "soap__generic", None)
if function:
return function, getattr(function, "useKeywords", False)
else:
return None, None
def render(self, request):
"""Handle a SOAP command."""
data = request.content.read()
headers = request.getAllHeaders()
self.info('soap_request:', headers)
# allow external check of data
louie.send('UPnPTest.Control.Client.CommandReceived', None, headers, data)
def print_c(e):
for c in e.getchildren():
print c, c.tag
print_c(c)
tree = parse_xml(data)
#root = tree.getroot()
#print_c(root)
body = tree.find('{http://schemas.xmlsoap.org/soap/envelope/}Body')
method = body.getchildren()[0]
methodName = method.tag
ns = None
if methodName.startswith('{') and methodName.rfind('}') > 1:
ns, methodName = methodName[1:].split('}')
args = []
kwargs = {}
for child in method.getchildren():
kwargs[child.tag] = self.decode_result(child)
args.append(kwargs[child.tag])
#p, header, body, attrs = SOAPpy.parseSOAPRPC(data, 1, 1, 1)
#methodName, args, kwargs, ns = p._name, p._aslist, p._asdict, p._ns
try:
headers['content-type'].index('text/xml')
except:
self._gotError(failure.Failure(errorCode(415)), request, methodName)
return server.NOT_DONE_YET
self.debug('headers: %r' % headers)
function, useKeywords = self.lookupFunction(methodName)
#print 'function', function, 'keywords', useKeywords, 'args', args, 'kwargs', kwargs
if not function:
self._methodNotFound(request, methodName)
return server.NOT_DONE_YET
else:
keywords = {'soap_methodName':methodName}
ua = headers.get('user-agent', '')
if ua.find('Xbox/') == 0:
keywords['X_UPnPClient'] = 'XBox'
elif ua.find('Philips-Software-WebClient/4.32') == 0:
keywords['X_UPnPClient'] = 'Philips-TV'
elif ua.find('SEC_HHP_BD') == 0:
keywords['X_UPnPClient'] = 'Samsung'
elif ua.find('SEC_HHP_') >= 0:
keywords['X_UPnPClient'] = 'SamsungDMC10'
#if(headers.has_key('user-agent') and
# headers['user-agent'].startswith("""Mozilla/4.0 (compatible; UPnP/1.0; Windows""")):
# keywords['X_UPnPClient'] = 'XBox'
if(headers.has_key('x-av-client-info') and
headers['x-av-client-info'].find('"PLAYSTATION3') > 0):
keywords['X_UPnPClient'] = 'PLAYSTATION3'
for k, v in kwargs.items():
keywords[str(k)] = v
self.info('call', methodName, keywords)
if hasattr(function, "useKeywords"):
d = defer.maybeDeferred(function, **keywords)
else:
d = defer.maybeDeferred(function, *args, **keywords)
d.addCallback(self._gotResult, request, methodName, ns)
d.addErrback(self._gotError, request, methodName, ns)
return server.NOT_DONE_YET
def decode_result(self, element):
type = element.get('{http://www.w3.org/1999/XMLSchema-instance}type')
if type is not None:
try:
prefix, local = type.split(":")
if prefix == 'xsd':
type = local
except ValueError:
pass
if type == "integer" or type == "int":
return int(element.text)
if type == "float" or type == "double":
return float(element.text)
if type == "boolean":
return element.text == "true"
return element.text or ""
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backend.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007,, Frank Scholz <[email protected]>
import time
from coherence.extern.simple_plugin import Plugin
from coherence import log
import coherence.extern.louie as louie
from coherence.upnp.core.utils import getPage
from coherence.extern.et import parse_xml
from coherence.upnp.core import DIDLLite
from twisted.internet import defer,reactor
class Backend(log.Loggable,Plugin):
""" the base class for all backends
if there are any UPnP service actions, that can't
be handled by the service classes itself, or need some
special adjustments for the backend, they need to be
defined here.
Like maybe upnp_Browse for the CDS Browse action.
"""
implements = [] # list the device classes here
# like [BinaryLight'] or ['MediaServer','MediaRenderer']
logCategory = 'backend'
def __init__(self,server,**kwargs):
""" the init method for a backend,
should probably most of the time be overwritten
when the init is done, send a signal to its device
the device will then setup and announce itself,
after that it calls the backends upnp_init method
"""
self.config = kwargs
self.server = server # the UPnP device that's hosting that backend
""" do whatever is necessary with the stuff we can
extract from the config dict,
connect maybe to an external data-source and
start up the backend
after that's done, tell Coherence about it
"""
log.Loggable.__init__(self)
Plugin.__init__(self)
""" this has to be done in the actual backend, maybe it has
to wait for an answer from an external data-source first
"""
#self.init_completed()
def init_completed(self, *args, **kwargs):
""" inform Coherence that this backend is ready for
announcement
this method just accepts any form of arguments
as we don't under which circumstances it is called
"""
louie.send('Coherence.UPnP.Backend.init_completed',
None, backend=self)
def upnp_init(self):
""" this method gets called after the device is fired,
here all initializations of service related state variables
should happen, as the services aren't available before that point
"""
pass
class BackendStore(Backend):
""" the base class for all MediaServer backend stores
"""
logCategory = 'backend_store'
def __init__(self,server,*args,**kwargs):
""" the init method for a MediaServer backend,
should probably most of the time be overwritten
when the init is done, send a signal to its device
the device will then setup and announce itself,
after that it calls the backends upnp_init method
"""
Backend.__init__(self, server, *args)
self.config = kwargs
self.server = server # the UPnP device that's hosting that backend
self.update_id = 0
""" do whatever is necessary with the stuff we can
extract from the config dict
"""
""" in case we want so serve something via
the MediaServer web backend
the BackendItem should pass an URI assembled
of urlbase + '/' + id to the DIDLLite.Resource
"""
self.urlbase = kwargs.get('urlbase','')
if not self.urlbase.endswith('/'):
self.urlbase += '/'
self.wmc_mapping = {'4':'4', '5':'5', '6':'6','7':'7','14':'14','F':'F',
'11':'11','16':'16','B':'B','C':'C','D':'D',
'13':'13', '17':'17',
'8':'8', '9':'9', '10':'10', '15':'15', 'A':'A', 'E':'E'}
self.wmc_mapping.update({'4':lambda: self._get_all_items(0),
'8':lambda: self._get_all_items(0),
'B':lambda: self._get_all_items(0),
})
""" and send out the signal when ready
"""
#louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
def release(self):
""" if anything needs to be cleaned up upon
shutdown of this backend, this is the place
for it
"""
pass
def _get_all_items(self,id):
""" a helper method to get all items as a response
to some XBox 360 UPnP Search action
probably never be used as the backend will overwrite
the wmc_mapping with more appropriate methods
"""
items = []
item = self.get_by_id(id)
if item is not None:
containers = [item]
while len(containers)>0:
container = containers.pop()
if container.mimetype not in ['root', 'directory']:
continue
for child in container.get_children(0,0):
if child.mimetype in ['root', 'directory']:
containers.append(child)
else:
items.append(child)
return items
def get_by_id(self,id):
""" called by the CDS or the MediaServer web
id is the id property of our DIDLLite item
if this MediaServer implements containers, that can
share their content, like 'all tracks', 'album' and
'album_of_artist' - they all have the same track item as content -
then the id may be passed by the CDS like this:
'id@container' or 'id@container@container@container...'
therefore a
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
may be appropriate as the first thing to do
when entering this method
should return
- None when no matching item for that id is found,
- a BackendItem,
- or a Deferred
"""
return None
class BackendItem(log.Loggable):
""" the base class for all MediaServer backend items
"""
logCategory = 'backend_item'
def __init__(self, *args, **kwargs):
""" most of the time we collect the necessary data for
an UPnP ContentDirectoryService Container or Object
and instantiate it here
self.item = DIDLLite.Container(id,parent_id,name,...)
or
self.item = DIDLLite.MusicTrack(id,parent_id,name,...)
To make that a valid UPnP CDS Object it needs one or
more DIDLLite.Resource(uri,protocolInfo)
self.item.res = []
res = DIDLLite.Resource(url, 'http-get:*:%s:*' % mimetype)
url : the urlbase of our backend + '/' + our id
res.size = size
self.item.res.append(res)
"""
self.name = u'my_name' # the basename of a file, the album title,
# the artists name,...
# is expected to be unicode
self.item = None
self.update_id = 0 # the update id of that item,
# when an UPnP ContentDirectoryService Container
# this should be incremented on every modification
self.location = None # the filepath of our media file, or alternatively
# a FilePath or a ReverseProxyResource object
self.cover = None # if we have some album art image, let's put
# the filepath or link into here
def get_children(self,start=0,end=0):
""" called by the CDS and the MediaServer web
should return
- a list of its childs[start:end]
- or a Deferred
if end == 0, the request is for all childs
after start - childs[start:]
"""
pass
def get_child_count(self):
""" called by the CDS
should return
- the number of its childs - len(childs)
- or a Deferred
"""
def get_item(self):
""" called by the CDS and the MediaServer web
should return
- an UPnP ContentDirectoryServer DIDLLite object
- or a Deferred
"""
return self.item
def get_name(self):
""" called by the MediaServer web
should return
- the name of the item,
it is always expected to be in unicode
"""
return self.name
def get_path(self):
""" called by the MediaServer web
should return
- the filepath where to find the media file
that this item does refer to
"""
return self.location
def get_cover(self):
""" called by the MediaServer web
should return
- the filepath where to find the album art file
only needed when we have created for that item
an albumArtURI property that does point back to us
"""
return self.cover
def __repr__(self):
return "%s[%s]" % (self.__class__.__name__, self.get_name())
class BackendRssMixin:
def update_data(self,rss_url,container=None,encoding="utf-8"):
""" creates a deferred chain to retrieve the rdf file,
parse and extract the metadata and reschedule itself
"""
def fail(f):
self.info("fail %r", f)
self.debug(f.getTraceback())
return f
dfr = getPage(rss_url)
dfr.addCallback(parse_xml, encoding=encoding)
dfr.addErrback(fail)
dfr.addCallback(self.parse_data,container)
dfr.addErrback(fail)
dfr.addBoth(self.queue_update,rss_url,container)
return dfr
def parse_data(self,xml_data,container):
""" extract media info and create BackendItems
"""
pass
def queue_update(self, error_or_failure,rss_url,container):
from twisted.internet import reactor
reactor.callLater(self.refresh, self.update_data,rss_url,container)
class Container(BackendItem):
def __init__(self, parent, title):
BackendItem.__init__(self)
self.parent = parent
if self.parent is not None:
self.parent_id = self.parent.get_id()
else:
self.parent_id = -1
self.store = None
self.storage_id = None
self.name = title
self.mimetype = 'directory'
self.children = []
self.children_ids = {}
self.children_by_external_id = {}
self.update_id = 0
self.item = None
self.sorted = False
def childs_sort(x,y):
return cmp(x.name,y.name)
self.sorting_method = childs_sort
def register_child(self, child, external_id = None):
storage_id = self.store.append_item(child)
child.url = self.store.urlbase + str(storage_id)
child.parent = self
if external_id is not None:
child.external_id = external_id
self.children_by_external_id[external_id] = child
return storage_id
def add_child(self, child, external_id = None, update=True):
storage_id = self.register_child(child, external_id)
if self.children is None:
self.children = []
self.children.append(child)
self.sorted = False
if update == True:
self.update_id += 1
return storage_id
def remove_child(self, child, external_id = None, update=True):
self.children.remove(child)
self.store.remove_item(child)
if update == True:
self.update_id += 1
if external_id is not None:
child.external_id = None
del self.children_by_external_id[external_id]
def get_children(self, start=0, end=0):
if self.sorted == False:
self.children.sort(cmp=self.sorting_method)
self.sorted = True
if end != 0:
return self.children[start:end]
return self.children[start:]
def get_child_count(self):
if self.children is None:
return 0
return len(self.children)
def get_path(self):
return self.store.urlbase + str(self.storage_id)
def get_item(self):
if self.item is None:
self.item = DIDLLite.Container(self.storage_id, self.parent_id, self.name)
self.item.childCount = len(self.children)
return self.item
def get_name(self):
return self.name
def get_id(self):
return self.storage_id
def get_update_id(self):
return self.update_id
class LazyContainer(Container, log.Loggable):
logCategory = 'lazyContainer'
def __init__(self, parent, title, external_id=None, refresh=0, childrenRetriever=None, **kwargs):
Container.__init__(self, parent, title)
self.childrenRetrievingNeeded = True
self.childrenRetrievingDeferred = None
self.childrenRetriever = childrenRetriever
self.children_retrieval_campaign_in_progress = False
self.childrenRetriever_params = kwargs
self.childrenRetriever_params['parent']=self
self.has_pages = (self.childrenRetriever_params.has_key('per_page'))
self.external_id = None
self.external_id = external_id
self.retrieved_children = {}
self.last_updated = 0
self.refresh = refresh
def replace_by(self, item):
if self.external_id is not None and item.external_id is not None:
return (self.external_id == item.external_id)
return True
def add_child(self, child, external_id = None, update=True):
if self.children_retrieval_campaign_in_progress is True:
self.retrieved_children[external_id] = child
else:
Container.add_child(self, child, external_id=external_id, update=update)
def update_children(self, new_children, old_children):
children_to_be_removed = {}
children_to_be_replaced = {}
children_to_be_added = {}
# Phase 1
# let's classify the item between items to be removed,
# to be updated or to be added
self.debug("Refresh pass 1:%d %d" % (len(new_children), len(old_children)))
for id,item in old_children.items():
children_to_be_removed[id] = item
for id,item in new_children.items():
if old_children.has_key(id):
#print(id, "already there")
children_to_be_replaced[id] = old_children[id]
del children_to_be_removed[id]
else:
children_to_be_added[id] = new_children[id]
# Phase 2
# Now, we remove, update or add the relevant items
# to the list of items
self.debug("Refresh pass 2: %d %d %d" % (len(children_to_be_removed), len(children_to_be_replaced), len(children_to_be_added)))
# Remove relevant items from Container children
for id,item in children_to_be_removed.items():
self.remove_child(item, external_id=id, update=False)
# Update relevant items from Container children
for id,item in children_to_be_replaced.items():
old_item = item
new_item = new_children[id]
replaced = False
if self.replace_by:
#print "Replacement method available: Try"
replaced = old_item.replace_by(new_item)
if replaced is False:
#print "No replacement possible: we remove and add the item again"
self.remove_child(old_item, external_id=id, update=False)
self.add_child(new_item, external_id=id, update=False)
# Add relevant items to COntainer children
for id,item in children_to_be_added.items():
self.add_child(item, external_id=id, update=False)
self.update_id += 1
def start_children_retrieval_campaign(self):
#print "start_update_campaign"
self.last_updated = time.time()
self.retrieved_children = {}
self.children_retrieval_campaign_in_progress = True
def end_children_retrieval_campaign(self, success=True):
#print "end_update_campaign"
self.children_retrieval_campaign_in_progress = False
if success is True:
self.update_children(self.retrieved_children, self.children_by_external_id)
self.update_id += 1
self.last_updated = time.time()
self.retrieved_children = {}
def retrieve_children(self, start=0, page=0):
def items_retrieved(result, page, start_offset):
if self.childrenRetrievingNeeded is True:
new_offset = len(self.retrieved_children)
return self.retrieve_children(new_offset, page+1) # we try the next page
return self.retrieved_children
self.childrenRetrievingNeeded = False
if self.has_pages is True:
self.childrenRetriever_params['offset'] = start
self.childrenRetriever_params['page'] = page
d = self.childrenRetriever(**self.childrenRetriever_params)
d.addCallback(items_retrieved, page, start)
return d
def retrieve_all_children(self, start=0, request_count=0):
def all_items_retrieved (result):
#print "All children retrieved!"
self.end_children_retrieval_campaign(True)
return Container.get_children(self, start, request_count)
def error_while_retrieving_items (error):
#print "Error while retrieving all children!"
self.end_children_retrieval_campaign(False)
return Container.get_children(self, start, request_count)
# if first retrieval and refresh required
# we start a looping call to periodically update the children
#if ((self.last_updated == 0) and (self.refresh > 0)):
# task.LoopingCall(self.retrieve_children,0,0).start(self.refresh, now=False)
self.start_children_retrieval_campaign()
if self.childrenRetriever is not None:
d = self.retrieve_children(start)
if start == 0:
d.addCallbacks(all_items_retrieved, error_while_retrieving_items)
return d
else:
self.end_children_retrieval_campaign()
return self.children
def get_children(self,start=0,request_count=0):
# Check if an update is needed since last update
current_time = time.time()
delay_since_last_updated = current_time - self.last_updated
period = self.refresh
if (period > 0) and (delay_since_last_updated > period):
self.info("Last update is older than %d s -> update data" % period)
self.childrenRetrievingNeeded = True
if self.childrenRetrievingNeeded is True:
#print "children Retrieving IS Needed (offset is %d)" % start
self.retrieve_all_children()
Container.get_children(self, start, request_count)
ROOT_CONTAINER_ID = 0
SEED_ITEM_ID = 1000
class AbstractBackendStore (BackendStore):
def __init__(self, server, **kwargs):
BackendStore.__init__(self, server, **kwargs)
self.next_id = SEED_ITEM_ID
self.store = {}
def len(self):
return len(self.store)
def set_root_item(self, item):
return self.append_item(item, storage_id = ROOT_CONTAINER_ID)
def get_root_id(self):
return ROOT_CONTAINER_ID
def get_root_item(self):
return self.get_by_id(ROOT_CONTAINER_ID)
def append_item(self, item, storage_id=None):
if storage_id is None:
storage_id = self.getnextID()
self.store[storage_id] = item
item.storage_id = storage_id
item.store = self
return storage_id
def remove_item(self, item):
del self.store[item.storage_id]
item.storage_id = -1
item.store = None
def get_by_id(self,id):
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0].split('.')[0]
try:
return self.store[int(id)]
except (ValueError,KeyError):
pass
return None
def getnextID(self):
ret = self.next_id
self.next_id += 1
return ret
def __repr__(self):
return self.__class__.__name__
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~transcoder.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
""" transcoder classes to be used in combination with
a Coherence MediaServer
using GStreamer pipelines for the actually work
and feeding the output into a http response
"""
import pygst
pygst.require('0.10')
import gst
import gobject
gobject.threads_init()
import os.path
import urllib
from twisted.web import resource, server
from twisted.internet import protocol
from coherence import log
import struct
def get_transcoder_name(transcoder):
return transcoder.name
class InternalTranscoder(object):
""" just a class to inherit from and
which we can look for upon creating our
list of available transcoders
"""
class FakeTransformer(gst.Element, log.Loggable):
logCategory = 'faker_datasink'
_sinkpadtemplate = gst.PadTemplate ("sinkpadtemplate",
gst.PAD_SINK,
gst.PAD_ALWAYS,
gst.caps_new_any())
_srcpadtemplate = gst.PadTemplate ("srcpadtemplate",
gst.PAD_SRC,
gst.PAD_ALWAYS,
gst.caps_new_any())
def __init__(self, destination=None, request=None):
gst.Element.__init__(self)
self.sinkpad = gst.Pad(self._sinkpadtemplate, "sink")
self.srcpad = gst.Pad(self._srcpadtemplate, "src")
self.add_pad(self.sinkpad)
self.add_pad(self.srcpad)
self.sinkpad.set_chain_function(self.chainfunc)
self.buffer = ''
self.buffer_size = 0
self.proxy = False
self.got_new_segment = False
self.closed = False
def get_fake_header(self):
return struct.pack(">L4s", 32, 'ftyp') + \
"mp42\x00\x00\x00\x00mp42mp41isomiso2"
def chainfunc(self, pad, buffer):
if self.proxy:
# we are in proxy mode already
self.srcpad.push(buffer)
return gst.FLOW_OK
self.buffer = self.buffer + buffer.data
if not self.buffer_size:
try:
self.buffer_size, a_type = struct.unpack(">L4s", self.buffer[:8])
except:
return gst.FLOW_OK
if len(self.buffer) < self.buffer_size:
# we need to buffer more
return gst.FLOW_OK
buffer = self.buffer[self.buffer_size:]
fake_header = self.get_fake_header()
n_buf = gst.Buffer(fake_header + buffer)
self.proxy = True
self.srcpad.push(n_buf)
return gst.FLOW_OK
gobject.type_register(FakeTransformer)
class DataSink(gst.Element, log.Loggable):
logCategory = 'transcoder_datasink'
_sinkpadtemplate = gst.PadTemplate ("sinkpadtemplate",
gst.PAD_SINK,
gst.PAD_ALWAYS,
gst.caps_new_any())
def __init__(self, destination=None, request=None):
gst.Element.__init__(self)
self.sinkpad = gst.Pad(self._sinkpadtemplate, "sink")
self.add_pad(self.sinkpad)
self.sinkpad.set_chain_function(self.chainfunc)
self.sinkpad.set_event_function(self.eventfunc)
self.destination = destination
self.request = request
if self.destination is not None:
self.destination = open(self.destination, 'wb')
self.buffer = ''
self.data_size = 0
self.got_new_segment = False
self.closed = False
def chainfunc(self, pad, buffer):
if self.closed:
return gst.FLOW_OK
if self.destination is not None:
self.destination.write(buffer.data)
elif self.request is not None:
self.buffer += buffer.data
if len(self.buffer) > 200000:
self.request.write(self.buffer)
self.buffer = ''
else:
self.buffer += buffer.data
self.data_size += buffer.size
return gst.FLOW_OK
def eventfunc(self, pad, event):
if event.type == gst.EVENT_NEWSEGMENT:
if not self.got_new_segment:
self.got_new_segment = True
else:
self.closed = True
elif event.type == gst.EVENT_EOS:
if self.destination is not None:
self.destination.close()
elif self.request is not None:
if len(self.buffer) > 0:
self.request.write(self.buffer)
self.request.finish()
return True
gobject.type_register(DataSink)
class GStreamerPipeline(resource.Resource, log.Loggable):
logCategory = 'gstreamer'
addSlash = True
def __init__(self, pipeline, content_type):
self.pipeline_description = pipeline
self.contentType = content_type
self.requests = []
# if stream has a streamheader (something that has to be prepended
# before any data), then it will be a tuple of GstBuffers
self.streamheader = None
self.parse_pipeline()
resource.Resource.__init__(self)
def parse_pipeline(self):
self.pipeline = gst.parse_launch(self.pipeline_description)
self.appsink = gst.element_factory_make("appsink", "sink")
self.appsink.set_property('emit-signals', True)
self.pipeline.add(self.appsink)
enc = self.pipeline.get_by_name("enc")
enc.link(self.appsink)
self.appsink.connect("new-preroll", self.new_preroll)
self.appsink.connect("new-buffer", self.new_buffer)
self.appsink.connect("eos", self.eos)
def start(self, request=None):
self.info("GStreamerPipeline start %r %r", request,
self.pipeline_description)
self.requests.append(request)
self.pipeline.set_state(gst.STATE_PLAYING)
d = request.notifyFinish()
d.addBoth(self.requestFinished, request)
def new_preroll(self, appsink):
self.debug("new preroll")
buffer = appsink.emit('pull-preroll')
if not self.streamheader:
# check caps for streamheader buffer
caps = buffer.get_caps()
s = caps[0]
if s.has_key("streamheader"):
self.streamheader = s["streamheader"]
self.debug("setting streamheader")
for r in self.requests:
self.debug("writing streamheader")
for h in self.streamheader:
r.write(h.data)
for r in self.requests:
self.debug("writing preroll")
r.write(buffer.data)
def new_buffer(self, appsink):
buffer = appsink.emit('pull-buffer')
if not self.streamheader:
# check caps for streamheader buffers
caps = buffer.get_caps()
s = caps[0]
if s.has_key("streamheader"):
self.streamheader = s["streamheader"]
self.debug("setting streamheader")
for r in self.requests:
self.debug("writing streamheader")
for h in self.streamheader:
r.write(h.data)
for r in self.requests:
r.write(buffer.data)
def eos(self, appsink):
self.info("eos")
for r in self.requests:
r.finish()
self.cleanup()
def getChild(self, name, request):
self.info('getChild %s, %s' % (name, request))
return self
def render_GET(self, request):
self.info('render GET %r' % (request))
request.setResponseCode(200)
if hasattr(self, 'contentType'):
request.setHeader('Content-Type', self.contentType)
request.write('')
headers = request.getAllHeaders()
if('connection' in headers and
headers['connection'] == 'close'):
pass
if self.requests:
if self.streamheader:
self.debug("writing streamheader")
for h in self.streamheader:
request.write(h.data)
self.requests.append(request)
else:
self.parse_pipeline()
self.start(request)
return server.NOT_DONE_YET
def render_HEAD(self, request):
self.info('render HEAD %r' % (request))
request.setResponseCode(200)
request.setHeader('Content-Type', self.contentType)
request.write('')
def requestFinished(self, result, request):
self.info("requestFinished %r" % result)
""" we need to find a way to destroy the pipeline here
"""
#from twisted.internet import reactor
#reactor.callLater(0, self.pipeline.set_state, gst.STATE_NULL)
self.requests.remove(request)
if not self.requests:
self.cleanup()
def on_message(self, bus, message):
t = message.type
print "on_message", t
if t == gst.MESSAGE_ERROR:
#err, debug = message.parse_error()
#print "Error: %s" % err, debug
self.cleanup()
elif t == gst.MESSAGE_EOS:
self.cleanup()
def cleanup(self):
self.info("pipeline cleanup")
self.pipeline.set_state(gst.STATE_NULL)
self.requests = []
self.streamheader = None
class BaseTranscoder(resource.Resource, log.Loggable):
logCategory = 'transcoder'
addSlash = True
def __init__(self, uri, destination=None):
self.info('uri %s %r' % (uri, type(uri)))
if uri[:7] not in ['file://', 'http://']:
uri = 'file://' + urllib.quote(uri) #FIXME
self.uri = uri
self.destination = destination
resource.Resource.__init__(self)
def getChild(self, name, request):
self.info('getChild %s, %s' % (name, request))
return self
def render_GET(self, request):
self.info('render GET %r' % (request))
request.setResponseCode(200)
if hasattr(self, 'contentType'):
request.setHeader('Content-Type', self.contentType)
request.write('')
headers = request.getAllHeaders()
if('connection' in headers and
headers['connection'] == 'close'):
pass
self.start(request)
return server.NOT_DONE_YET
def render_HEAD(self, request):
self.info('render HEAD %r' % (request))
request.setResponseCode(200)
request.setHeader('Content-Type', self.contentType)
request.write('')
def requestFinished(self, result):
self.info("requestFinished %r" % result)
""" we need to find a way to destroy the pipeline here
"""
#from twisted.internet import reactor
#reactor.callLater(0, self.pipeline.set_state, gst.STATE_NULL)
gobject.idle_add(self.cleanup)
def on_message(self, bus, message):
t = message.type
print "on_message", t
if t == gst.MESSAGE_ERROR:
#err, debug = message.parse_error()
#print "Error: %s" % err, debug
self.cleanup()
elif t == gst.MESSAGE_EOS:
self.cleanup()
def cleanup(self):
self.pipeline.set_state(gst.STATE_NULL)
class PCMTranscoder(BaseTranscoder, InternalTranscoder):
contentType = 'audio/L16;rate=44100;channels=2'
name = 'lpcm'
def start(self, request=None):
self.info("PCMTranscoder start %r %r", request, self.uri)
self.pipeline = gst.parse_launch(
"%s ! decodebin ! audioconvert name=conv" % self.uri)
conv = self.pipeline.get_by_name('conv')
caps = gst.Caps("audio/x-raw-int,rate=44100,endianness=4321,channels=2,width=16,depth=16,signed=true")
#FIXME: UGLY. 'filter' is a python builtin!
filter = gst.element_factory_make("capsfilter", "filter")
filter.set_property("caps", caps)
self.pipeline.add(filter)
conv.link(filter)
sink = DataSink(destination=self.destination, request=request)
self.pipeline.add(sink)
filter.link(sink)
self.pipeline.set_state(gst.STATE_PLAYING)
d = request.notifyFinish()
d.addBoth(self.requestFinished)
class WAVTranscoder(BaseTranscoder, InternalTranscoder):
contentType = 'audio/x-wav'
name = 'wav'
def start(self, request=None):
self.info("start %r", request)
self.pipeline = gst.parse_launch(
"%s ! decodebin ! audioconvert ! wavenc name=enc" % self.uri)
enc = self.pipeline.get_by_name('enc')
sink = DataSink(destination=self.destination, request=request)
self.pipeline.add(sink)
enc.link(sink)
#bus = self.pipeline.get_bus()
#bus.connect('message', self.on_message)
self.pipeline.set_state(gst.STATE_PLAYING)
d = request.notifyFinish()
d.addBoth(self.requestFinished)
class MP3Transcoder(BaseTranscoder, InternalTranscoder):
contentType = 'audio/mpeg'
name = 'mp3'
def start(self, request=None):
self.info("start %r", request)
self.pipeline = gst.parse_launch(
"%s ! decodebin ! audioconvert ! lame name=enc" % self.uri)
enc = self.pipeline.get_by_name('enc')
sink = DataSink(destination=self.destination, request=request)
self.pipeline.add(sink)
enc.link(sink)
self.pipeline.set_state(gst.STATE_PLAYING)
d = request.notifyFinish()
d.addBoth(self.requestFinished)
class MP4Transcoder(BaseTranscoder, InternalTranscoder):
""" Only works if H264 inside Quicktime/MP4 container is input
Source has to be a valid uri
"""
contentType = 'video/mp4'
name = 'mp4'
def start(self, request=None):
self.info("start %r", request)
self.pipeline = gst.parse_launch(
"%s ! qtdemux name=d ! queue ! h264parse ! mp4mux name=mux d. ! queue ! mux." % self.uri)
mux = self.pipeline.get_by_name('mux')
sink = DataSink(destination=self.destination, request=request)
self.pipeline.add(sink)
mux.link(sink)
self.pipeline.set_state(gst.STATE_PLAYING)
d = request.notifyFinish()
d.addBoth(self.requestFinished)
class MP2TSTranscoder(BaseTranscoder, InternalTranscoder):
contentType = 'video/mpeg'
name = 'mpegts'
def start(self, request=None):
self.info("start %r", request)
### FIXME mpeg2enc
self.pipeline = gst.parse_launch(
"mpegtsmux name=mux %s ! decodebin2 name=d ! queue ! ffmpegcolorspace ! mpeg2enc ! queue ! mux. d. ! queue ! audioconvert ! twolame ! queue ! mux." % self.uri)
enc = self.pipeline.get_by_name('mux')
sink = DataSink(destination=self.destination, request=request)
self.pipeline.add(sink)
enc.link(sink)
self.pipeline.set_state(gst.STATE_PLAYING)
d = request.notifyFinish()
d.addBoth(self.requestFinished)
class ThumbTranscoder(BaseTranscoder, InternalTranscoder):
""" should create a valid thumbnail according to the DLNA spec
neither width nor height must exceed 160px
"""
contentType = 'image/jpeg'
name = 'thumb'
def start(self, request=None):
self.info("start %r", request)
""" what we actually want here is a pipeline that calls
us when it knows about the size of the original image,
and allows us now to adjust the caps-filter with the
calculated values for width and height
new_width = 160
new_height = 160
if original_width > 160:
new_heigth = int(float(original_height) * (160.0/float(original_width)))
if new_height > 160:
new_width = int(float(new_width) * (160.0/float(new_height)))
elif original_height > 160:
new_width = int(float(original_width) * (160.0/float(original_height)))
"""
try:
type = request.args['type'][0]
except:
type = 'jpeg'
if type == 'png':
self.pipeline = gst.parse_launch(
"%s ! decodebin2 ! videoscale ! video/x-raw-yuv,width=160,height=160 ! pngenc name=enc" % self.uri)
self.contentType = 'image/png'
else:
self.pipeline = gst.parse_launch(
"%s ! decodebin2 ! videoscale ! video/x-raw-yuv,width=160,height=160 ! jpegenc name=enc" % self.uri)
self.contentType = 'image/jpeg'
enc = self.pipeline.get_by_name('enc')
sink = DataSink(destination=self.destination, request=request)
self.pipeline.add(sink)
enc.link(sink)
self.pipeline.set_state(gst.STATE_PLAYING)
d = request.notifyFinish()
d.addBoth(self.requestFinished)
class GStreamerTranscoder(BaseTranscoder):
""" a generic Transcode based on GStreamer
the pipeline which will be parsed upon
calling the start method, as to be set as
the attribute pipeline_description to the
instantiated class
same for the attribute contentType
"""
def start(self, request=None):
self.info("start %r", request)
self.pipeline = gst.parse_launch(self.pipeline_description % self.uri)
enc = self.pipeline.get_by_name('mux')
sink = DataSink(destination=self.destination, request=request)
self.pipeline.add(sink)
enc.link(sink)
self.pipeline.set_state(gst.STATE_PLAYING)
d = request.notifyFinish()
d.addBoth(self.requestFinished)
class ExternalProcessProtocol(protocol.ProcessProtocol):
def __init__(self, caller):
self.caller = caller
def connectionMade(self):
print "pp connection made"
def outReceived(self, data):
#print "outReceived with %d bytes!" % len(data)
self.caller.write_data(data)
def errReceived(self, data):
#print "errReceived! with %d bytes!" % len(data)
print "pp (err):", data.strip()
def inConnectionLost(self):
#print "inConnectionLost! stdin is closed! (we probably did it)"
pass
def outConnectionLost(self):
#print "outConnectionLost! The child closed their stdout!"
pass
def errConnectionLost(self):
#print "errConnectionLost! The child closed their stderr."
pass
def processEnded(self, status_object):
print "processEnded, status %d" % status_object.value.exitCode
print "processEnded quitting"
self.caller.ended = True
self.caller.write_data('')
class ExternalProcessProducer(object):
logCategory = 'externalprocess'
def __init__(self, pipeline, request):
self.pipeline = pipeline
self.request = request
self.process = None
self.written = 0
self.data = ''
self.ended = False
request.registerProducer(self, 0)
def write_data(self, data):
if data:
#print "write %d bytes of data" % len(data)
self.written += len(data)
# this .write will spin the reactor, calling .doWrite and then
# .resumeProducing again, so be prepared for a re-entrant call
self.request.write(data)
if self.request and self.ended:
print "closing"
self.request.unregisterProducer()
self.request.finish()
self.request = None
def resumeProducing(self):
#print "resumeProducing", self.request
if not self.request:
return
if self.process is None:
argv = self.pipeline.split()
executable = argv[0]
argv[0] = os.path.basename(argv[0])
from twisted.internet import reactor
self.process = reactor.spawnProcess(ExternalProcessProtocol(self),
executable, argv, {})
def pauseProducing(self):
pass
def stopProducing(self):
print "stopProducing", self.request
self.request.unregisterProducer()
self.process.loseConnection()
self.request.finish()
self.request = None
class ExternalProcessPipeline(resource.Resource, log.Loggable):
logCategory = 'externalprocess'
addSlash = False
def __init__(self, uri):
self.uri = uri
def getChildWithDefault(self, path, request):
return self
def render(self, request):
print "ExternalProcessPipeline render"
try:
if self.contentType:
request.setHeader('Content-Type', self.contentType)
except AttributeError:
pass
ExternalProcessProducer(self.pipeline_description % self.uri, request)
return server.NOT_DONE_YET
def transcoder_class_wrapper(klass, content_type, pipeline):
def create_object(uri):
transcoder = klass(uri)
transcoder.contentType = content_type
transcoder.pipeline_description = pipeline
return transcoder
return create_object
class TranscoderManager(log.Loggable):
""" singleton class which holds information
about all available transcoders
they are put into a transcoders dict with
their id as the key
we collect all internal transcoders by searching
for all subclasses of InternalTranscoder, the class
will be the value
transcoders defined in the config are parsed and
stored as a dict in the transcoders dict
in the config a transcoder description has to look like this:
*** preliminary, will be extended and might even change without further notice ***
<transcoder>
<pipeline>%s ...</pipeline> <!-- we need a %s here to insert the source uri
(or can we have all the times pipelines we can prepend
with a '%s !')
and an element named mux where we can attach
our sink -->
<type>gstreamer</type> <!-- could be gstreamer or process -->
<name>mpegts</name>
<target>video/mpeg</target>
<fourth_field> <!-- value for the 4th field of the protocolInfo phalanx,
default is '*' -->
</transcoder>
"""
logCategory = 'transcoder_manager'
_instance_ = None # Singleton
def __new__(cls, *args, **kwargs):
""" creates the singleton """
if cls._instance_ is None:
obj = super(TranscoderManager, cls).__new__(cls, *args, **kwargs)
cls._instance_ = obj
return cls._instance_
def __init__(self, coherence=None):
""" initializes the class
it should be called at least once
with the main coherence class passed as an argument,
so we have access to the config
"""
self.transcoders = {}
for transcoder in InternalTranscoder.__subclasses__():
self.transcoders[get_transcoder_name(transcoder)] = transcoder
if coherence is not None:
self.coherence = coherence
try:
transcoders_from_config = self.coherence.config['transcoder']
if isinstance(transcoders_from_config, dict):
transcoders_from_config = [transcoders_from_config]
except KeyError:
transcoders_from_config = []
for transcoder in transcoders_from_config:
# FIXME: is anyone checking if all keys are given ?
pipeline = transcoder['pipeline']
if not '%s' in pipeline:
self.warning("Can't create transcoder %r:"
" missing placehoder '%%s' in 'pipeline'",
transcoder)
continue
try:
transcoder_name = transcoder['name'].decode('ascii')
except UnicodeEncodeError:
self.warning("Can't create transcoder %r:"
" the 'name' contains non-ascii letters",
transcoder)
continue
transcoder_type = transcoder['type'].lower()
if transcoder_type == 'gstreamer':
wrapped = transcoder_class_wrapper(GStreamerTranscoder,
transcoder['target'], transcoder['pipeline'])
elif transcoder_type == 'process':
wrapped = transcoder_class_wrapper(ExternalProcessPipeline,
transcoder['target'], transcoder['pipeline'])
else:
self.warning("unknown transcoder type %r", transcoder_type)
continue
self.transcoders[transcoder_name] = wrapped
#FIXME reduce that to info later
self.warning("available transcoders %r" % self.transcoders)
def select(self, name, uri, backend=None):
# FIXME:why do we specify the name when trying to get it?
if backend is not None:
""" try to find a transcoder provided by the backend
and return that here,
if there isn't one continue with the ones
provided by the config or the internal ones
"""
pass
transcoder = self.transcoders[name](uri)
return transcoder
if __name__ == '__main__':
t = Transcoder(None)
| [
"sinkpadtemplate",
"srcpadtemplate"
] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~devices~wan_device_client.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2010 Frank Scholz <[email protected]>
from coherence.upnp.devices.wan_connection_device_client import WANConnectionDeviceClient
from coherence.upnp.services.clients.wan_common_interface_config_client import WANCommonInterfaceConfigClient
from coherence import log
import coherence.extern.louie as louie
class WANDeviceClient(log.Loggable):
logCategory = 'wan_device_client'
def __init__(self, device):
self.device = device
self.device_type = self.device.get_friendly_device_type()
self.version = int(self.device.get_device_type_version())
self.icons = device.icons
self.wan_connection_device = None
self.wan_common_interface_connection = None
self.embedded_device_detection_completed = False
self.service_detection_completed = False
louie.connect(self.embedded_device_notified, signal='Coherence.UPnP.EmbeddedDeviceClient.detection_completed', sender=self.device)
try:
wan_connection_device = self.device.get_embedded_device_by_type('WANConnectionDevice')[0]
self.wan_connection_device = WANConnectionDeviceClient(wan_connection_device)
except:
self.warning("Embedded WANConnectionDevice device not available, device not implemented properly according to the UPnP specification")
raise
louie.connect(self.service_notified, signal='Coherence.UPnP.DeviceClient.Service.notified', sender=self.device)
for service in self.device.get_services():
if service.get_type() in ["urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1"]:
self.wan_common_interface_connection = WANCommonInterfaceConfigClient(service)
self.info("WANDevice %s" % (self.device.get_friendly_name()))
def remove(self):
self.info("removal of WANDeviceClient started")
if self.wan_common_interface_connection != None:
self.wan_common_interface_connection.remove()
if self.wan_connection_device != None:
self.wan_connection_device.remove()
def embedded_device_notified(self, device):
self.info("EmbeddedDevice %r sent notification" % device);
if self.embedded_device_detection_completed == True:
return
self.embedded_device_detection_completed = True
if self.embedded_device_detection_completed == True and self.service_detection_completed == True:
louie.send('Coherence.UPnP.EmbeddedDeviceClient.detection_completed', None,
self)
def service_notified(self, service):
self.info("Service %r sent notification" % service);
if self.service_detection_completed == True:
return
if self.wan_common_interface_connection != None:
if not hasattr(self.wan_common_interface_connection.service, 'last_time_updated'):
return
if self.wan_common_interface_connection.service.last_time_updated == None:
return
self.service_detection_completed = True
if self.embedded_device_detection_completed == True and self.service_detection_completed == True:
louie.send('Coherence.UPnP.EmbeddedDeviceClient.detection_completed', None,
self)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~yamj_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# a backend to expose a YMAJ library via UPnP
# see http://code.google.com/p/moviejukebox/ for more info on YAMJ (Yet Another Movie Jukebox):
# Copyright 2007, Frank Scholz <[email protected]>
# Copyright 2009, Jean-Michel Sizun <jm.sizun AT free.fr>
#
# TODO: add comments
import urllib
from coherence.upnp.core import DIDLLite
from coherence.backend import BackendStore, BackendItem, Container, \
LazyContainer, AbstractBackendStore
from coherence import log
from coherence.upnp.core.utils import getPage
from coherence.extern.et import parse_xml
import mimetypes
mimetypes.init()
mimetypes.add_type('audio/x-m4a', '.m4a')
mimetypes.add_type('video/mp4', '.mp4')
mimetypes.add_type('video/mpegts', '.ts')
mimetypes.add_type('video/divx', '.divx')
mimetypes.add_type('video/divx', '.avi')
mimetypes.add_type('video/x-matroska', '.mkv')
class MovieItem(BackendItem):
def __init__(self, movie, store, title = None, url = None):
self.movie_id = 'UNK'
if movie.find('./id') is not None:
self.movie_id = movie.find('./id').text
self.title = movie.find('./title').text
self.baseFilename = movie.find('./baseFilename').text
self.plot = movie.find('./plot').text
self.outline = movie.find('./outline').text
self.posterFilename = movie.find('./posterFile').text
self.thumbnailFilename = movie.find('./thumbnail').text
self.rating = movie.find('./rating').text
self.director = movie.find('./director').text
self.genres = movie.findall('./genres/genre')
self.actors = movie.findall('./cast/actor')
self.year = movie.find('year').text
self.audioChannels = movie.find('audioChannels').text
self.resolution = movie.find('resolution').text
self.language = movie.find('language').text
self.season = movie.find('season').text
if title is not None:
self.upnp_title = title
else:
self.upnp_title = self.title
if url is not None:
self.movie_url = url
else:
self.movie_url = movie.find('./files/file/fileURL').text
self.posterURL = "%s/%s" % (store.jukebox_url, self.posterFilename)
self.thumbnailURL = "%s/%s" % (store.jukebox_url, self.thumbnailFilename)
#print self.movie_id, self.title, self.url, self.posterURL
self.str_genres = []
for genre in self.genres:
self.str_genres.append(genre.text)
self.str_actors = []
for actor in self.actors:
self.str_actors.append(actor.text)
url_mimetype,_ = mimetypes.guess_type(self.movie_url,strict=False)
if url_mimetype == None:
url_mimetype = "video"
self.name = self.title
self.duration = None
self.size = None
self.mimetype = url_mimetype
self.item = None
def get_item(self):
if self.item == None:
upnp_id = self.get_id()
upnp_parent_id = self.parent.get_id()
self.item = DIDLLite.Movie(upnp_id, upnp_parent_id, self.upnp_title)
self.item.album = None
self.item.albumArtURI = self.posterURL
self.item.artist = None
self.item.creator = self.director
self.item.date = self.year
self.item.description = self.plot
self.item.director = self.director
self.item.longDescription = self.outline
self.item.originalTrackNumber = None
self.item.restricted = None
self.item.title = self.upnp_title
self.item.writeStatus = "PROTECTED"
self.item.icon = self.thumbnailURL
self.item.genre = None
self.item.genres = self.str_genres
self.item.language = self.language
self.item.actors = self.str_actors
res = DIDLLite.Resource(self.movie_url, 'http-get:*:%s:*' % self.mimetype)
res.duration = self.duration
res.size = self.size
res.nrAudioChannels = self.audioChannels
res.resolution = self.resolution
self.item.res.append(res)
return self.item
def get_path(self):
return self.movie_url
def get_id(self):
return self.storage_id
class YamjStore(AbstractBackendStore):
logCategory = 'yamj_store'
implements = ['MediaServer']
description = ('YAMJ', 'exposes the movie/TV series data files and metadata from a given YAMJ (Yet Another Movie Jukebox) library.', None)
options = [{'option':'name', 'text':'Server Name:', 'type':'string','default':'my media','help': 'the name under this MediaServer shall show up with on other UPnP clients'},
{'option':'version','text':'UPnP Version:','type':'int','default':2,'enum': (2,1),'help': 'the highest UPnP version this MediaServer shall support','level':'advance'},
{'option':'uuid','text':'UUID Identifier:','type':'string','help':'the unique (UPnP) identifier for this MediaServer, usually automatically set','level':'advance'},
{'option':'refresh','text':'Refresh period','type':'string'},
{'option':'yamj_url','text':'Library URL:','type':'string', 'help':'URL to the library root directory.'}
]
def __init__(self, server, **kwargs):
AbstractBackendStore.__init__(self, server, **kwargs)
self.name = kwargs.get('name','YAMJ')
self.yamj_url = kwargs.get('yamj_url',"http://localhost/yamj");
self.jukebox_url = self.yamj_url + "/Jukebox/"
self.refresh = int(kwargs.get('refresh',60))*60
self.nbMoviesPerFile = None
rootItem = Container(None, self.name)
self.set_root_item(rootItem)
d = self.retrieveCategories(rootItem)
def upnp_init(self):
self.current_connection_id = None
if self.server:
self.server.presentationURL = self.yamj_url
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
['internal:%s:video/mp4:*' % self.server.coherence.hostname,
'http-get:*:video/mp4:*',
'internal:%s:video/x-msvideo:*' % self.server.coherence.hostname,
'http-get:*:video/x-msvideo:*',
'internal:%s:video/mpeg:*' % self.server.coherence.hostname,
'http-get:*:video/mpeg:*',
'internal:%s:video/avi:*' % self.server.coherence.hostname,
'http-get:*:video/avi:*',
'internal:%s:video/divx:*' % self.server.coherence.hostname,
'http-get:*:video/divx:*',
'internal:%s:video/quicktime:*' % self.server.coherence.hostname,
'http-get:*:video/quicktime:*'],
default=True)
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
#self.server.content_directory_server.set_variable(0, 'SortCapabilities', '*')
def retrieveCategories (self, parent):
filepath = self.jukebox_url + "Categories.xml"
dfr = getPage(filepath)
def read_categories(data, parent_item, jukebox_url):
#nbMoviesPerFile = 1 #int(data.find('preferences/mjb.nbThumbnailsPerPage').text)
#self.debug("YMAJ: Nb Movies per file = %s" % nbMoviesPerFile)
for category in data.findall('category'):
type = category.get('name')
category_title = type
if (type != 'Other'):
category_title = "By %s" % category_title
categoryItem = Container(parent_item, category_title)
parent_item.add_child(categoryItem)
for index in category.findall('./index'):
name = index.get('name')
first_filename = index.text
root_name = first_filename[:-2]
self.debug("adding index %s:%s" % (type,name))
parent = categoryItem
if (type == 'Other'):
parent = parent_item
indexItem = LazyContainer(parent, name, None, self.refresh, self.retrieveIndexMovies, per_page=1, name=name, root_name=root_name)
parent.add_child(indexItem)
self.init_completed()
def fail_categories_read(f):
self.warning("failure reading yamj categories (%s): %r" % (filepath,f.getErrorMessage()))
return f
dfr.addCallback(parse_xml)
dfr.addErrback(fail_categories_read)
dfr.addCallback(read_categories, parent_item=parent, jukebox_url=self.jukebox_url)
dfr.addErrback(fail_categories_read)
return dfr
def retrieveIndexMovies (self, parent, name, root_name, per_page=10, page=0, offset=0):
#print offset, per_page
if self.nbMoviesPerFile is None:
counter = 1
else:
counter = abs(offset / self.nbMoviesPerFile) + 1
fileUrl = "%s/%s_%d.xml" % (self.jukebox_url, urllib.quote(root_name), counter)
def fail_readPage(f):
self.warning("failure reading yamj index (%s): %r" % (fileUrl,f.getErrorMessage()))
return f
def fail_parseIndex(f):
self.warning("failure parsing yamj index (%s): %r" % (fileUrl,f.getErrorMessage()))
return f
def readIndex(data):
for index in data.findall('category/index'):
current = index.get('current')
if (current == "true"):
currentIndex = index.get('currentIndex')
lastIndex = index.get('lastIndex')
if (currentIndex != lastIndex):
parent.childrenRetrievingNeeded = True
self.debug("%s: %s/%s" % (root_name, currentIndex, lastIndex))
break
movies = data.findall('movies/movie')
if self.nbMoviesPerFile is None:
self.nbMoviesPerFile = len(movies)
for movie in movies:
isSet = (movie.attrib['isSet'] == 'true')
if isSet is True:
# the movie corresponds to a set
name = movie.find('./title').text
index_name = movie.find('./baseFilename').text
set_root_name = index_name[:-2]
self.debug("adding set %s" % name)
indexItem = LazyContainer(parent, name, None, self.refresh, self.retrieveIndexMovies, per_page=1, name=name, root_name=set_root_name)
parent.add_child(indexItem, set_root_name)
else:
# this is a real movie
movie_id = "UNK"
movie_id_xml = movie.find('./id')
if movie_id_xml is not None:
movie_id = movie_id_xml.text
files = movie.findall('./files/file')
if (len(files) == 1):
url = files[0].find('./fileURL').text
external_id = "%s/%s" % (movie_id,url)
movieItem = MovieItem(movie, self)
parent.add_child(movieItem, external_id)
else:
name = movie.find('./title').text
if name is None or name == '':
name = movie.find('./baseFilename').text
season = movie.find('season').text
if season is not None and season != '-1':
name = "%s - season %s" % (name, season)
container_item = Container(parent, name)
parent.add_child(container_item, name)
container_item.store = self
for file in files:
episodeIndex = file.attrib['firstPart']
episodeTitle = file.attrib['title']
if (episodeTitle == 'UNKNOWN'):
title = "%s - %s" %(name, episodeIndex)
else:
title = "%s - %s " % (episodeIndex, episodeTitle)
episodeUrl = file.find('./fileURL').text
fileItem = MovieItem(movie, self, title=title, url=episodeUrl)
file_external_id = "%s/%s" % (movie_id,episodeUrl)
container_item.add_child(fileItem, file_external_id)
self.debug("Reading index file %s" % fileUrl)
d = getPage(fileUrl)
d.addCallback(parse_xml)
d.addErrback(fail_readPage)
d.addCallback(readIndex)
d.addErrback(fail_parseIndex)
return d
def __repr__(self):
return self.__class__.__name__
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~elisa_renderer.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006, Frank Scholz <[email protected]>
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
from twisted.internet.defer import Deferred
from twisted.python import failure
from twisted.spread import pb
from coherence.upnp.core.soap_service import errorCode
from coherence.upnp.core import DIDLLite
import string
import coherence.extern.louie as louie
from coherence.extern.simple_plugin import Plugin
from coherence import log
class ElisaPlayer(log.Loggable, Plugin):
""" a backend to the Elisa player
"""
logCategory = 'elisa_player'
implements = ['MediaRenderer']
vendor_value_defaults = {'RenderingControl': {'A_ARG_TYPE_Channel':'Master'}}
vendor_range_defaults = {'RenderingControl': {'Volume': {'maximum':100}}}
def __init__(self, device, **kwargs):
self.name = kwargs.get('name','Elisa MediaRenderer')
self.host = kwargs.get('host','127.0.0.1')
self.player = None
self.metadata = None
if self.host == 'internal':
try:
from elisa.core import common
self.player = common.get_application().get_player()
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
except:
self.warning("this works only from within Elisa")
raise ImportError
else:
factory = pb.PBClientFactory()
factory.noisy = False
reactor.connectTCP(self.host, 8789, factory)
d = factory.getRootObject()
def result(player):
self.player = player
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
def got_error(error):
self.warning("connection to Elisa failed!")
d.addCallback(lambda object: object.callRemote("get_player"))
d.addCallback(result)
d.addErrback(got_error)
self.playing = False
self.state = None
self.duration = None
self.view = []
self.tags = {}
self.server = device
self.poll_LC = LoopingCall( self.poll_player)
def call_player(self, method, callback, *args):
self.debug('call player.%s%s', method, args)
if self.host == 'internal':
dfr = Deferred()
dfr.addCallback(callback)
result = getattr(self.player, method)(*args)
dfr.callback(result)
else:
dfr = self.player.callRemote(method, *args)
dfr.addCallback(callback)
return dfr
def __repr__(self):
return str(self.__class__).split('.')[-1]
def poll_player(self):
def got_result(result):
self.info("poll_player %r", result)
if self.server != None:
connection_id = self.server.connection_manager_server.lookup_avt_id(self.current_connection_id)
if result in ('STOPPED','READY'):
transport_state = 'STOPPED'
if result == 'PLAYING':
transport_state = 'PLAYING'
if result == 'PAUSED':
transport_state = 'PAUSED_PLAYBACK'
if transport_state == 'PLAYING':
self.query_position()
if self.state != transport_state:
self.state = transport_state
if self.server != None:
self.server.av_transport_server.set_variable(connection_id,
'TransportState',
transport_state)
self.call_player("get_readable_state", got_result)
def query_position( self):
def got_result(result):
self.info("query_position", result)
position, duration = result
if self.server != None:
connection_id = self.server.connection_manager_server.lookup_avt_id(self.current_connection_id)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrack', 0)
if position is not None:
m,s = divmod( position/1000000000, 60)
h,m = divmod(m,60)
if self.server != None:
self.server.av_transport_server.set_variable(connection_id, 'RelativeTimePosition', '%02d:%02d:%02d' % (h,m,s))
self.server.av_transport_server.set_variable(connection_id, 'AbsoluteTimePosition', '%02d:%02d:%02d' % (h,m,s))
if duration is not None:
m,s = divmod( duration/1000000000, 60)
h,m = divmod(m,60)
if self.server != None:
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackDuration', '%02d:%02d:%02d' % (h,m,s))
self.server.av_transport_server.set_variable(connection_id, 'CurrentMediaDuration', '%02d:%02d:%02d' % (h,m,s))
if self.duration is None:
if self.metadata is not None:
elt = DIDLLite.DIDLElement.fromString(self.metadata)
for item in elt:
for res in item.findall('res'):
res.attrib['duration'] = "%d:%02d:%02d" % (h,m,s)
self.metadata = elt.toString()
if self.server != None:
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURIMetaData',self.metadata)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackMetaData',self.metadata)
self.duration = duration
self.call_player("get_status", got_result)
def load( self, uri, metadata):
def got_result(result):
self.duration = None
self.metadata = metadata
self.tags = {}
connection_id = self.server.connection_manager_server.lookup_avt_id(self.current_connection_id)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTransportActions','Play,Stop,Pause')
self.server.av_transport_server.set_variable(connection_id, 'NumberOfTracks',1)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURIMetaData',metadata)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackMetaData',metadata)
self.call_player("set_uri", got_result, uri)
def start(self, uri):
self.load(uri)
self.play()
def stop(self):
def got_result(result):
self.server.av_transport_server.set_variable( \
self.server.connection_manager_server.lookup_avt_id(self.current_connection_id),\
'TransportState', 'STOPPED')
self.call_player("stop", got_result)
def play(self):
def got_result(result):
self.server.av_transport_server.set_variable( \
self.server.connection_manager_server.lookup_avt_id(self.current_connection_id),\
'TransportState', 'PLAYING')
self.call_player("play", got_result)
def pause(self):
def got_result(result):
self.server.av_transport_server.set_variable( \
self.server.connection_manager_server.lookup_avt_id(self.current_connection_id),\
'TransportState', 'PAUSED_PLAYBACK')
self.call_player("pause", got_result)
def seek(self, location):
"""
@param location: simple number = time to seek to, in seconds
+nL = relative seek forward n seconds
-nL = relative seek backwards n seconds
"""
def mute(self):
def got_result(result):
rcs_id = self.server.connection_manager_server.lookup_rcs_id(self.current_connection_id)
#FIXME: use result, not True
self.server.rendering_control_server.set_variable(rcs_id, 'Mute', 'True')
self.call_player("mute", got_result)
def unmute(self):
def got_result(result):
rcs_id = self.server.connection_manager_server.lookup_rcs_id(self.current_connection_id)
#FIXME: use result, not False
self.server.rendering_control_server.set_variable(rcs_id, 'Mute', 'False')
self.call_player("un_mute", got_result)
def get_mute(self):
def got_infos(result):
self.info("got_mute: %r", result)
return result
return self.call_player("get_mute", got_infos)
def get_volume(self):
""" playbin volume is a double from 0.0 - 10.0
"""
def got_infos(result):
self.info("got_volume: %r", result)
return result
return self.call_player('get_volume', got_infos)
def set_volume(self, volume):
volume = int(volume)
if volume < 0:
volume=0
if volume > 100:
volume=100
def got_result(result):
rcs_id = self.server.connection_manager_server.lookup_rcs_id(self.current_connection_id)
#FIXME: use result, not volume
self.server.rendering_control_server.set_variable(rcs_id, 'Volume', volume)
self.call_player("set_volume", got_result, volume)
def upnp_init(self):
self.current_connection_id = None
self.server.connection_manager_server.set_variable(0, 'SinkProtocolInfo',
['internal:%s:*:*' % self.host,
'http-get:*:audio/mpeg:*'],
default=True)
self.server.av_transport_server.set_variable(0, 'TransportState', 'NO_MEDIA_PRESENT', default=True)
self.server.av_transport_server.set_variable(0, 'TransportStatus', 'OK', default=True)
self.server.av_transport_server.set_variable(0, 'CurrentPlayMode', 'NORMAL', default=True)
self.server.av_transport_server.set_variable(0, 'CurrentTransportActions', '', default=True)
self.server.rendering_control_server.set_variable(0, 'Volume', self.get_volume())
self.server.rendering_control_server.set_variable(0, 'Mute', self.get_mute())
self.poll_LC.start( 1.0, True)
def upnp_Play(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Speed = int(kwargs['Speed'])
self.play()
return {}
def upnp_Pause(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
self.pause()
return {}
def upnp_Stop(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
self.stop()
return {}
def upnp_SetAVTransportURI(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
CurrentURI = kwargs['CurrentURI']
CurrentURIMetaData = kwargs['CurrentURIMetaData']
local_protocol_infos=self.server.connection_manager_server.get_variable('SinkProtocolInfo').value.split(',')
#print '>>>', local_protocol_infos
if len(CurrentURIMetaData)==0:
self.load(CurrentURI,CurrentURIMetaData)
else:
elt = DIDLLite.DIDLElement.fromString(CurrentURIMetaData)
if elt.numItems() == 1:
item = elt.getItems()[0]
res = item.res.get_matching(local_protocol_infos, protocol_type='internal')
if len(res) == 0:
res = item.res.get_matching(local_protocol_infos)
if len(res) > 0:
res = res[0]
remote_protocol,remote_network,remote_content_format,_ = res.protocolInfo.split(':')
self.load(res.data,CurrentURIMetaData)
return {}
return failure.Failure(errorCode(714))
def upnp_SetMute(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Channel = kwargs['Channel']
DesiredMute = kwargs['DesiredMute']
if DesiredMute in ['TRUE', 'True', 'true', '1','Yes','yes']:
self.mute()
else:
self.unmute()
return {}
def upnp_SetVolume(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Channel = kwargs['Channel']
DesiredVolume = int(kwargs['DesiredVolume'])
self.set_volume(DesiredVolume)
return {}
def main():
f = ElisaPlayer(None)
def call_player():
f.get_volume()
f.get_mute()
f.poll_player()
reactor.callLater(2,call_player)
if __name__ == '__main__':
from twisted.internet import reactor
reactor.callWhenRunning(main)
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~devices~binary_light_client.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
from coherence.upnp.services.clients.switch_power_client import SwitchPowerClient
from coherence import log
import coherence.extern.louie as louie
class BinaryLightClient(log.Loggable):
logCategory = 'binarylight_client'
def __init__(self, device):
self.device = device
self.device_type = self.device.get_friendly_device_type()
self.version = int(self.device.get_device_type_version())
self.icons = device.icons
self.switch_power = None
self.detection_completed = False
louie.connect(self.service_notified, signal='Coherence.UPnP.DeviceClient.Service.notified', sender=self.device)
for service in self.device.get_services():
if service.get_type() in ["urn:schemas-upnp-org:service:SwitchPower:1"]:
self.switch_power = SwitchPowerClient(service)
self.info("BinaryLight %s" % (self.device.get_friendly_name()))
if self.switch_power:
self.info("SwitchPower service available")
else:
self.warning("SwitchPower service not available, device not implemented properly according to the UPnP specification")
def remove(self):
self.info("removal of BinaryLightClient started")
if self.switch_power != None:
self.switch_power.remove()
def service_notified(self, service):
self.info("Service %r sent notification" % service);
if self.detection_completed == True:
return
if self.switch_power != None:
if not hasattr(self.switch_power.service, 'last_time_updated'):
return
if self.switch_power.service.last_time_updated == None:
return
self.detection_completed = True
louie.send('Coherence.UPnP.DeviceClient.detection_completed', None,
client=self,udn=self.device.udn)
def state_variable_change( self, variable):
self.info(variable.name, 'changed from', variable.old_value, 'to', variable.value)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~devices~control_point.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006-2010 Frank Scholz <[email protected]>
import string
import traceback
from twisted.internet import task
from twisted.internet import reactor
from twisted.web import xmlrpc, client
from coherence.upnp.core import service
from coherence.upnp.core.event import EventServer
from coherence.upnp.devices.media_server_client import MediaServerClient
from coherence.upnp.devices.media_renderer_client import MediaRendererClient
from coherence.upnp.devices.binary_light_client import BinaryLightClient
from coherence.upnp.devices.dimmable_light_client import DimmableLightClient
from coherence.upnp.devices.internet_gateway_device_client import InternetGatewayDeviceClient
import coherence.extern.louie as louie
from coherence import log
class DeviceQuery(object):
def __init__(self, type, pattern, callback, timeout=0, oneshot=True):
self.type = type
self.pattern = pattern
self.callback = callback
self.fired = False
self.timeout = timeout
self.oneshot = oneshot
if self.type == 'uuid' and self.pattern.startswith('uuid:'):
self.pattern = self.pattern[5:]
def fire(self, device):
if callable(self.callback):
self.callback(device)
elif isinstance(self.callback,basestring):
louie.send(self.callback, None, device=device)
self.fired = True
def check(self, device):
if self.fired and self.oneshot:
return
if(self.type == 'host' and
device.host == self.pattern):
self.fire(device)
elif(self.type == 'friendly_name' and
device.friendly_name == self.pattern):
self.fire(device)
elif(self.type == 'uuid' and
device.get_uuid() == self.pattern):
self.fire(device)
class ControlPoint(log.Loggable):
logCategory = 'controlpoint'
def __init__(self,coherence,auto_client=['MediaServer','MediaRenderer','BinaryLight','DimmableLight']):
self.coherence = coherence
self.info("Coherence UPnP ControlPoint starting...")
self.event_server = EventServer(self)
self.coherence.add_web_resource('RPC2',
XMLRPC(self))
self.auto_client = auto_client
self.queries=[]
for device in self.get_devices():
self.check_device( device)
louie.connect(self.check_device, 'Coherence.UPnP.Device.detection_completed', louie.Any)
louie.connect(self.remove_client, 'Coherence.UPnP.Device.remove_client', louie.Any)
louie.connect(self.completed, 'Coherence.UPnP.DeviceClient.detection_completed', louie.Any)
def shutdown(self):
louie.disconnect(self.check_device, 'Coherence.UPnP.Device.detection_completed', louie.Any)
louie.disconnect(self.remove_client, 'Coherence.UPnP.Device.remove_client', louie.Any)
louie.disconnect(self.completed, 'Coherence.UPnP.DeviceClient.detection_completed', louie.Any)
def auto_client_append(self,device_type):
if device_type in self.auto_client:
return
self.auto_client.append(device_type)
for device in self.get_devices():
self.check_device( device)
def browse(self, device):
device = self.coherence.get_device_with_usn(infos['USN'])
if not device:
return
self.check_device( device)
def process_queries(self, device):
for query in self.queries:
query.check(device)
def add_query(self, query):
for device in self.get_devices():
query.check(device)
if query.fired == False and query.timeout == 0:
query.callback(None)
else:
self.queries.append(query)
def connect(self,receiver,signal=louie.signal.All,sender=louie.sender.Any, weak=True):
""" wrapper method around louie.connect
"""
louie.connect(receiver,signal=signal,sender=sender,weak=weak)
def disconnect(self,receiver,signal=louie.signal.All,sender=louie.sender.Any, weak=True):
""" wrapper method around louie.disconnect
"""
louie.disconnect(receiver,signal=signal,sender=sender,weak=weak)
def get_devices(self):
return self.coherence.get_devices()
def get_device_with_id(self, id):
return self.coherence.get_device_with_id(id)
def get_device_by_host(self, host):
return self.coherence.get_device_by_host(host)
def check_device( self, device):
if device.client == None:
self.info("found device %s of type %s - %r" %(device.get_friendly_name(),
device.get_device_type(), device.client))
short_type = device.get_friendly_device_type()
if short_type in self.auto_client and short_type is not None:
self.info("identified %s %r" %
(short_type, device.get_friendly_name()))
if short_type == 'MediaServer':
client = MediaServerClient(device)
if short_type == 'MediaRenderer':
client = MediaRendererClient(device)
if short_type == 'BinaryLight':
client = BinaryLightClient(device)
if short_type == 'DimmableLight':
client = DimmableLightClient(device)
if short_type == 'InternetGatewayDevice':
client = InternetGatewayDeviceClient(device)
client.coherence = self.coherence
device.set_client( client)
self.process_queries(device)
def completed(self, client, udn):
self.info('sending signal Coherence.UPnP.ControlPoint.%s.detected %r' % (client.device_type, udn))
louie.send('Coherence.UPnP.ControlPoint.%s.detected' % client.device_type, None,
client=client,udn=udn)
def remove_client(self, udn, client):
louie.send('Coherence.UPnP.ControlPoint.%s.removed' % client.device_type, None, udn=udn)
self.info("removed %s %s" % (client.device_type,client.device.get_friendly_name()))
client.remove()
def propagate(self, event):
self.info('propagate: %r', event)
if event.get_sid() in service.subscribers.keys():
try:
service.subscribers[event.get_sid()].process_event(event)
except Exception, msg:
self.debug(msg)
self.debug(traceback.format_exc())
pass
def put_resource(self, url, path):
def got_result(result):
print result
def got_error(result):
print "error", result
try:
f = open(path)
data = f.read()
f.close()
headers= {
"Content-Type": "application/octet-stream",
"Content-Length": str(len(data))
}
df = client.getPage(url, method="POST",
headers=headers, postdata=data)
df.addCallback(got_result)
df.addErrback(got_error)
return df
except IOError:
pass
class XMLRPC( xmlrpc.XMLRPC):
def __init__(self, control_point):
self.control_point = control_point
self.allowNone = True
def xmlrpc_list_devices(self):
print "list_devices"
r = []
for device in self.control_point.get_devices():
#print device.get_friendly_name(), device.get_service_type(), device.get_location(), device.get_id()
d = {}
d[u'friendly_name']=device.get_friendly_name()
d[u'device_type']=device.get_device_type()
d[u'location']=unicode(device.get_location())
d[u'id']=unicode(device.get_id())
r.append(d)
return r
def xmlrpc_mute_device(self, device_id):
print "mute"
device = self.control_point.get_device_with_id(device_id)
if device != None:
client = device.get_client()
client.rendering_control.set_mute(desired_mute=1)
return "Ok"
return "Error"
def xmlrpc_unmute_device(self, device_id):
print "unmute", device_id
device = self.control_point.get_device_with_id(device_id)
if device != None:
client = device.get_client()
client.rendering_control.set_mute(desired_mute=0)
return "Ok"
return "Error"
def xmlrpc_set_volume(self, device_id, volume):
print "set volume"
device = self.control_point.get_device_with_id(device_id)
if device != None:
client = device.get_client()
client.rendering_control.set_volume(desired_volume=volume)
return "Ok"
return "Error"
def xmlrpc_play(self, device_id):
print "play"
device = self.control_point.get_device_with_id(device_id)
if device != None:
client = device.get_client()
client.av_transport.play()
return "Ok"
return "Error"
def xmlrpc_pause(self, device_id):
print "pause"
device = self.control_point.get_device_with_id(device_id)
if device != None:
client = device.get_client()
client.av_transport.pause()
return "Ok"
return "Error"
def xmlrpc_stop(self, device_id):
print "stop"
device = self.control_point.get_device_with_id(device_id)
if device != None:
client = device.get_client()
client.av_transport.stop()
return "Ok"
return "Error"
def xmlrpc_next(self, device_id):
print "next"
device = self.control_point.get_device_with_id(device_id)
if device != None:
client = device.get_client()
client.av_transport.next()
return "Ok"
return "Error"
def xmlrpc_previous(self, device_id):
print "previous"
device = self.control_point.get_device_with_id(device_id)
if device != None:
client = device.get_client()
client.av_transport.previous()
return "Ok"
return "Error"
def xmlrpc_set_av_transport_uri(self, device_id, uri):
print "set_av_transport_uri"
device = self.control_point.get_device_with_id(device_id)
if device != None:
client = device.get_client()
client.av_transport.set_av_transport_uri(current_uri=uri)
return "Ok"
return "Error"
def xmlrpc_create_object(self, device_id, container_id, arguments):
print "create_object", arguments
device = self.control_point.get_device_with_id(device_id)
if device != None:
client = device.get_client()
client.content_directory.create_object(container_id, arguments)
return "Ok"
return "Error"
def xmlrpc_import_resource(self, device_id, source_uri, destination_uri):
print "import_resource", source_uri, destination_uri
device = self.control_point.get_device_with_id(device_id)
if device != None:
client = device.get_client()
client.content_directory.import_resource(source_uri, destination_uri)
return "Ok"
return "Error"
def xmlrpc_put_resource(self, url, path):
print "put_resource", url, path
self.control_point.put_resource(url, path)
return "Ok"
def xmlrpc_ping(self):
print "ping"
return "Ok"
def startXMLRPC( control_point, port):
from twisted.web import server
r = XMLRPC( control_point)
print "XMLRPC-API on port %d ready" % port
reactor.listenTCP(port, server.Site(r), interface="::")
if __name__ == '__main__':
from coherence.base import Coherence
from coherence.upnp.devices.media_server_client import MediaServerClient
from coherence.upnp.devices.media_renderer_client import MediaRendererClient
config = {}
config['logmode'] = 'warning'
config['serverport'] = 30020
#ctrl = ControlPoint(Coherence(config),auto_client=[])
#ctrl = ControlPoint(Coherence(config))
def show_devices():
print "show_devices"
for d in ctrl.get_devices():
print d, d.get_id()
def the_result(r):
print "result", r, r.get_id()
def query_devices():
print "query_devices"
ctrl.add_query(DeviceQuery('host', '192.168.1.163', the_result))
def query_devices2():
print "query_devices with timeout"
ctrl.add_query(DeviceQuery('host', '192.168.1.163', the_result, timeout=10, oneshot=False))
#reactor.callLater(2, show_devices)
#reactor.callLater(3, query_devices)
#reactor.callLater(4, query_devices2)
#reactor.callLater(5, ctrl.add_query, DeviceQuery('friendly_name', 'Coherence Test Content', the_result, timeout=10, oneshot=False))
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | misc~Rhythmbox-Plugin~upnp_coherence~MediaPlayer.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2011, Caleb Callaway <[email protected]>
# Copyright 2008-2010, Frank Scholz <[email protected]>
import os.path
import urllib
from twisted.python import failure
import rhythmdb
from coherence.upnp.core.soap_service import errorCode
from coherence.upnp.core import DIDLLite
import coherence.extern.louie as louie
from coherence.extern.simple_plugin import Plugin
from coherence import log
from CoherenceDBEntryType import CoherenceDBEntryType
TRACK_COUNT = 1000000
class RhythmboxPlayer(log.Loggable):
""" a backend to the Rhythmbox
"""
logCategory = 'rb_media_renderer'
implements = ['MediaRenderer']
vendor_value_defaults = {'RenderingControl': {'A_ARG_TYPE_Channel':'Master'},
'AVTransport': {'A_ARG_TYPE_SeekMode':('ABS_TIME','REL_TIME','TRACK_NR')}}
vendor_range_defaults = {'RenderingControl': {'Volume': {'maximum':100}}}
def __init__(self, device, **kwargs):
self.warning("__init__ RhythmboxPlayer %r", kwargs)
self.shell = kwargs['shell']
self.server = device
self.dmr_uuid = kwargs['dmr_uuid']
self.player = None
self.entry = None
self.metadata = None
try:
self.name = kwargs['name']
except KeyError:
self.name = "Rhythmbox on %s" % self.server.coherence.hostname
self.player = self.shell.get_player()
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
coherence_player_entry_type = CoherenceDBEntryType("CoherencePlayer")
self.shell.props.db.register_entry_type(coherence_player_entry_type)
self.playing = False
self.state = None
self.duration = None
self.volume = 1.0
self.muted_volume = None
self.view = []
self.tags = {}
def __repr__(self):
return str(self.__class__).split('.')[-1]
def volume_changed(self, player, parameter):
self.volume = self.player.props.volume
self.info('volume_changed to %r', self.volume)
if self.volume > 0:
rcs_id = self.server.connection_manager_server.lookup_rcs_id(self.current_connection_id)
self.server.rendering_control_server.set_variable(rcs_id, 'Volume', self.volume*100)
def playing_song_changed(self, player, entry):
self.info("playing_song_changed %r", entry)
if self.server != None:
connection_id = self.server.connection_manager_server.lookup_avt_id(self.current_connection_id)
if entry == None:
self.update('STOPPED')
self.playing = False
#self.entry = None
self.metadata = None
self.duration = None
else:
id = self.shell.props.db.entry_get (entry, rhythmdb.PROP_ENTRY_ID)
bitrate = self.shell.props.db.entry_get(entry, rhythmdb.PROP_BITRATE) * 1024 / 8
# Duration is in HH:MM:SS format
seconds = self.shell.props.db.entry_get(entry, rhythmdb.PROP_DURATION)
hours = seconds / 3600
seconds = seconds - hours * 3600
minutes = seconds / 60
seconds = seconds - minutes * 60
self.duration = "%02d:%02d:%02d" % (hours, minutes, seconds)
mimetype = self.shell.props.db.entry_get(entry, rhythmdb.PROP_MIMETYPE)
# This isn't a real mime-type
if mimetype == "application/x-id3":
mimetype = "audio/mpeg"
size = self.shell.props.db.entry_get(entry, rhythmdb.PROP_FILE_SIZE)
# create item
item = DIDLLite.MusicTrack(id + TRACK_COUNT,'101')
item.album = self.shell.props.db.entry_get(entry, rhythmdb.PROP_ALBUM)
item.artist = self.shell.props.db.entry_get(entry, rhythmdb.PROP_ARTIST)
item.genre = self.shell.props.db.entry_get(entry, rhythmdb.PROP_GENRE)
item.originalTrackNumber = str(self.shell.props.db.entry_get (entry, rhythmdb.PROP_TRACK_NUMBER))
item.title = self.shell.props.db.entry_get(entry, rhythmdb.PROP_TITLE) # much nicer if it was entry.title
cover = self.shell.props.db.entry_request_extra_metadata(entry, "rb:coverArt-uri")
if cover != None:
_,ext = os.path.splitext(cover)
item.albumArtURI = ''.join((self.server.coherence.urlbase+str(self.dmr_uuid)[5:]+'/'+ str(int(id) + TRACK_COUNT),'?cover',ext))
item.res = []
location = self.shell.props.db.entry_get(entry, rhythmdb.PROP_LOCATION)
if location.startswith("file://"):
location = unicode(urllib.unquote(location[len("file://"):]))
uri = ''.join((self.server.coherence.urlbase+str(self.dmr_uuid)[5:]+'/'+ str(int(id) + TRACK_COUNT)))
res = DIDLLite.Resource(uri, 'http-get:*:%s:*' % mimetype)
if size > 0:
res.size = size
if self.duration > 0:
res.duration = self.duration
if bitrate > 0:
res.bitrate = str(bitrate)
item.res.append(res)
# add internal resource
res = DIDLLite.Resource('track-%d' % id, 'rhythmbox:%s:%s:*' % (self.server.coherence.hostname, mimetype))
if size > 0:
res.size = size
if self.duration > 0:
res.duration = str(self.duration)
if bitrate > 0:
res.bitrate = str(bitrate)
item.res.append(res)
elt = DIDLLite.DIDLElement()
elt.addItem(item)
self.metadata = elt.toString()
self.entry = entry
if self.server != None:
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURIMetaData',self.metadata)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackMetaData',self.metadata)
self.info("playing_song_changed %r", self.metadata)
if self.server != None:
self.server.av_transport_server.set_variable(connection_id, 'CurrentTransportActions','PLAY,STOP,PAUSE,SEEK,NEXT,PREVIOUS')
self.server.av_transport_server.set_variable(connection_id, 'RelativeTimePosition', '00:00:00')
self.server.av_transport_server.set_variable(connection_id, 'AbsoluteTimePosition', '00:00:00')
def playing_changed(self, player, state):
self.info("playing_changed", state)
if state is True:
transport_state = 'PLAYING'
else:
if self.playing is False:
transport_state = 'STOPPED'
else:
transport_state = 'PAUSED_PLAYBACK'
self.update(transport_state)
try:
position = player.get_playing_time()
except:
position = None
try:
duration = player.get_playing_song_duration()
except:
duration = None
self.update_position(position,duration)
self.info("playing_changed %r %r ", position, duration)
def elapsed_changed(self, player, time):
self.info("elapsed_changed %r %r", player, time)
try:
duration = player.get_playing_song_duration()
except:
duration = None
self.update_position(time,duration)
def update(self, state):
self.info("update %r", state)
if state in ('STOPPED','READY'):
transport_state = 'STOPPED'
if state == 'PLAYING':
transport_state = 'PLAYING'
if state == 'PAUSED_PLAYBACK':
transport_state = 'PAUSED_PLAYBACK'
if self.state != transport_state:
self.state = transport_state
if self.server != None:
connection_id = self.server.connection_manager_server.lookup_avt_id(self.current_connection_id)
self.server.av_transport_server.set_variable(connection_id,
'TransportState',
transport_state)
def update_position(self, position,duration):
self.info("update_position %r %r", position,duration)
if self.server != None:
connection_id = self.server.connection_manager_server.lookup_avt_id(self.current_connection_id)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrack', 1)
if position is not None:
m,s = divmod( position, 60)
h,m = divmod(m,60)
if self.server != None:
self.server.av_transport_server.set_variable(connection_id, 'RelativeTimePosition', '%02d:%02d:%02d' % (h,m,s))
self.server.av_transport_server.set_variable(connection_id, 'AbsoluteTimePosition', '%02d:%02d:%02d' % (h,m,s))
if duration <= 0:
duration = None
if duration is not None:
m,s = divmod( duration, 60)
h,m = divmod(m,60)
if self.server != None:
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackDuration', '%02d:%02d:%02d' % (h,m,s))
self.server.av_transport_server.set_variable(connection_id, 'CurrentMediaDuration', '%02d:%02d:%02d' % (h,m,s))
if self.duration is None:
if self.metadata is not None:
self.info("update_position %r", self.metadata)
elt = DIDLLite.DIDLElement.fromString(self.metadata)
for item in elt:
for res in item.findall('res'):
res.attrib['duration'] = "%d:%02d:%02d" % (h,m,s)
self.metadata = elt.toString()
if self.server != None:
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURIMetaData',self.metadata)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackMetaData',self.metadata)
self.duration = duration
def load( self, uri, metadata):
self.info("player load %r %r", uri, metadata)
#self.shell.load_uri(uri,play=False)
self.duration = None
self.metadata = metadata
self.tags = {}
was_playing = self.playing
if was_playing == True:
self.stop()
if len(metadata)>0:
elt = DIDLLite.DIDLElement.fromString(metadata)
if elt.numItems() == 1:
item = elt.getItems()[0]
if uri.startswith('track-'):
self.entry = self.shell.props.db.entry_lookup_by_id(int(uri[6:]))
else:
self.entry = self.shell.props.db.entry_lookup_by_location(uri)
self.info("check for entry %r %r %r", self.entry,item.server_uuid,uri)
if self.entry == None:
db = self.shell.props.db
if item.server_uuid is not None:
entry_type = CoherenceDBEntryType("CoherenceUpnp:" + item.server_uuid)
db.register_entry_type(entry_type)
self.entry = self.shell.props.db.entry_new(entry_type, uri)
self.info("create new entry %r", self.entry)
else:
self.entry = self.shell.props.db.entry_new(self.coherence_player_entry_type, uri)
self.info("load and check for entry %r", self.entry)
duration = None
size = None
bitrate = None
for res in item.res:
if res.data == uri:
duration = res.duration
size = res.size
bitrate = res.bitrate
break
self.shell.props.db.set(self.entry, rhythmdb.PROP_TITLE, item.title)
try:
if item.artist is not None:
self.shell.props.db.set(self.entry, rhythmdb.PROP_ARTIST, item.artist)
except AttributeError:
pass
try:
if item.album is not None:
self.shell.props.db.set(self.entry, rhythmdb.PROP_ALBUM, item.album)
except AttributeError:
pass
try:
self.info("%r %r", item.title,item.originalTrackNumber)
if item.originalTrackNumber is not None:
self.shell.props.db.set(self.entry, rhythmdb.PROP_TRACK_NUMBER, int(item.originalTrackNumber))
except AttributeError:
pass
if duration is not None:
h,m,s = duration.split(':')
seconds = int(h)*3600 + int(m)*60 + int(s)
self.info("%r %r:%r:%r %r", duration, h, m , s, seconds)
self.shell.props.db.set(self.entry, rhythmdb.PROP_DURATION, seconds)
if size is not None:
self.shell.props.db.set(self.entry, rhythmdb.PROP_FILE_SIZE,int(size))
else:
if uri.startswith('track-'):
self.entry = self.shell.props.db.entry_lookup_by_id(int(uri[6:]))
else:
#self.shell.load_uri(uri,play=False)
#self.entry = self.shell.props.db.entry_lookup_by_location(uri)
self.entry = self.shell.props.db.entry_new(self.coherence_player_entry_type, uri)
self.playing = False
self.metadata = metadata
connection_id = self.server.connection_manager_server.lookup_avt_id(self.current_connection_id)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTransportActions','PLAY,STOP,PAUSE,SEEK,NEXT,PREVIOUS')
self.server.av_transport_server.set_variable(connection_id, 'NumberOfTracks',1)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURIMetaData',metadata)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackMetaData',metadata)
if was_playing == True:
self.play()
def start(self, uri):
self.load(uri)
self.play()
def stop(self):
self.info("player stop")
self.player.stop()
self.playing = False
#self.server.av_transport_server.set_variable( \
# self.server.connection_manager_server.lookup_avt_id(self.current_connection_id),\
# 'TransportState', 'STOPPED')
def play(self):
self.info("player play")
if self.playing == False:
if self.entry:
self.player.play_entry(self.entry)
else:
self.player.playpause()
self.playing = True
else:
self.player.playpause()
#self.server.av_transport_server.set_variable( \
# self.server.connection_manager_server.lookup_avt_id(self.current_connection_id),\
# 'TransportState', 'PLAYING')
def pause(self):
self.player.pause()
#self.server.av_transport_server.set_variable( \
# self.server.connection_manager_server.lookup_avt_id(self.current_connection_id),\
# 'TransportState', 'PAUSED_PLAYBACK')
def seek(self, location, old_state):
"""
@param location: +nL = relative seek forward n seconds
-nL = relative seek backwards n seconds
"""
self.info("player seek %r", location)
self.player.seek(location)
self.server.av_transport_server.set_variable(0, 'TransportState', old_state)
def mute(self):
self.muted_volume = self.volume
self.player.set_volume(0)
rcs_id = self.server.connection_manager_server.lookup_rcs_id(self.current_connection_id)
self.server.rendering_control_server.set_variable(rcs_id, 'Mute', 'True')
def unmute(self):
if self.muted_volume is not None:
self.player.set_volume(self.muted_volume)
self.muted_volume = None
self.player.set_mute(False)
rcs_id = self.server.connection_manager_server.lookup_rcs_id(self.current_connection_id)
self.server.rendering_control_server.set_variable(rcs_id, 'Mute', 'False')
def get_mute(self):
return self.player.get_mute()
def get_volume(self):
self.volume = self.player.get_volume()
self.info("get_volume %r", self.volume)
return self.volume * 100
def set_volume(self, volume):
self.info("set_volume %r", volume)
volume = int(volume)
if volume < 0:
volume=0
if volume > 100:
volume=100
self.player.set_volume(float(volume/100.0))
def upnp_init(self):
self.player.connect ('playing-song-changed',
self.playing_song_changed),
self.player.connect ('playing-changed',
self.playing_changed)
self.player.connect ('elapsed-changed',
self.elapsed_changed)
self.player.connect("notify::volume", self.volume_changed)
self.current_connection_id = None
self.server.connection_manager_server.set_variable(0, 'SinkProtocolInfo',
['rhythmbox:%s:audio/mpeg:*' % self.server.coherence.hostname,
'http-get:*:audio/mpeg:*',
'rhythmbox:%s:application/ogg:*' % self.server.coherence.hostname,
'http-get:*:application/ogg:*',
'rhythmbox:%s:audio/ogg:*' % self.server.coherence.hostname,
'http-get:*:audio/ogg:*',
'rhythmbox:%s:audio/x-flac:*' % self.server.coherence.hostname,
'http-get:*:audio/x-flac:*',
'rhythmbox:%s:audio/flac:*' % self.server.coherence.hostname,
'http-get:*:audio/flac:*',
'rhythmbox:%s:audio/x-wav:*' % self.server.coherence.hostname,
'http-get:*:audio/x-wav:*',
'rhythmbox:%s:audio/L16;rate=44100;channels=2:*' % self.server.coherence.hostname,
'http-get:*:audio/L16;rate=44100;channels=2:*',
'rhythmbox:%s:audio/x-m4a:*' % self.server.coherence.hostname,
'http-get:*:audio/x-m4a:*'],
default=True)
self.server.av_transport_server.set_variable(0, 'TransportState', 'NO_MEDIA_PRESENT', default=True)
self.server.av_transport_server.set_variable(0, 'TransportStatus', 'OK', default=True)
self.server.av_transport_server.set_variable(0, 'CurrentPlayMode', 'NORMAL', default=True)
self.server.av_transport_server.set_variable(0, 'CurrentTransportActions', '', default=True)
self.server.rendering_control_server.set_variable(0, 'Volume', self.get_volume())
self.server.rendering_control_server.set_variable(0, 'Mute', self.get_mute())
def upnp_Play(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Speed = int(kwargs['Speed'])
self.play()
return {}
def upnp_Previous(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
self.player.do_previous()
return {}
def upnp_Next(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
self.player.do_next()
return {}
def upnp_Pause(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
self.pause()
return {}
def upnp_Stop(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
self.stop()
return {}
def upnp_Seek(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Unit = kwargs['Unit']
Target = kwargs['Target']
if Unit in ['ABS_TIME','REL_TIME']:
old_state = self.server.av_transport_server.get_variable('TransportState').value
self.server.av_transport_server.set_variable(0, 'TransportState', 'TRANSITIONING')
sign = 1
if Target[0] == '+':
Target = Target[1:]
if Target[0] == '-':
Target = Target[1:]
sign = -1
h,m,s = Target.split(':')
seconds = int(h)*3600 + int(m)*60 + int(s)
if Unit == 'ABS_TIME':
position = self.player.get_playing_time()
self.seek(seconds-position, old_state)
elif Unit == 'REL_TIME':
self.seek(seconds*sign, old_state)
return {}
def upnp_Next(self,*args,**kwargs):
self.player.do_next()
return {}
def upnp_Previous(self,*args,**kwargs):
self.player.do_previous()
return {}
def upnp_SetAVTransportURI(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
CurrentURI = kwargs['CurrentURI']
CurrentURIMetaData = kwargs['CurrentURIMetaData']
local_protocol_infos=self.server.connection_manager_server.get_variable('SinkProtocolInfo').value.split(',')
#print '>>>', local_protocol_infos
if len(CurrentURIMetaData)==0:
self.load(CurrentURI,CurrentURIMetaData)
return {}
else:
elt = DIDLLite.DIDLElement.fromString(CurrentURIMetaData)
#import pdb; pdb.set_trace()
if elt.numItems() == 1:
item = elt.getItems()[0]
res = item.res.get_matching(local_protocol_infos, protocol_type='rhythmbox')
if len(res) == 0:
res = item.res.get_matching(local_protocol_infos)
if len(res) > 0:
res = res[0]
remote_protocol,remote_network,remote_content_format,_ = res.protocolInfo.split(':')
self.load(res.data,CurrentURIMetaData)
return {}
return failure.Failure(errorCode(714))
def upnp_SetMute(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Channel = kwargs['Channel']
DesiredMute = kwargs['DesiredMute']
if DesiredMute in ['TRUE', 'True', 'true', '1','Yes','yes']:
self.mute()
else:
self.unmute()
return {}
def upnp_SetVolume(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Channel = kwargs['Channel']
DesiredVolume = int(kwargs['DesiredVolume'])
self.set_volume(DesiredVolume)
return {}
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~services~servers~connection_manager_server.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006, Frank Scholz <[email protected]>
# Connection Manager service
import time
from twisted.web import resource
from twisted.python import failure
from twisted.internet import task
from coherence.upnp.core.soap_service import UPnPPublisher
from coherence.upnp.core.soap_service import errorCode
from coherence.upnp.core import service
from coherence.upnp.core.DIDLLite import build_dlna_additional_info
from coherence import log
class ConnectionManagerControl(service.ServiceControl,UPnPPublisher):
def __init__(self, server):
self.service = server
self.variables = server.get_variables()
self.actions = server.get_actions()
class ConnectionManagerServer(service.ServiceServer, resource.Resource,
log.Loggable):
logCategory = 'connection_manager_server'
def __init__(self, device, backend=None):
self.device = device
if backend == None:
backend = self.device.backend
resource.Resource.__init__(self)
service.ServiceServer.__init__(self, 'ConnectionManager', self.device.version, backend)
self.control = ConnectionManagerControl(self)
self.putChild(self.scpd_url, service.scpdXML(self, self.control))
self.putChild(self.control_url, self.control)
self.next_connection_id = 1
self.next_avt_id = 1
self.next_rcs_id = 1
self.connections = {}
self.set_variable(0, 'SourceProtocolInfo', '')
self.set_variable(0, 'SinkProtocolInfo', '')
self.set_variable(0, 'CurrentConnectionIDs', '')
self.does_playcontainer = False
try:
if 'playcontainer-0-1' in backend.dlna_caps:
self.does_playcontainer = True
except AttributeError:
pass
self.remove_lingering_connections_loop = task.LoopingCall(self.remove_lingering_connections)
self.remove_lingering_connections_loop.start(180.0, now=False)
def release(self):
self.remove_lingering_connections_loop.stop()
def add_connection(self, RemoteProtocolInfo,
Direction,
PeerConnectionID,
PeerConnectionManager):
id = self.next_connection_id
self.next_connection_id += 1
avt_id = 0
rcs_id = 0
if self.device.device_type == 'MediaServer':
self.connections[id] = {'ProtocolInfo':RemoteProtocolInfo,
'Direction':Direction,
'PeerConnectionID':PeerConnectionID,
'PeerConnectionManager':PeerConnectionManager,
'AVTransportID':avt_id,
'RcsID':rcs_id,
'Status':'OK'}
if self.device.device_type == 'MediaRenderer':
""" this is the place to instantiate AVTransport and RenderingControl
for this connection
"""
avt_id = self.next_avt_id
self.next_avt_id += 1
self.device.av_transport_server.create_new_instance(avt_id)
rcs_id = self.next_rcs_id
self.next_rcs_id += 1
self.device.rendering_control_server.create_new_instance(rcs_id)
self.connections[id] = {'ProtocolInfo':RemoteProtocolInfo,
'Direction':Direction,
'PeerConnectionID':PeerConnectionID,
'PeerConnectionManager':PeerConnectionManager,
'AVTransportID':avt_id,
'RcsID':rcs_id,
'Status':'OK'}
self.backend.current_connection_id = id
csv_ids = ','.join([str(x) for x in self.connections])
self.set_variable(0, 'CurrentConnectionIDs', csv_ids)
return id, avt_id, rcs_id
def remove_connection(self,id):
if self.device.device_type == 'MediaRenderer':
try:
self.device.av_transport_server.remove_instance(self.lookup_avt_id(id))
self.device.rendering_control_server.remove_instance(self.lookup_rcs_id(id))
del self.connections[id]
except:
pass
self.backend.current_connection_id = None
if self.device.device_type == 'MediaServer':
del self.connections[id]
csv_ids = ','.join([str(x) for x in self.connections])
self.set_variable(0, 'CurrentConnectionIDs', csv_ids)
def remove_lingering_connections(self):
""" check if we have a connection that hasn't a StateVariable change
within the last 300 seconds, if so remove it
"""
if self.device.device_type != 'MediaRenderer':
return
now = time.time()
for id, connection in self.connections.items():
avt_id = connection['AVTransportID']
rcs_id = connection['RcsID']
avt_active = True
rcs_active = True
#print "remove_lingering_connections", id, avt_id, rcs_id
if avt_id > 0:
avt_variables = self.device.av_transport_server.get_variables().get(avt_id)
if avt_variables:
avt_active = False
for variable in avt_variables.values():
if variable.last_time_touched+300 >= now:
avt_active = True
break
if rcs_id > 0:
rcs_variables = self.device.rendering_control_server.get_variables().get(rcs_id)
if rcs_variables:
rcs_active = False
for variable in rcs_variables.values():
if variable.last_time_touched+300 >= now:
rcs_active = True
break
if( avt_active == False and rcs_active == False):
self.remove_connection(id)
def lookup_connection(self,id):
return self.connections.get(id)
def lookup_avt_id(self,id):
try:
return self.connections[id]['AVTransportID']
except:
return 0
def lookup_rcs_id(self,id):
try:
return self.connections[id]['RcsID']
except:
return 0
def listchilds(self, uri):
cl = ''
for c in self.children:
cl += '<li><a href=%s/%s>%s</a></li>' % (uri,c,c)
return cl
def render(self,request):
return '<html><p>root of the ConnectionManager</p><p><ul>%s</ul></p></html>'% self.listchilds(request.uri)
def set_variable(self, instance, variable_name, value, default=False):
if(variable_name == 'SourceProtocolInfo' or
variable_name == 'SinkProtocolInfo'):
if isinstance(value,basestring) and len(value) > 0:
value = [v.strip() for v in value.split(',')]
without_dlna_tags = []
for v in value:
protocol,network,content_format,additional_info = v.split(':')
if additional_info == '*':
without_dlna_tags.append(v)
def with_some_tag_already_there(protocolinfo):
protocol,network,content_format,additional_info = protocolinfo.split(':')
for v in value:
v_protocol,v_network,v_content_format,v_additional_info = v.split(':')
if((protocol,network,content_format) ==
(v_protocol,v_network,v_content_format) and
v_additional_info != '*'):
return True
return False
for w in without_dlna_tags:
if with_some_tag_already_there(w) == False:
protocol,network,content_format,additional_info = w.split(':')
if variable_name == 'SinkProtocolInfo':
value.append(':'.join((protocol,network,content_format,build_dlna_additional_info(content_format,does_playcontainer=self.does_playcontainer))))
else:
value.append(':'.join((protocol,network,content_format,build_dlna_additional_info(content_format))))
service.ServiceServer.set_variable(self,instance,variable_name,value,default=default)
def upnp_PrepareForConnection(self, *args, **kwargs):
self.info('upnp_PrepareForConnection')
""" check if we really support that mimetype """
RemoteProtocolInfo = kwargs['RemoteProtocolInfo']
""" if we are a MR and this in not 'Input'
then there is something strange going on
"""
Direction = kwargs['Direction']
if( self.device.device_type == 'MediaRenderer' and
Direction == 'Output'):
return failure.Failure(errorCode(702))
if( self.device.device_type == 'MediaServer' and
Direction != 'Input'):
return failure.Failure(errorCode(702))
""" the InstanceID of the MS ? """
PeerConnectionID = kwargs['PeerConnectionID']
""" ??? """
PeerConnectionManager = kwargs['PeerConnectionManager']
local_protocol_infos = None
if self.device.device_type == 'MediaRenderer':
local_protocol_infos = self.get_variable('SinkProtocolInfo').value
if self.device.device_type == 'MediaServer':
local_protocol_infos = self.get_variable('SourceProtocolInfo').value
self.debug('ProtocalInfos:',RemoteProtocolInfo, '--', local_protocol_infos)
try:
remote_protocol,remote_network,remote_content_format,_ = RemoteProtocolInfo.split(':')
except:
self.warning("unable to process RemoteProtocolInfo", RemoteProtocolInfo)
return failure.Failure(errorCode(701))
for protocol_info in local_protocol_infos.split(','):
#print remote_protocol,remote_network,remote_content_format
#print protocol_info
local_protocol,local_network,local_content_format,_ = protocol_info.split(':')
#print local_protocol,local_network,local_content_format
if((remote_protocol == local_protocol or
remote_protocol == '*' or
local_protocol == '*') and
(remote_network == local_network or
remote_network == '*' or
local_network == '*') and
(remote_content_format == local_content_format or
remote_content_format == '*' or
local_content_format == '*')):
connection_id, avt_id, rcs_id = \
self.add_connection(RemoteProtocolInfo,
Direction,
PeerConnectionID,
PeerConnectionManager)
return {'ConnectionID': connection_id, 'AVTransportID': avt_id, 'RcsID': rcs_id}
return failure.Failure(errorCode(701))
def upnp_ConnectionComplete(self, *args, **kwargs):
ConnectionID = int(kwargs['ConnectionID'])
""" remove this ConnectionID
and the associated instances @ AVTransportID and RcsID
"""
self.remove_connection(ConnectionID)
return {}
def upnp_GetCurrentConnectionInfo(self, *args, **kwargs):
ConnectionID = int(kwargs['ConnectionID'])
""" return for this ConnectionID
the associated InstanceIDs @ AVTransportID and RcsID
ProtocolInfo
PeerConnectionManager
PeerConnectionID
Direction
Status
or send a 706 if there isn't such a ConnectionID
"""
connection = self.lookup_connection(ConnectionID)
if connection == None:
return failure.Failure(errorCode(706))
else:
return {'AVTransportID':connection['AVTransportID'],
'RcsID':connection['RcsID'],
'ProtocolInfo':connection['ProtocolInfo'],
'PeerConnectionManager':connection['PeerConnectionManager'],
'PeerConnectionID':connection['PeerConnectionID'],
'Direction':connection['Direction'],
'Status':connection['Status'],
}
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~miroguide_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Coherence backend presenting the content of the MIRO Guide catalog for on-line videos
#
# The APi is described on page:
# https://develop.participatoryculture.org/trac/democracy/wiki/MiroGuideApi
# Copyright 2009, Jean-Michel Sizun
# Copyright 2009 Frank Scholz <[email protected]>
import urllib
from coherence.upnp.core import utils
from coherence.upnp.core import DIDLLite
from coherence.backend import BackendStore, BackendItem, Container, LazyContainer, \
AbstractBackendStore
from coherence.backends.youtube_storage import TestVideoProxy
class VideoItem(BackendItem):
def __init__(self, name, description, url, thumbnail_url, store):
self.name = name
self.duration = None
self.size = None
self.mimetype = "video"
self.url = None
self.video_url = url
self.thumbnail_url = thumbnail_url
self.description = description
self.date = None
self.item = None
self.location = TestVideoProxy(self.video_url, hash(self.video_url),
store.proxy_mode,
store.cache_directory, store.cache_maxsize,store.buffer_size
)
def get_item(self):
if self.item == None:
upnp_id = self.get_id()
upnp_parent_id = self.parent.get_id()
self.item = DIDLLite.VideoItem(upnp_id, upnp_parent_id, self.name)
self.item.description = self.description
self.item.date = self.date
if self.thumbnail_url is not None:
self.item.icon = self.thumbnail_url
self.item.albumArtURI = self.thumbnail_url
res = DIDLLite.Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
res.duration = self.duration
res.size = self.size
self.item.res.append(res)
return self.item
def get_path(self):
return self.url
def get_id(self):
return self.storage_id
class MiroGuideStore(AbstractBackendStore):
logCategory = 'miroguide_store'
implements = ['MediaServer']
description = ('Miro Guide', 'connects to the MIRO Guide service and exposes the podcasts catalogued by the service. ', None)
options = [{'option':'name', 'text':'Server Name:', 'type':'string','default':'my media','help': 'the name under this MediaServer shall show up with on other UPnP clients'},
{'option':'version','text':'UPnP Version:','type':'int','default':2,'enum': (2,1),'help': 'the highest UPnP version this MediaServer shall support','level':'advance'},
{'option':'uuid','text':'UUID Identifier:','type':'string','help':'the unique (UPnP) identifier for this MediaServer, usually automatically set','level':'advance'},
{'option':'language','text':'Language:','type':'string', 'default':'English'},
{'option':'refresh','text':'Refresh period','type':'string'},
{'option':'proxy_mode','text':'Proxy mode:','type':'string', 'enum': ('redirect','proxy','cache','buffered')},
{'option':'buffer_size','text':'Buffering size:','type':'int'},
{'option':'cache_directory','text':'Cache directory:','type':'dir', 'group':'Cache'},
{'option':'cache_maxsize','text':'Cache max size:','type':'int', 'group':'Cache'},
]
def __init__(self, server, **kwargs):
AbstractBackendStore.__init__(self, server, **kwargs)
self.name = kwargs.get('name','MiroGuide')
self.language = kwargs.get('language','English')
self.refresh = int(kwargs.get('refresh',60))*60
self.proxy_mode = kwargs.get('proxy_mode', 'redirect')
self.cache_directory = kwargs.get('cache_directory', '/tmp/coherence-cache')
try:
if self.proxy_mode != 'redirect':
os.mkdir(self.cache_directory)
except:
pass
self.cache_maxsize = kwargs.get('cache_maxsize', 100000000)
self.buffer_size = kwargs.get('buffer_size', 750000)
rootItem = Container(None, self.name)
self.set_root_item(rootItem)
categoriesItem = Container(rootItem, "All by Categories")
rootItem.add_child(categoriesItem)
languagesItem = Container(rootItem, "All by Languages")
rootItem.add_child(languagesItem)
self.appendLanguage("Recent Videos", self.language, rootItem, sort='-age', count=15)
self.appendLanguage("Top Rated", self.language, rootItem, sort='rating', count=15)
self.appendLanguage("Most Popular", self.language, rootItem, sort='-popular', count=15)
def gotError(error):
print "ERROR: %s" % error
def gotCategories(result):
if result is None:
print "Unable to retrieve list of categories"
return
data,header = result
categories = eval(data) # FIXME add some checks to avoid code injection
for category in categories:
name = category['name'].encode('ascii', 'strict')
category_url = category['url'].encode('ascii', 'strict')
self.appendCategory(name, name, categoriesItem)
categories_url = "https://www.miroguide.com/api/list_categories"
d1 = utils.getPage(categories_url)
d1.addCallbacks(gotCategories, gotError)
def gotLanguages(result):
if result is None:
print "Unable to retrieve list of languages"
return
data,header = result
languages = eval(data) # FIXME add some checks to avoid code injection
for language in languages:
name = language['name'].encode('ascii', 'strict')
language_url = language['url'].encode('ascii', 'strict')
self.appendLanguage(name, name, languagesItem)
languages_url = "https://www.miroguide.com/api/list_languages"
d2 = utils.getPage(languages_url)
d2.addCallbacks(gotLanguages, gotError)
self.init_completed()
def __repr__(self):
return self.__class__.__name__
def appendCategory( self, name, category_id, parent):
item = LazyContainer(parent, name, category_id, self.refresh, self.retrieveChannels, filter="category", filter_value=category_id, per_page=100)
parent.add_child(item, external_id=category_id)
def appendLanguage( self, name, language_id, parent, sort='name', count=0):
item = LazyContainer(parent, name, language_id, self.refresh, self.retrieveChannels, filter="language", filter_value=language_id, per_page=100, sort=sort, count=count)
parent.add_child(item, external_id=language_id)
def appendChannel(self, name, channel_id, parent):
item = LazyContainer(parent, name, channel_id, self.refresh, self.retrieveChannelItems, channel_id=channel_id)
parent.add_child(item, external_id=channel_id)
def upnp_init(self):
self.current_connection_id = None
if self.server:
self.server.connection_manager_server.set_variable(
0, 'SourceProtocolInfo',
['http-get:*:%s:*' % 'video/'], #FIXME put list of all possible video mimetypes
default=True)
self.wmc_mapping = {'15': self.get_root_id()}
def retrieveChannels (self, parent, filter, filter_value, per_page=100, page=0, offset=0, count=0, sort='name'):
filter_value = urllib.quote(filter_value.encode("utf-8"))
limit = count
if (count == 0):
limit = per_page
uri = "https://www.miroguide.com/api/get_channels?limit=%d&offset=%d&filter=%s&filter_value=%s&sort=%s" % (limit, offset, filter, filter_value, sort)
#print uri
d = utils.getPage(uri)
def gotChannels(result):
if result is None:
print "Unable to retrieve channel for category %s" % category_id
return
data,header = result
channels = eval(data)
for channel in channels:
publisher = channel['publisher']
description = channel['description']
url = channel['url']
hi_def = channel['hi_def']
thumbnail_url = channel['thumbnail_url']
postal_code = channel['postal_code']
id = channel['id']
website_url = channel['website_url']
name = channel['name']
self.appendChannel(name, id, parent)
if ((count == 0) and (len(channels) >= per_page)):
#print "reached page limit (%d)" % len(channels)
parent.childrenRetrievingNeeded = True
def gotError(error):
print "ERROR: %s" % error
d.addCallbacks(gotChannels, gotError)
return d
def retrieveChannelItems (self, parent, channel_id):
uri = "https://www.miroguide.com/api/get_channel?id=%s" % channel_id
d = utils.getPage(uri)
def gotItems(result):
if result is None:
print "Unable to retrieve items for channel %s" % channel_id
return
data,header = result
channel = eval(data)
items = []
if (channel.has_key('item')):
items = channel['item']
for item in items:
#print "item:",item
url = item['url']
description = item['description']
#print "description:", description
name = item['name']
thumbnail_url = None
if (channel.has_key('thumbnail_url')):
#print "Thumbnail:", channel['thumbnail_url']
thumbnail_url = channel['thumbnail_url']
#size = size['size']
item = VideoItem(name, description, url, thumbnail_url, self)
item.parent = parent
parent.add_child(item, external_id=url)
def gotError(error):
print "ERROR: %s" % error
d.addCallbacks(gotItems, gotError)
return d
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~devices~media_server.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006,2007 Frank Scholz <[email protected]>
import os
import re
import traceback
from StringIO import StringIO
import urllib
from twisted.internet import defer
from twisted.web import static
from twisted.web import resource
#from twisted.web import proxy
from twisted.python import util
from coherence.extern.et import ET
from coherence import __version__
from coherence.upnp.core import utils
from coherence.upnp.core.utils import StaticFile
from coherence.upnp.core.utils import ReverseProxyResource
from coherence.upnp.devices.basics import RootDeviceXML
from coherence.upnp.services.servers.connection_manager_server import ConnectionManagerServer
from coherence.upnp.services.servers.content_directory_server import ContentDirectoryServer
from coherence.upnp.services.servers.scheduled_recording_server import ScheduledRecordingServer
from coherence.upnp.services.servers.media_receiver_registrar_server import MediaReceiverRegistrarServer
from coherence.upnp.services.servers.media_receiver_registrar_server import FakeMediaReceiverRegistrarBackend
from coherence.upnp.devices.basics import BasicDeviceMixin
from coherence import log
COVER_REQUEST_INDICATOR = re.compile(".*?cover\.[A-Z|a-z]{3,4}$")
ATTACHMENT_REQUEST_INDICATOR = re.compile(".*?attachment=.*$")
TRANSCODED_REQUEST_INDICATOR = re.compile(".*/transcoded/.*$")
class MSRoot(resource.Resource, log.Loggable):
logCategory = 'mediaserver'
def __init__(self, server, store):
resource.Resource.__init__(self)
log.Loggable.__init__(self)
self.server = server
self.store = store
#def delayed_response(self, resrc, request):
# print "delayed_response", resrc, request
# body = resrc.render(request)
# print "delayed_response", body
# if body == 1:
# print "delayed_response not yet done"
# return
# request.setHeader("Content-length", str(len(body)))
# request.write(response)
# request.finish()
def getChildWithDefault(self, path, request):
self.info('%s getChildWithDefault, %s, %s, %s %s' % (self.server.device_type,
request.method, path, request.uri, request.client))
headers = request.getAllHeaders()
self.msg( request.getAllHeaders())
try:
if headers['getcontentfeatures.dlna.org'] != '1':
request.setResponseCode(400)
return static.Data('<html><p>wrong value for getcontentFeatures.dlna.org</p></html>','text/html')
except:
pass
if request.method == 'HEAD':
if 'getcaptioninfo.sec' in headers:
self.warning("requesting srt file for id %s" % path)
ch = self.store.get_by_id(path)
try:
location = ch.get_path()
caption = ch.caption
if caption == None:
raise KeyError
request.setResponseCode(200)
request.setHeader('CaptionInfo.sec', caption)
return static.Data('','text/html')
except:
print traceback.format_exc()
request.setResponseCode(404)
return static.Data('<html><p>the requested srt file was not found</p></html>','text/html')
try:
request._dlna_transfermode = headers['transfermode.dlna.org']
except KeyError:
request._dlna_transfermode = 'Streaming'
if request.method in ('GET','HEAD'):
if COVER_REQUEST_INDICATOR.match(request.uri):
self.info("request cover for id %s" % path)
def got_item(ch):
if ch is not None:
request.setResponseCode(200)
file = ch.get_cover()
if os.path.exists(file):
self.info("got cover %s" % file)
return StaticFile(file)
request.setResponseCode(404)
return static.Data('<html><p>cover requested not found</p></html>','text/html')
dfr = defer.maybeDeferred(self.store.get_by_id, path)
dfr.addCallback(got_item)
dfr.isLeaf = True
return dfr
if ATTACHMENT_REQUEST_INDICATOR.match(request.uri):
self.info("request attachment %r for id %s" % (request.args,path))
def got_attachment(ch):
try:
#FIXME same as below
if 'transcoded' in request.args:
if self.server.coherence.config.get('transcoding', 'no') == 'yes':
format = request.args['transcoded'][0]
type = request.args['type'][0]
self.info("request transcoding %r %r" % (format, type))
try:
from coherence.transcoder import TranscoderManager
manager = TranscoderManager(self.server.coherence)
return manager.select(format,ch.item.attachments[request.args['attachment'][0]])
except:
self.debug(traceback.format_exc())
request.setResponseCode(404)
return static.Data('<html><p>the requested transcoded file was not found</p></html>','text/html')
else:
request.setResponseCode(404)
return static.Data("<html><p>This MediaServer doesn't support transcoding</p></html>",'text/html')
else:
return ch.item.attachments[request.args['attachment'][0]]
except:
request.setResponseCode(404)
return static.Data('<html><p>the requested attachment was not found</p></html>','text/html')
dfr = defer.maybeDeferred(self.store.get_by_id, path)
dfr.addCallback(got_attachment)
dfr.isLeaf = True
return dfr
#if(request.method in ('GET','HEAD') and
# XBOX_TRANSCODED_REQUEST_INDICATOR.match(request.uri)):
# if self.server.coherence.config.get('transcoding', 'no') == 'yes':
# id = path[:-15].split('/')[-1]
# self.info("request transcoding to %r for id %s" % (request.args,id))
# ch = self.store.get_by_id(id)
# uri = ch.get_path()
# return MP3Transcoder(uri)
if(request.method in ('GET','HEAD') and
TRANSCODED_REQUEST_INDICATOR.match(request.uri)):
self.info("request transcoding to %s for id %s" % (request.uri.split('/')[-1],path))
if self.server.coherence.config.get('transcoding', 'no') == 'yes':
def got_stuff_to_transcode(ch):
#FIXME create a generic transcoder class and sort the details there
format = request.uri.split('/')[-1] #request.args['transcoded'][0]
uri = ch.get_path()
try:
from coherence.transcoder import TranscoderManager
manager = TranscoderManager(self.server.coherence)
return manager.select(format,uri)
except:
self.debug(traceback.format_exc())
request.setResponseCode(404)
return static.Data('<html><p>the requested transcoded file was not found</p></html>','text/html')
dfr = defer.maybeDeferred(self.store.get_by_id, path)
dfr.addCallback(got_stuff_to_transcode)
dfr.isLeaf = True
return dfr
request.setResponseCode(404)
return static.Data("<html><p>This MediaServer doesn't support transcoding</p></html>",'text/html')
if(request.method == 'POST' and
request.uri.endswith('?import')):
d = self.import_file(path,request)
if isinstance(d, defer.Deferred):
d.addBoth(self.import_response,path)
d.isLeaf = True
return d
return self.import_response(None,path)
if path in ['description-1.xml','description-2.xml']:
ua = headers.get('user-agent', '')
if ua.find('Xbox/') == 0 or ua.startswith("""Mozilla/4.0 (compatible; UPnP/1.0; Windows"""):
self.info('XBox/WMP alert, we need to simulate a Windows Media Connect server')
if self.children.has_key('xbox-description-1.xml'):
self.msg( 'returning xbox-description-1.xml')
return self.children['xbox-description-1.xml']
elif ua.find('SEC_HHP_BD') == 0:
pass
elif ua.find('SEC_HHP_') >= 0:
pass
#return self.children['sec-%s' %path]
# resource http://XXXX/<deviceID>/config
# configuration for the given device
# accepted methods:
# GET, HEAD: returns the configuration data (in XML format)
# POST: stop the current device and restart it with the posted configuration data
if path in ('config'):
backend = self.server.backend
backend_type = backend.__class__.__name__
def constructConfigData(backend):
msg = "<plugin active=\"yes\">"
msg += "<backend>" + backend_type + "</backend>"
for key, value in backend.config.items():
msg += "<" + key + ">" + value + "</" + key + ">"
msg += "</plugin>"
return msg
if request.method in ('GET', 'HEAD'):
# the client wants to retrieve the configuration parameters for the backend
msg = constructConfigData(backend)
request.setResponseCode(200)
return static.Data(msg,'text/xml')
elif request.method in ('POST'):
# the client wants to update the configuration parameters for the backend
# we relaunch the backend with the new configuration (after content validation)
def convert_elementtree_to_dict (root):
active = False
for name, value in root.items():
if name == 'active':
if value in ('yes'):
active = True
break
if active is False:
return None
dict = {}
for element in root.getchildren():
key = element.tag
text = element.text
if (key not in ('backend')):
dict[key] = text
return dict
new_config = None
try:
element_tree = utils.parse_xml(request.content.getvalue(), encoding='utf-8')
new_config = convert_elementtree_to_dict(element_tree.getroot())
self.server.coherence.remove_plugin(self.server)
self.warning("%s %s (%s) with id %s desactivated" % (backend.name, self.server.device_type, backend, str(self.server.uuid)[5:]))
if new_config is None :
msg = "<plugin active=\"no\"/>"
else:
new_backend = self.server.coherence.add_plugin(backend_type, **new_config)
if (self.server.coherence.writeable_config()):
self.server.coherence.store_plugin_config(new_backend.uuid, new_config)
msg = "<html><p>Device restarted. Config file has been modified with posted data.</p></html>" #constructConfigData(new_backend)
else:
msg = "<html><p>Device restarted. Config file not modified</p></html>" #constructConfigData(new_backend)
request.setResponseCode(202)
return static.Data(msg,'text/html')#'text/xml')
except SyntaxError, e:
request.setResponseCode(400)
return static.Data("<html><p>Invalid data posted:<BR>%s</p></html>" % e,'text/html')
else:
# invalid method requested
request.setResponseCode(405)
return static.Data("<html><p>This resource does not allow the requested HTTP method</p></html>",'text/html')
if self.children.has_key(path):
return self.children[path]
if request.uri == '/':
return self
return self.getChild(path, request)
def requestFinished(self, result, id, request):
self.info("finished, remove %d from connection table" % id)
self.info("finished, sentLength: %d chunked: %d code: %d" % (request.sentLength, request.chunked, request.code))
self.info("finished %r" % request.headers)
self.server.connection_manager_server.remove_connection(id)
def import_file(self,name,request):
self.info("import file, id %s" % name)
print "import file, id %s" % name
def got_file(ch):
print "ch", ch
if ch is not None:
if hasattr(self.store,'backend_import'):
response_code = self.store.backend_import(ch,request.content)
if isinstance(response_code, defer.Deferred):
return response_code
request.setResponseCode(response_code)
return
else:
request.setResponseCode(404)
dfr = defer.maybeDeferred(self.store.get_by_id, name)
dfr.addCallback(got_file)
def prepare_connection(self,request):
new_id,_,_ = self.server.connection_manager_server.add_connection('',
'Output',
-1,
'')
self.info("startup, add %d to connection table" % new_id)
d = request.notifyFinish()
d.addBoth(self.requestFinished, new_id, request)
def prepare_headers(self,ch,request):
request.setHeader('transferMode.dlna.org', request._dlna_transfermode)
if hasattr(ch,'item') and hasattr(ch.item, 'res'):
if ch.item.res[0].protocolInfo is not None:
additional_info = ch.item.res[0].get_additional_info()
if additional_info != '*':
request.setHeader('contentFeatures.dlna.org', additional_info)
elif 'getcontentfeatures.dlna.org' in request.getAllHeaders():
request.setHeader('contentFeatures.dlna.org', "DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01500000000000000000000000000000")
def process_child(self,ch,name,request):
if ch != None:
self.info('Child found', ch)
if(request.method == 'GET' or
request.method == 'HEAD'):
headers = request.getAllHeaders()
if headers.has_key('content-length'):
self.warning('%s request with content-length %s header - sanitizing' % (
request.method,
headers['content-length']))
del request.responseHeaders['content-length']
self.debug('data', )
if len(request.content.getvalue()) > 0:
""" shall we remove that?
can we remove that?
"""
self.warning('%s request with %d bytes of message-body - sanitizing' % (
request.method,
len(request.content.getvalue())))
request.content = StringIO()
if hasattr(ch, "location"):
self.debug("we have a location %s" % isinstance(ch.location, resource.Resource))
if(isinstance(ch.location, ReverseProxyResource) or
isinstance(ch.location, resource.Resource)):
#self.info('getChild proxy %s to %s' % (name, ch.location.uri))
self.prepare_connection(request)
self.prepare_headers(ch,request)
return ch.location
try:
p = ch.get_path()
except TypeError:
return self.list_content(name, ch, request)
except Exception, msg:
self.debug("error accessing items path %r" % msg)
self.debug(traceback.format_exc())
return self.list_content(name, ch, request)
if p != None and os.path.exists(p):
self.info("accessing path %r" % p)
self.prepare_connection(request)
self.prepare_headers(ch,request)
ch = StaticFile(p)
else:
self.debug("accessing path %r failed" % p)
return self.list_content(name, ch, request)
if ch is None:
p = util.sibpath(__file__, name)
if os.path.exists(p):
ch = StaticFile(p)
self.info('MSRoot ch', ch)
return ch
def getChild(self, name, request):
self.info('getChild %s, %s' % (name, request))
ch = self.store.get_by_id(name)
if isinstance(ch, defer.Deferred):
ch.addCallback(self.process_child,name,request)
#ch.addCallback(self.delayed_response, request)
return ch
return self.process_child(ch,name,request)
def list_content(self, name, item, request):
self.info('list_content', name, item, request)
page = """<html><head><title>%s</title></head><body><p>%s</p>"""% \
(item.get_name().encode('ascii','xmlcharrefreplace'),
item.get_name().encode('ascii','xmlcharrefreplace'))
if( hasattr(item,'mimetype') and item.mimetype in ['directory','root']):
uri = request.uri
if uri[-1] != '/':
uri += '/'
def build_page(r,page):
#print "build_page", r
page += """<ul>"""
if r is not None:
for c in r:
if hasattr(c,'get_url'):
path = c.get_url()
self.debug('has get_url', path)
elif hasattr(c,'get_path') and c.get_path != None:
#path = c.get_path().encode('utf-8').encode('string_escape')
path = c.get_path()
if isinstance(path,unicode):
path = path.encode('ascii','xmlcharrefreplace')
else:
path = path.decode('utf-8').encode('ascii','xmlcharrefreplace')
self.debug('has get_path', path)
else:
path = request.uri.split('/')
path[-1] = str(c.get_id())
path = '/'.join(path)
self.debug('got path', path)
title = c.get_name()
self.debug( 'title is:', type(title))
try:
if isinstance(title,unicode):
title = title.encode('ascii','xmlcharrefreplace')
else:
title = title.decode('utf-8').encode('ascii','xmlcharrefreplace')
except (UnicodeEncodeError,UnicodeDecodeError):
title = c.get_name().encode('utf-8').encode('string_escape')
page += '<li><a href="%s">%s</a></li>' % \
(path, title)
page += """</ul>"""
page += """</body></html>"""
return static.Data(page,'text/html')
children = item.get_children()
if isinstance(children, defer.Deferred):
print "list_content, we have a Deferred", children
children.addCallback(build_page,page)
#children.addErrback(....) #FIXME
return children
return build_page(children,page)
elif( hasattr(item,'mimetype') and item.mimetype.find('image/') == 0):
#path = item.get_path().encode('utf-8').encode('string_escape')
path = urllib.quote(item.get_path().encode('utf-8'))
title = item.get_name().decode('utf-8').encode('ascii','xmlcharrefreplace')
page += """<p><img src="%s" alt="%s"></p>""" % \
(path, title)
else:
pass
page += """</body></html>"""
return static.Data(page,'text/html')
def listchilds(self, uri):
self.info('listchilds %s' % uri)
if uri[-1] != '/':
uri += '/'
cl = '<p><a href=%s0>content</a></p>' % uri
cl += '<li><a href=%sconfig>config</a></li>' % uri
for c in self.children:
cl += '<li><a href=%s%s>%s</a></li>' % (uri,c,c)
return cl
def import_response(self,result,id):
return static.Data('<html><p>import of %s finished</p></html>'% id,'text/html')
def render(self,request):
#print "render", request
return '<html><p>root of the %s MediaServer</p><p><ul>%s</ul></p></html>'% \
(self.server.backend,
self.listchilds(request.uri))
class XboxRootDeviceXML(static.Data):
def __init__(self, hostname, uuid, urlbase,
device_type='MediaServer',
version=2,
friendly_name='Coherence UPnP MediaServer',
services=[],
devices=[],
icons=[],
presentation_url=None,
manufacturer='beebits.net',
manufacturer_url='http://coherence.beebits.net',
model_description='Coherence UPnP MediaServer',
model_number=__version__,
model_url='http://coherence.beebits.net'):
uuid = str(uuid)
root = ET.Element('root')
root.attrib['xmlns']='urn:schemas-upnp-org:device-1-0'
device_type = 'urn:schemas-upnp-org:device:%s:%d' % (device_type, int(version))
e = ET.SubElement(root, 'specVersion')
ET.SubElement(e, 'major').text = '1'
ET.SubElement(e, 'minor').text = '0'
#if version == 1:
# ET.SubElement(root, 'URLBase').text = urlbase + uuid[5:] + '/'
d = ET.SubElement(root, 'device')
ET.SubElement(d, 'deviceType').text = device_type
ET.SubElement(d, 'friendlyName').text = friendly_name + ' : 1 : Windows Media Connect'
ET.SubElement(d, 'manufacturer').text = manufacturer
ET.SubElement(d, 'manufacturerURL').text = manufacturer_url
ET.SubElement(d, 'modelDescription').text = model_description
ET.SubElement(d, 'modelName').text = 'Windows Media Connect'
ET.SubElement(d, 'modelNumber').text = model_number
ET.SubElement(d, 'modelURL').text = model_url
ET.SubElement(d, 'serialNumber').text = '0000001'
ET.SubElement(d, 'UDN').text = uuid
ET.SubElement(d, 'UPC').text = ''
if len(icons):
e = ET.SubElement(d, 'iconList')
for icon in icons:
icon_path = ''
if icon.has_key('url'):
if icon['url'].startswith('file://'):
icon_path = icon['url'][7:]
elif icon['url'] == '.face':
icon_path = os.path.join(os.path.expanduser('~'), ".face")
else:
from pkg_resources import resource_filename
icon_path = os.path.abspath(resource_filename(__name__, os.path.join('..','..','..','misc','device-icons',icon['url'])))
if os.path.exists(icon_path) == True:
i = ET.SubElement(e, 'icon')
for k,v in icon.items():
if k == 'url':
if v.startswith('file://'):
ET.SubElement(i, k).text = '/'+uuid[5:]+'/'+os.path.basename(v)
continue
elif v == '.face':
ET.SubElement(i, k).text = '/'+uuid[5:]+'/'+'face-icon.png'
continue
else:
ET.SubElement(i, k).text = '/'+uuid[5:]+'/'+os.path.basename(v)
continue
ET.SubElement(i, k).text = str(v)
if len(services):
e = ET.SubElement(d, 'serviceList')
for service in services:
id = service.get_id()
s = ET.SubElement(e, 'service')
try:
namespace = service.namespace
except:
namespace = 'schemas-upnp-org'
if( hasattr(service,'version') and
service.version < version):
v = service.version
else:
v = version
ET.SubElement(s, 'serviceType').text = 'urn:%s:service:%s:%d' % (namespace, id, int(v))
try:
namespace = service.id_namespace
except:
namespace = 'upnp-org'
ET.SubElement(s, 'serviceId').text = 'urn:%s:serviceId:%s' % (namespace,id)
ET.SubElement(s, 'SCPDURL').text = '/' + uuid[5:] + '/' + id + '/' + service.scpd_url
ET.SubElement(s, 'controlURL').text = '/' + uuid[5:] + '/' + id + '/' + service.control_url
ET.SubElement(s, 'eventSubURL').text = '/' + uuid[5:] + '/' + id + '/' + service.subscription_url
#ET.SubElement(s, 'SCPDURL').text = id + '/' + service.scpd_url
#ET.SubElement(s, 'controlURL').text = id + '/' + service.control_url
#ET.SubElement(s, 'eventSubURL').text = id + '/' + service.subscription_url
if len(devices):
e = ET.SubElement(d, 'deviceList')
if presentation_url is None:
presentation_url = '/' + uuid[5:]
ET.SubElement(d, 'presentationURL').text = presentation_url
x = ET.SubElement(d, 'dlna:X_DLNADOC')
x.attrib['xmlns:dlna']='urn:schemas-dlna-org:device-1-0'
x.text = 'DMS-1.50'
x = ET.SubElement(d, 'dlna:X_DLNADOC')
x.attrib['xmlns:dlna']='urn:schemas-dlna-org:device-1-0'
x.text = 'M-DMS-1.50'
x=ET.SubElement(d, 'dlna:X_DLNACAP')
x.attrib['xmlns:dlna']='urn:schemas-dlna-org:device-1-0'
x.text = 'av-upload,image-upload,audio-upload'
#if self.has_level(LOG_DEBUG):
# indent( root)
self.xml = """<?xml version="1.0" encoding="utf-8"?>""" + ET.tostring( root, encoding='utf-8')
static.Data.__init__(self, self.xml, 'text/xml')
class MediaServer(log.Loggable,BasicDeviceMixin):
logCategory = 'mediaserver'
device_type = 'MediaServer'
presentationURL = None
def fire(self,backend,**kwargs):
if kwargs.get('no_thread_needed',False) == False:
""" this could take some time, put it in a thread to be sure it doesn't block
as we can't tell for sure that every backend is implemented properly """
from twisted.internet import threads
d = threads.deferToThread(backend, self, **kwargs)
def backend_ready(backend):
self.backend = backend
def backend_failure(x):
self.warning('backend %s not installed, MediaServer activation aborted - %s', backend, x.getErrorMessage())
self.debug(x)
d.addCallback(backend_ready)
d.addErrback(backend_failure)
# FIXME: we need a timeout here so if the signal we wait for not arrives we'll
# can close down this device
else:
self.backend = backend(self, **kwargs)
def init_complete(self, backend):
if self.backend != backend:
return
self._services = []
self._devices = []
try:
self.connection_manager_server = ConnectionManagerServer(self)
self._services.append(self.connection_manager_server)
except LookupError,msg:
self.warning( 'ConnectionManagerServer', msg)
raise LookupError(msg)
try:
transcoding = False
if self.coherence.config.get('transcoding', 'no') == 'yes':
transcoding = True
self.content_directory_server = ContentDirectoryServer(self,transcoding=transcoding)
self._services.append(self.content_directory_server)
except LookupError,msg:
self.warning( 'ContentDirectoryServer', msg)
raise LookupError(msg)
try:
self.media_receiver_registrar_server = MediaReceiverRegistrarServer(self,
backend=FakeMediaReceiverRegistrarBackend())
self._services.append(self.media_receiver_registrar_server)
except LookupError,msg:
self.warning( 'MediaReceiverRegistrarServer (optional)', msg)
try:
self.scheduled_recording_server = ScheduledRecordingServer(self)
self._services.append(self.scheduled_recording_server)
except LookupError,msg:
self.info( 'ScheduledRecordingServer', msg)
upnp_init = getattr(self.backend, "upnp_init", None)
if upnp_init:
upnp_init()
self.web_resource = MSRoot( self, backend)
self.coherence.add_web_resource( str(self.uuid)[5:], self.web_resource)
version = int(self.version)
while version > 0:
self.web_resource.putChild( 'description-%d.xml' % version,
RootDeviceXML( self.coherence.hostname,
str(self.uuid),
self.coherence.urlbase,
device_type=self.device_type,
version=version,
friendly_name=self.backend.name,
services=self._services,
devices=self._devices,
icons=self.icons,
presentation_url = self.presentationURL,
manufacturer=self.manufacturer,
manufacturer_url=self.manufacturer_url,
model_description=self.model_description,
model_name=self.model_name,
model_number=self.model_number,
model_url=self.model_url,
dlna_caps = ['av-upload,image-upload,audio-upload']
))
self.web_resource.putChild( 'sec-description-%d.xml' % version,
RootDeviceXML( self.coherence.hostname,
str(self.uuid),
self.coherence.urlbase,
device_type=self.device_type,
version=version,
friendly_name=self.backend.name,
services=self._services,
devices=self._devices,
icons=self.icons,
presentation_url = self.presentationURL,
manufacturer=self.manufacturer,
manufacturer_url=self.manufacturer_url,
model_description=self.model_description,
model_name=self.model_name,
model_number=self.model_number,
model_url=self.model_url,
dlna_caps = ['av-upload,image-upload,audio-upload'],
sec_dmc10 = True
))
self.web_resource.putChild( 'xbox-description-%d.xml' % version,
XboxRootDeviceXML( self.coherence.hostname,
str(self.uuid),
self.coherence.urlbase,
self.device_type, version,
friendly_name=self.backend.name,
services=self._services,
devices=self._devices,
icons=self.icons,
presentation_url = self.presentationURL,
manufacturer=self.manufacturer,
manufacturer_url=self.manufacturer_url,
model_description=self.model_description,
model_number=self.model_number,
model_url=self.model_url))
version -= 1
self.web_resource.putChild('ConnectionManager', self.connection_manager_server)
self.web_resource.putChild('ContentDirectory', self.content_directory_server)
if hasattr(self,"scheduled_recording_server"):
self.web_resource.putChild('ScheduledRecording', self.scheduled_recording_server)
if hasattr(self,"media_receiver_registrar_server"):
self.web_resource.putChild('X_MS_MediaReceiverRegistrar', self.media_receiver_registrar_server)
for icon in self.icons:
if icon.has_key('url'):
if icon['url'].startswith('file://'):
if os.path.exists(icon['url'][7:]):
self.web_resource.putChild(os.path.basename(icon['url']),
StaticFile(icon['url'][7:],defaultType=icon['mimetype']))
elif icon['url'] == '.face':
face_path = os.path.abspath(os.path.join(os.path.expanduser('~'), ".face"))
if os.path.exists(face_path):
self.web_resource.putChild('face-icon.png',StaticFile(face_path,defaultType=icon['mimetype']))
else:
from pkg_resources import resource_filename
icon_path = os.path.abspath(resource_filename(__name__, os.path.join('..','..','..','misc','device-icons',icon['url'])))
if os.path.exists(icon_path):
self.web_resource.putChild(icon['url'],StaticFile(icon_path,defaultType=icon['mimetype']))
self.register()
self.warning("%s %s (%s) activated with id %s" % (self.device_type, self.backend.name, self.backend, str(self.uuid)[5:]))
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~audiocd_storage.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# <EXPERIMENTAL>
# a backend to expose to the local network the content of an audio CD
# inserted in a local drive
# the CD data is extracted from the CDDB/FreeDB database
# Warning: this backend does not detect insertion and ejection of CD drive
# the CD must be inserted before activating the backing.
# The backend must be disabled before ejecting the audio CD.
# Dependencies
# CDDB.py and DiscID.py (ex: debian package python-cddb)
# python-gst (with base and ugly plugins)
# TODO: switch from CDDB/FreeDB to musicBrainz
# TODO: find source for AlbumArt UI
# TODO: support other character encoding environment than ISO-8856-1
# Copyright 2010, Jean-Michel Sizun
import CDDB, DiscID
from twisted.internet import reactor,threads
from coherence.upnp.core import DIDLLite
from coherence import log
from coherence.transcoder import GStreamerPipeline
from coherence.backend import AbstractBackendStore, Container, BackendItem
PLAY_TRACK_GST_PIPELINE = "cdiocddasrc device=%s track=%d ! wavenc name=enc"
TRACK_MIMETYPE = "audio/x-wav"
TRACK_FOURTH_FIELD = "*"
class TrackItem(BackendItem):
logCategory = "audiocd"
def __init__(self,device_name="/dev/cdrom", track_number=1, artist="Unknown", title="Unknown"):
self.device_name = device_name
self.track_number = track_number
self.artist = artist
self.title = title
self.mimetype = TRACK_MIMETYPE
self.fourth_field = TRACK_FOURTH_FIELD
self.item = None
self.pipeline = PLAY_TRACK_GST_PIPELINE % (self.device_name, self.track_number)
self.location = GStreamerPipeline(self.pipeline,self.mimetype)
def get_item(self):
if self.item == None:
upnp_id = self.storage_id
upnp_parent_id = self.parent.get_id()
url = self.store.urlbase + str(self.storage_id)
self.item = DIDLLite.MusicTrack(upnp_id, upnp_parent_id, self.title)
res = DIDLLite.Resource(url, 'http-get:*:%s:%s' % (self.mimetype,self.fourth_field))
#res.duration = self.duration
#res.size = self.get_size()
self.item.res.append(res)
return self.item
def get_name(self):
return self.title
def get_path(self):
return self.location
def get_size(self):
return self.size
def get_id (self):
return self.storage_id
class AudioCDStore(AbstractBackendStore):
logCategory = 'audiocd'
implements = ['MediaServer']
description = ('audioCD', '', None)
options = [{'option':'version','text':'UPnP Version:','type':'int','default':2,'enum': (2,1),'help': 'the highest UPnP version this MediaServer shall support','level':'advance'},
{'option':'uuid','text':'UUID Identifier:','type':'string','help':'the unique (UPnP) identifier for this MediaServer, usually automatically set','level':'advance'},
{'option':'device_name','text':'device name for audio CD:','type':'string', 'help':'device name containing the audio cd.'}
]
disc_title = None
cdrom = None
def __init__(self, server, **kwargs):
AbstractBackendStore.__init__(self, server, **kwargs)
self.name = 'audio CD'
self.device_name= kwargs.get('device_name',"/dev/cdom");
threads.deferToThread(self.extractAudioCdInfo)
# self.init_completed() # will be fired when the audio CD info is extracted
def upnp_init(self):
self.current_connection_id = None
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
['http-get:*:%s:%s' % (TRACK_MIMETYPE, TRACK_FOURTH_FIELD)],
default=True)
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
#self.server.content_directory_server.set_variable(0, 'SortCapabilities', '*')
def extractAudioCdInfo (self):
""" extract the CD info (album art + artist + tracks), and construct the UPnP items"""
self.cdrom = DiscID.open(self.device_name)
disc_id = DiscID.disc_id(self.cdrom)
(query_status, query_info) = CDDB.query(disc_id)
if query_status in (210, 211):
query_info = query_info[0]
(read_status, read_info) = CDDB.read(query_info['category'], query_info['disc_id'])
# print query_info['title']
# print disc_id[1]
# for i in range(disc_id[1]):
# print "Track %.02d: %s" % (i, read_info['TTITLE' + `i`])
track_count = disc_id[1]
disc_id = query_info['disc_id']
self.disc_title = query_info['title'].encode('utf-8')
tracks = {}
for i in range(track_count):
tracks[i+1] = read_info['TTITLE' + `i`].decode('ISO-8859-1').encode('utf-8')
self.name = self.disc_title
root_item = Container(None, self.disc_title)
# we will sort the item by "track_number"
def childs_sort(x,y):
return cmp(x.track_number, y.track_number)
root_item.sorting_method = childs_sort
self.set_root_item(root_item)
for number, title in tracks.items():
item = TrackItem(self.device_name, number, "Unknown", title)
external_id = "%s_%d" % (disc_id, number)
root_item.add_child(item, external_id = external_id)
self.info('Sharing audio CD %s' % self.disc_title)
reactor.callLater(2,self.checkIfAudioCdStillPresent)
self.init_completed()
def checkIfAudioCdStillPresent(self):
try:
disc_id = DiscID.disc_id(self.cdrom)
reactor.callLater(2,self.checkIfAudioCdStillPresent)
except:
self.warning('audio CD %s ejected: closing UPnP server!' % self.disc_title)
self.server.coherence.remove_plugin(self.server)
def __repr__(self):
return self.__class__.__name__
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~core~soap_lite.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007 - Frank Scholz <[email protected]>
""" SOAP-lite
some simple functions to implement the SOAP msgs
needed by UPnP with ElementTree
inspired by ElementSOAP.py
"""
from twisted.python.util import OrderedDict
from coherence.extern.et import ET
NS_SOAP_ENV = "{http://schemas.xmlsoap.org/soap/envelope/}"
NS_SOAP_ENC = "{http://schemas.xmlsoap.org/soap/encoding/}"
NS_XSI = "{http://www.w3.org/1999/XMLSchema-instance}"
NS_XSD = "{http://www.w3.org/1999/XMLSchema}"
SOAP_ENCODING = "http://schemas.xmlsoap.org/soap/encoding/"
UPNPERRORS = {401:'Invalid Action',
402:'Invalid Args',
501:'Action Failed',
600:'Argument Value Invalid',
601:'Argument Value Out of Range',
602:'Optional Action Not Implemented',
603:'Out Of Memory',
604:'Human Intervention Required',
605:'String Argument Too Long',
606:'Action Not Authorized',
607:'Signature Failure',
608:'Signature Missing',
609:'Not Encrypted',
610:'Invalid Sequence',
611:'Invalid Control URL',
612:'No Such Session',}
def build_soap_error(status,description='without words'):
""" builds an UPnP SOAP error msg
"""
root = ET.Element('s:Fault')
ET.SubElement(root,'faultcode').text='s:Client'
ET.SubElement(root,'faultstring').text='UPnPError'
e = ET.SubElement(root,'detail')
e = ET.SubElement(e, 'UPnPError')
e.attrib['xmlns']='urn:schemas-upnp-org:control-1-0'
ET.SubElement(e,'errorCode').text=str(status)
ET.SubElement(e,'errorDescription').text=UPNPERRORS.get(status,description)
return build_soap_call(None, root, encoding=None)
def build_soap_call(method, arguments, is_response=False,
encoding=SOAP_ENCODING,
envelope_attrib=None,
typed=None):
""" create a shell for a SOAP request or response element
- set method to none to omitt the method element and
add the arguments directly to the body (for an error msg)
- arguments can be a dict or an ET.Element
"""
envelope = ET.Element("s:Envelope")
if envelope_attrib:
for n in envelope_attrib:
envelope.attrib.update({n[0] : n[1]})
else:
envelope.attrib.update({'s:encodingStyle' : "http://schemas.xmlsoap.org/soap/encoding/"})
envelope.attrib.update({'xmlns:s' :"http://schemas.xmlsoap.org/soap/envelope/"})
body = ET.SubElement(envelope, "s:Body")
if method:
# append the method call
if is_response is True:
method += "Response"
ns,method = method.split("}")
method = "u:%s" %method
ns = ns[1:]
re = ET.SubElement(body,method)
re.attrib.update({'xmlns:u' : ns})
if encoding:
re.set(NS_SOAP_ENV + "encodingStyle", encoding)
else:
re = body
# append the arguments
if isinstance(arguments,(dict,OrderedDict)) :
type_map = {str: 'xsd:string',
unicode: 'xsd:string',
int: 'xsd:int',
float: 'xsd:float',
bool: 'xsd:boolean'}
for arg_name, arg_val in arguments.iteritems():
arg_type = type_map[type(arg_val)]
if arg_type == 'xsd:string' and type(arg_val) == unicode:
arg_val = arg_val.encode('utf-8')
if arg_type == 'xsd:int' or arg_type == 'xsd:float':
arg_val = str(arg_val)
if arg_type == 'xsd:boolean':
if arg_val == True:
arg_val = '1'
else:
arg_val = '0'
e = ET.SubElement(re, arg_name)
if typed and arg_type:
if not isinstance(type, ET.QName):
arg_type = ET.QName("http://www.w3.org/1999/XMLSchema", arg_type)
e.set(NS_XSI + "type", arg_type)
e.text = arg_val
else:
if arguments == None:
arguments = {}
re.append(arguments)
preamble = """<?xml version="1.0" encoding="utf-8"?>"""
return preamble + ET.tostring(envelope,'utf-8')
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~devices~media_renderer.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006,2007 Frank Scholz <[email protected]>
import os.path
from twisted.internet import task
from twisted.internet import reactor
from twisted.web import resource, static
from coherence import __version__
from coherence.extern.et import ET, indent
from coherence.upnp.core.utils import StaticFile
from coherence.upnp.services.servers.connection_manager_server import ConnectionManagerServer
from coherence.upnp.services.servers.rendering_control_server import RenderingControlServer
from coherence.upnp.services.servers.av_transport_server import AVTransportServer
from coherence.upnp.devices.basics import RootDeviceXML, DeviceHttpRoot, BasicDeviceMixin
from coherence import log
class HttpRoot(DeviceHttpRoot):
logCategory = 'mediarenderer'
class MediaRenderer(log.Loggable,BasicDeviceMixin):
logCategory = 'mediarenderer'
device_type = 'MediaRenderer'
def fire(self,backend,**kwargs):
if kwargs.get('no_thread_needed',False) == False:
""" this could take some time, put it in a thread to be sure it doesn't block
as we can't tell for sure that every backend is implemented properly """
from twisted.internet import threads
d = threads.deferToThread(backend, self, **kwargs)
def backend_ready(backend):
self.backend = backend
def backend_failure(x):
self.warning('backend %s not installed, %s activation aborted - %s' % (backend, self.device_type, x.getErrorMessage()))
self.debug(x)
d.addCallback(backend_ready)
d.addErrback(backend_failure)
# FIXME: we need a timeout here so if the signal we wait for not arrives we'll
# can close down this device
else:
self.backend = backend(self, **kwargs)
def init_complete(self, backend):
if self.backend != backend:
return
self._services = []
self._devices = []
try:
self.connection_manager_server = ConnectionManagerServer(self)
self._services.append(self.connection_manager_server)
except LookupError,msg:
self.warning( 'ConnectionManagerServer', msg)
raise LookupError(msg)
try:
self.rendering_control_server = RenderingControlServer(self)
self._services.append(self.rendering_control_server)
except LookupError,msg:
self.warning( 'RenderingControlServer', msg)
raise LookupError(msg)
try:
self.av_transport_server = AVTransportServer(self)
self._services.append(self.av_transport_server)
except LookupError,msg:
self.warning( 'AVTransportServer', msg)
raise LookupError(msg)
upnp_init = getattr(self.backend, "upnp_init", None)
if upnp_init:
upnp_init()
self.web_resource = HttpRoot(self)
self.coherence.add_web_resource( str(self.uuid)[5:], self.web_resource)
try:
dlna_caps = self.backend.dlna_caps
except AttributeError:
dlna_caps = []
version = self.version
while version > 0:
self.web_resource.putChild( 'description-%d.xml' % version,
RootDeviceXML( self.coherence.hostname,
str(self.uuid),
self.coherence.urlbase,
device_type=self.device_type,
version=version,
#presentation_url='/'+str(self.uuid)[5:],
friendly_name=self.backend.name,
services=self._services,
devices=self._devices,
icons=self.icons,
dlna_caps=dlna_caps,
manufacturer=self.manufacturer,
manufacturer_url=self.manufacturer_url,
model_name=self.model_name,
model_description=self.model_description,
model_number=self.model_number,
model_url=self.model_url
))
version -= 1
self.web_resource.putChild('ConnectionManager', self.connection_manager_server)
self.web_resource.putChild('RenderingControl', self.rendering_control_server)
self.web_resource.putChild('AVTransport', self.av_transport_server)
for icon in self.icons:
if icon.has_key('url'):
if icon['url'].startswith('file://'):
if os.path.exists(icon['url'][7:]):
self.web_resource.putChild(os.path.basename(icon['url']),
StaticFile(icon['url'][7:],defaultType=icon['mimetype']))
elif icon['url'] == '.face':
face_path = os.path.abspath(os.path.join(os.path.expanduser('~'), ".face"))
if os.path.exists(face_path):
self.web_resource.putChild('face-icon.png',StaticFile(face_path,defaultType=icon['mimetype']))
else:
from pkg_resources import resource_filename
icon_path = os.path.abspath(resource_filename(__name__, os.path.join('..','..','..','misc','device-icons',icon['url'])))
if os.path.exists(icon_path):
self.web_resource.putChild(icon['url'],StaticFile(icon_path,defaultType=icon['mimetype']))
self.register()
self.warning("%s %s (%s) activated with %s" % (self.backend.name, self.device_type, self.backend, str(self.uuid)[5:]))
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~web~ui.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006, Frank Scholz <[email protected]>
import os
from twisted.internet import reactor
from twisted.python import filepath, util
from nevow import athena, inevow, loaders, tags, static
from twisted.web import server, resource
from zope.interface import implements, Interface
import coherence.extern.louie as louie
from coherence import log
class IWeb(Interface):
def goingLive(self):
pass
class Web(object):
def __init__(self, coherence):
super(Web, self).__init__()
self.coherence = coherence
class MenuFragment(athena.LiveElement, log.Loggable):
logCategory = 'webui_menu_fragment'
jsClass = u'Coherence.Base'
fragmentName = 'coherence-menu'
docFactory = loaders.stan(
tags.div(render=tags.directive('liveElement'))[
tags.div(id="coherence_menu_box",class_="coherence_menu_box")[""],
]
)
def __init__(self, page):
super(MenuFragment, self).__init__()
self.setFragmentParent(page)
self.page = page
self.coherence = page.coherence
self.tabs = []
def going_live(self):
self.info("add a view to the MenuFragment")
d = self.page.notifyOnDisconnect()
d.addCallback( self.remove_me)
d.addErrback( self.remove_me)
if len(self.tabs):
return self.tabs
else:
return {}
athena.expose(going_live)
def add_tab(self,title,active,id):
self.info("add tab %s to the MenuFragment" % title)
new_tab = {u'title':unicode(title),
u'active':unicode(active),
u'athenaid':u'athenaid:%d' % id}
for t in self.tabs:
if t[u'title'] == new_tab[u'title']:
return
self.tabs.append(new_tab)
self.callRemote('addTab', new_tab)
def remove_me(self, result):
self.info("remove view from MenuFragment")
class DevicesFragment(athena.LiveElement, log.Loggable):
logCategory = 'webui_device_fragment'
jsClass = u'Coherence.Devices'
fragmentName = 'coherence-devices'
docFactory = loaders.stan(
tags.div(render=tags.directive('liveElement'))[
tags.div(id="Devices-container",class_="coherence_container")[""],
]
)
def __init__(self, page, active):
super(DevicesFragment, self).__init__()
self.setFragmentParent(page)
self.page = page
self.coherence = page.coherence
self.active = active
def going_live(self):
self.info("add a view to the DevicesFragment", self._athenaID)
self.page.menu.add_tab('Devices', self.active, self._athenaID)
d = self.page.notifyOnDisconnect()
d.addCallback(self.remove_me)
d.addErrback(self.remove_me)
devices = []
for device in self.coherence.get_devices():
if device is not None:
devices.append({u'name': device.get_markup_name(),
u'usn':unicode(device.get_usn())})
louie.connect(self.add_device,
'Coherence.UPnP.Device.detection_completed', louie.Any)
louie.connect(self.remove_device,
'Coherence.UPnP.Device.removed', louie.Any)
return devices
athena.expose(going_live)
def remove_me(self, result):
self.info("remove view from the DevicesFragment")
def add_device(self, device):
self.info("DevicesFragment found device %s %s of type %s" %(
device.get_usn(),
device.get_friendly_name(),
device.get_device_type()))
self.callRemote('addDevice',
{u'name': device.get_markup_name(),
u'usn':unicode(device.get_usn())})
def remove_device(self, usn):
self.info("DevicesFragment remove device %s", usn)
self.callRemote('removeDevice', unicode(usn))
def render_devices(self, ctx, data):
cl = []
self.info('children: %s' % self.coherence.children)
for child in self.coherence.children:
device = self.coherence.get_device_with_id(child)
if device is not None:
cl.append( tags.li[tags.a(href='/' + child)[
device.get_friendly_device_type, ':',
device.get_device_type_version, ' ',
device.get_friendly_name()]])
else:
cl.append( tags.li[child])
return ctx.tag[tags.ul[cl]]
class LoggingFragment(athena.LiveElement, log.Loggable):
logCategory = 'webui_logging_fragment'
jsClass = u'Coherence.Logging'
fragmentName = 'coherence-logging'
docFactory = loaders.stan(
tags.div(render=tags.directive('liveElement'))[
tags.div(id="Logging-container",class_="coherence_container")[""],
]
)
def __init__(self, page, active):
super(LoggingFragment, self).__init__()
self.setFragmentParent(page)
self.page = page
self.coherence = page.coherence
self.active = active
def going_live(self):
self.info("add a view to the LoggingFragment",self._athenaID)
self.page.menu.add_tab('Logging',self.active,self._athenaID)
d = self.page.notifyOnDisconnect()
d.addCallback( self.remove_me)
d.addErrback( self.remove_me)
return {}
athena.expose(going_live)
def remove_me(self, result):
self.info("remove view from the LoggingFragment")
class WebUI(athena.LivePage, log.Loggable):
"""
"""
logCategory = 'webui'
jsClass = u'Coherence'
addSlash = True
docFactory = loaders.xmlstr("""\
<html xmlns:nevow="http://nevow.com/ns/nevow/0.1">
<head>
<nevow:invisible nevow:render="liveglue" />
<link rel="stylesheet" type="text/css" href="static/main.css" />
</head>
<body>
<div id="coherence_header"><div class="coherence_title">Coherence</div><div nevow:render="menu"></div></div>
<div id="coherence_body">
<div nevow:render="devices" />
<div nevow:render="logging" />
</div>
</body>
</html>
""")
def __init__(self, *a, **kw):
super(WebUI, self).__init__( *a, **kw)
self.coherence = self.rootObject.coherence
self.jsModules.mapping.update({
'MochiKit': filepath.FilePath(__file__).parent().child('static').child('MochiKit.js').path})
self.jsModules.mapping.update({
'Coherence': filepath.FilePath(__file__).parent().child('static').child('Coherence.js').path})
self.jsModules.mapping.update({
'Coherence.Base': filepath.FilePath(__file__).parent().child('static').child('Coherence.Base.js').path})
self.jsModules.mapping.update({
'Coherence.Devices': filepath.FilePath(__file__).parent().child('static').child('Coherence.Devices.js').path})
self.jsModules.mapping.update({
'Coherence.Logging': filepath.FilePath(__file__).parent().child('static').child('Coherence.Logging.js').path})
self.menu = MenuFragment(self)
def childFactory(self, ctx, name):
self.info('WebUI childFactory: %s' % name)
try:
return self.rootObject.coherence.children[name]
except:
ch = super(WebUI, self).childFactory(ctx, name)
if ch is None:
p = util.sibpath(__file__, name)
self.info('looking for file',p)
if os.path.exists(p):
ch = static.File(p)
return ch
def render_listmenu(self, ctx, data):
l = []
l.append(tags.div(id="t",class_="coherence_menu_item")[tags.a(href='/'+'devices',class_="coherence_menu_link")['Devices']])
l.append(tags.div(id="t",class_="coherence_menu_item")[tags.a(href='/'+'logging',class_="coherence_menu_link")['Logging']])
return ctx.tag[l]
def render_menu(self, ctx, data):
self.info('render_menu')
return self.menu
def render_devices(self, ctx, data):
self.info('render_devices')
f = DevicesFragment(self,'yes')
return f
def render_logging(self, ctx, data):
self.info('render_logging')
f = LoggingFragment(self,'no')
return f
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~bbc_storage.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008 Frank Scholz <[email protected]>
from coherence.backend import BackendStore
from coherence.backend import BackendItem
from coherence.upnp.core import DIDLLite
from coherence.upnp.core.utils import getPage
from twisted.internet import reactor
from twisted.python.util import OrderedDict
from coherence.extern.et import parse_xml
ROOT_CONTAINER_ID = 0
SERIES_CONTAINER_ID = 100
class BBCItem(BackendItem):
def __init__(self, parent_id, id, title, url):
self.parent_id = parent_id
self.id = id
self.location = url
self.name = title
self.duration = None
self.size = None
self.mimetype = 'audio/mpeg'
self.description = None
self.item = None
def get_item(self):
if self.item == None:
self.item = DIDLLite.AudioItem(self.id, self.parent_id, self.name)
self.item.description = self.description
res = DIDLLite.Resource(self.location, 'http-get:*:%s:*' % self.mimetype)
res.duration = self.duration
res.size = self.size
self.item.res.append(res)
return self.item
class Container(BackendItem):
def __init__(self, id, store, parent_id, title):
self.url = store.urlbase+str(id)
self.parent_id = parent_id
self.id = id
self.name = title
self.mimetype = 'directory'
self.update_id = 0
self.children = []
self.item = DIDLLite.Container(self.id, self.parent_id, self.name)
self.item.childCount = 0
self.sorted = False
def add_child(self, child):
id = child.id
if isinstance(child.id, basestring):
_,id = child.id.split('.')
self.children.append(child)
self.item.childCount += 1
self.sorted = False
def get_children(self, start=0, end=0):
if self.sorted == False:
def childs_sort(x,y):
r = cmp(x.name,y.name)
return r
self.children.sort(cmp=childs_sort)
self.sorted = True
if end != 0:
return self.children[start:end]
return self.children[start:]
def get_child_count(self):
return len(self.children)
def get_path(self):
return self.url
def get_item(self):
return self.item
def get_name(self):
return self.name
def get_id(self):
return self.id
class BBCStore(BackendStore):
implements = ['MediaServer']
rss_url = "http://open.bbc.co.uk/rad/uriplay/availablecontent"
def __init__(self, server, *args, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.name = kwargs.get('name', 'BBC')
self.refresh = int(kwargs.get('refresh', 1)) * (60 *60)
self.next_id = 1000
self.update_id = 0
self.last_updated = None
self.store = {}
d = self.update_data()
d.addCallback(self.init_completed)
def get_next_id(self):
self.next_id += 1
return self.next_id
def get_by_id(self,id):
#print "looking for id %r" % id
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
try:
return self.store[int(id)]
except (ValueError,KeyError):
pass
return None
def upnp_init(self):
if self.server:
self.server.connection_manager_server.set_variable( \
0, 'SourceProtocolInfo', ['http-get:*:audio/mpeg:DLNA.ORG_PN=MP3;DLNA.ORG_OP=11;DLNA.ORG_FLAGS=01700000000000000000000000000000',
'http-get:*:audio/mpeg:*'])
def update_data(self):
def fail(f):
print "fail", f
return f
dfr = getPage(self.rss_url)
dfr.addCallback(parse_xml)
dfr.addErrback(fail)
dfr.addCallback(self.parse_data)
dfr.addErrback(fail)
dfr.addBoth(self.queue_update)
return dfr
def parse_data(self, xml_data):
root = xml_data.getroot()
self.store = {}
self.store[ROOT_CONTAINER_ID] = \
Container(ROOT_CONTAINER_ID,self,-1, self.name)
self.store[SERIES_CONTAINER_ID] = \
Container(SERIES_CONTAINER_ID,self,ROOT_CONTAINER_ID, 'Series')
self.store[ROOT_CONTAINER_ID].add_child(self.store[SERIES_CONTAINER_ID])
for brand in root.findall('./{http://purl.org/ontology/po/}Brand'):
first = None
for episode in brand.findall('*/{http://purl.org/ontology/po/}Episode'):
for version in episode.findall('*/{http://purl.org/ontology/po/}Version'):
seconds = int(version.find('./{http://uriplay.org/elements/}publishedDuration').text)
hours = seconds / 3600
seconds = seconds - hours * 3600
minutes = seconds / 60
seconds = seconds - minutes * 60
duration = ("%d:%02d:%02d") % (hours, minutes, seconds)
for manifestation in version.findall('./{http://uriplay.org/elements/}manifestedAs'):
encoding = manifestation.find('*/{http://uriplay.org/elements/}dataContainerFormat')
size = manifestation.find('*/{http://uriplay.org/elements/}dataSize')
for location in manifestation.findall('*/*/{http://uriplay.org/elements/}Location'):
uri = location.find('./{http://uriplay.org/elements/}uri')
uri = uri.attrib['{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource']
if first == None:
id = self.get_next_id()
self.store[id] = \
Container(id,self,SERIES_CONTAINER_ID,brand.find('./{http://purl.org/dc/elements/1.1/}title').text)
self.store[SERIES_CONTAINER_ID].add_child(self.store[id])
first = self.store[id]
item = BBCItem(first.id, self.get_next_id(), episode.find('./{http://purl.org/dc/elements/1.1/}title').text, uri)
first.add_child(item)
item.mimetype = encoding.text
item.duration = duration
item.size = int(size.text)*1024
item.description = episode.find('./{http://purl.org/dc/elements/1.1/}description').text
self.update_id += 1
#if self.server:
# self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
# value = (ROOT_CONTAINER_ID,self.container.update_id)
# self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
def queue_update(self, error_or_failure):
reactor.callLater(self.refresh, self.update_data)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~devices~internet_gateway_device_client.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2010 Frank Scholz <[email protected]>
from coherence.upnp.devices.wan_device_client import WANDeviceClient
from coherence import log
import coherence.extern.louie as louie
class InternetGatewayDeviceClient(log.Loggable):
logCategory = 'igd_client'
def __init__(self, device):
self.device = device
self.device_type = self.device.get_friendly_device_type()
self.version = int(self.device.get_device_type_version())
self.icons = device.icons
self.wan_device = None
self.detection_completed = False
louie.connect(self.embedded_device_notified, signal='Coherence.UPnP.EmbeddedDeviceClient.detection_completed', sender=self.device)
try:
wan_device = self.device.get_embedded_device_by_type('WANDevice')[0]
self.wan_device = WANDeviceClient(wan_device)
except:
self.warning("Embedded WANDevice device not available, device not implemented properly according to the UPnP specification")
raise
self.info("InternetGatewayDevice %s" % (self.device.get_friendly_name()))
def remove(self):
self.info("removal of InternetGatewayDeviceClient started")
if self.wan_device != None:
self.wan_device.remove()
def embedded_device_notified(self, device):
self.info("EmbeddedDevice %r sent notification" % device);
if self.detection_completed == True:
return
self.detection_completed = True
louie.send('Coherence.UPnP.DeviceClient.detection_completed', None,
client=self,udn=self.device.udn)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~services~servers~rendering_control_server.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006, Frank Scholz <[email protected]>
# RenderingControl service
from twisted.web import resource
from coherence.upnp.core.soap_service import UPnPPublisher
from coherence.upnp.core import service
class RenderingControlControl(service.ServiceControl,UPnPPublisher):
def __init__(self, server):
self.service = server
self.variables = server.get_variables()
self.actions = server.get_actions()
class RenderingControlServer(service.ServiceServer, resource.Resource):
def __init__(self, device, backend=None):
self.device = device
if backend == None:
backend = self.device.backend
resource.Resource.__init__(self)
service.ServiceServer.__init__(self, 'RenderingControl', self.device.version, backend)
self.control = RenderingControlControl(self)
self.putChild(self.scpd_url, service.scpdXML(self, self.control))
self.putChild(self.control_url, self.control)
def listchilds(self, uri):
cl = ''
for c in self.children:
cl += '<li><a href=%s/%s>%s</a></li>' % (uri,c,c)
return cl
def render(self,request):
return '<html><p>root of the RenderingControl</p><p><ul>%s</ul></p></html>'% self.listchilds(request.uri)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~core~device.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006, Frank Scholz <[email protected]>
import urllib2
import time
from twisted.internet import defer, reactor
from coherence.upnp.core.service import Service
from coherence.upnp.core import utils
from coherence import log
import coherence.extern.louie as louie
ns = "urn:schemas-upnp-org:device-1-0"
class Device(log.Loggable):
logCategory = 'device'
def __init__(self, parent=None):
self.parent = parent
self.services = []
#self.uid = self.usn[:-len(self.st)-2]
self.friendly_name = ""
self.device_type = ""
self.friendly_device_type = "[unknown]"
self.device_type_version = 0
self.udn = None
self.detection_completed = False
self.client = None
self.icons = []
self.devices = []
self.satipcap = None
louie.connect( self.receiver, 'Coherence.UPnP.Service.detection_completed', self)
louie.connect( self.service_detection_failed, 'Coherence.UPnP.Service.detection_failed', self)
def __repr__(self):
return "embedded device %r %r, parent %r" % (self.friendly_name,self.device_type,self.parent)
#def __del__(self):
# #print "Device removal completed"
# pass
def as_dict(self):
import copy
d = {'device_type': self.get_device_type(),
'friendly_name': self.get_friendly_name(),
'udn': self.get_id(),
'services': [x.as_dict() for x in self.services]}
icons = []
for icon in self.icons:
icons.append({"mimetype":icon['mimetype'],"url":icon['url'], "height":icon['height'], "width":icon['width'], "depth":icon['depth']})
d['icons'] = icons
return d
def remove(self,*args):
self.info("removal of ", self.friendly_name, self.udn)
while len(self.devices)>0:
device = self.devices.pop()
self.debug("try to remove %r", device)
device.remove()
while len(self.services)>0:
service = self.services.pop()
self.debug("try to remove %r", service)
service.remove()
if self.client != None:
louie.send('Coherence.UPnP.Device.remove_client', None, self.udn, self.client)
self.client = None
#del self
def receiver(self, *args, **kwargs):
if self.detection_completed == True:
return
for s in self.services:
if s.detection_completed == False:
return
if self.udn == None:
return
self.detection_completed = True
if self.parent != None:
self.info("embedded device %r %r initialized, parent %r" % (self.friendly_name,self.device_type,self.parent))
louie.send('Coherence.UPnP.Device.detection_completed', None, device=self)
if self.parent != None:
louie.send('Coherence.UPnP.Device.detection_completed', self.parent, device=self)
else:
louie.send('Coherence.UPnP.Device.detection_completed', self, device=self)
def service_detection_failed(self, device):
if device == self:
self.remove()
def get_id(self):
return self.udn
def get_uuid(self):
return self.udn[5:]
def get_embedded_devices(self):
return self.devices
def get_embedded_device_by_type(self,type):
r = []
for device in self.devices:
if type == device.friendly_device_type:
r.append(device)
return r
def get_services(self):
return self.services
def get_service_by_type(self,type):
if not isinstance(type,(tuple,list)):
type = [type,]
for service in self.services:
_,_,_,service_class,version = service.service_type.split(':')
if service_class in type:
return service
def add_service(self, service):
self.debug("add_service %r", service)
self.services.append(service)
def remove_service_with_usn(self, service_usn):
for service in self.services:
if service.get_usn() == service_usn:
self.services.remove(service)
service.remove()
break
def add_device(self, device):
self.debug("Device add_device %r", device)
self.devices.append(device)
def get_friendly_name(self):
return self.friendly_name
def get_device_type(self):
return self.device_type
def get_friendly_device_type(self):
return self.friendly_device_type
def get_markup_name(self):
try:
return self._markup_name
except AttributeError:
self._markup_name = u"%s:%s %s" % (self.friendly_device_type,
self.device_type_version, self.friendly_name)
return self._markup_name
def get_device_type_version(self):
return self.device_type_version
def set_client(self, client):
self.client = client
def get_client(self):
return self.client
def renew_service_subscriptions(self):
""" iterate over device's services and renew subscriptions """
self.info("renew service subscriptions for %s" % self.friendly_name)
now = time.time()
for service in self.services:
self.info("check service %r %r " % (service.id, service.get_sid()), service.get_timeout(), now)
if service.get_sid() is not None:
if service.get_timeout() < now:
self.debug("wow, we lost an event subscription for %s %s, " % (self.friendly_name, service.get_id()),
"maybe we need to rethink the loop time and timeout calculation?")
if service.get_timeout() < now + 30 :
service.renew_subscription()
for device in self.devices:
device.renew_service_subscriptions()
def unsubscribe_service_subscriptions(self):
""" iterate over device's services and unsubscribe subscriptions """
l = []
for service in self.get_services():
if service.get_sid() is not None:
l.append(service.unsubscribe())
dl = defer.DeferredList(l)
return dl
def parse_device(self, d):
self.info("parse_device %r" %d)
self.device_type = unicode(d.findtext('./{%s}deviceType' % ns))
self.friendly_device_type, self.device_type_version = \
self.device_type.split(':')[-2:]
self.friendly_name = unicode(d.findtext('./{%s}friendlyName' % ns))
self.udn = d.findtext('./{%s}UDN' % ns)
self.info("found udn %r %r" % (self.udn,self.friendly_name))
try:
self.manufacturer = d.findtext('./{%s}manufacturer' % ns)
except:
pass
try:
self.manufacturer_url = d.findtext('./{%s}manufacturerURL' % ns)
except:
pass
try:
self.model_name = d.findtext('./{%s}modelName' % ns)
except:
pass
try:
self.model_description = d.findtext('./{%s}modelDescription' % ns)
except:
pass
try:
self.model_number = d.findtext('./{%s}modelNumber' % ns)
except:
pass
try:
self.model_url = d.findtext('./{%s}modelURL' % ns)
except:
pass
try:
self.serial_number = d.findtext('./{%s}serialNumber' % ns)
except:
pass
try:
self.upc = d.findtext('./{%s}UPC' % ns)
except:
pass
try:
self.presentation_url = d.findtext('./{%s}presentationURL' % ns)
except:
pass
try:
for dlna_doc in d.findall('./{urn:schemas-dlna-org:device-1-0}X_DLNADOC'):
try:
self.dlna_dc.append(dlna_doc.text)
except AttributeError:
self.dlna_dc = []
self.dlna_dc.append(dlna_doc.text)
except:
pass
try:
for dlna_cap in d.findall('./{urn:schemas-dlna-org:device-1-0}X_DLNACAP'):
for cap in dlna_cap.text.split(','):
try:
self.dlna_cap.append(cap)
except AttributeError:
self.dlna_cap = []
self.dlna_cap.append(cap)
except:
pass
for satipns in ("urn:ses-com:satip", "urn-ses-com:satip"):
try:
self.satipcap = d.findtext('./{%s}X_SATIPCAP' % satipns)
if self.satipcap:
break
except:
pass
icon_list = d.find('./{%s}iconList' % ns)
if icon_list is not None:
import urllib2
url_base = "%s://%s" % urllib2.urlparse.urlparse(self.get_location())[:2]
for icon in icon_list.findall('./{%s}icon' % ns):
try:
i = {}
i['mimetype'] = icon.find('./{%s}mimetype' % ns).text
i['width'] = icon.find('./{%s}width' % ns).text
i['height'] = icon.find('./{%s}height' % ns).text
i['depth'] = icon.find('./{%s}depth' % ns).text
i['realurl'] = icon.find('./{%s}url' % ns).text
i['url'] = self.make_fullyqualified(i['realurl'])
self.icons.append(i)
self.debug("adding icon %r for %r" % (i,self.friendly_name))
except:
import traceback
self.debug(traceback.format_exc())
self.warning("device %r seems to have an invalid icon description, ignoring that icon" % self.friendly_name)
serviceList = d.find('./{%s}serviceList' % ns)
if serviceList:
for service in serviceList.findall('./{%s}service' % ns):
serviceType = service.findtext('{%s}serviceType' % ns)
serviceId = service.findtext('{%s}serviceId' % ns)
controlUrl = service.findtext('{%s}controlURL' % ns)
eventSubUrl = service.findtext('{%s}eventSubURL' % ns)
presentationUrl = service.findtext('{%s}presentationURL' % ns)
scpdUrl = service.findtext('{%s}SCPDURL' % ns)
""" check if values are somehow reasonable
"""
if len(scpdUrl) == 0:
self.warning("service has no uri for its description")
continue
if len(eventSubUrl) == 0:
self.warning("service has no uri for eventing")
continue
if len(controlUrl) == 0:
self.warning("service has no uri for controling")
continue
self.add_service(Service(serviceType, serviceId, self.get_location(),
controlUrl,
eventSubUrl, presentationUrl, scpdUrl, self))
# now look for all sub devices
embedded_devices = d.find('./{%s}deviceList' % ns)
if embedded_devices:
for d in embedded_devices.findall('./{%s}device' % ns):
embedded_device = Device(self)
self.add_device(embedded_device)
embedded_device.parse_device(d)
self.receiver()
def get_location(self):
return self.parent.get_location()
def get_usn(self):
return self.parent.get_usn()
def get_upnp_version(self):
return self.parent.get_upnp_version()
def get_urlbase(self):
return self.parent.get_urlbase()
def get_presentation_url(self):
try:
return self.make_fullyqualified(self.presentation_url)
except:
return ''
def get_parent_id(self):
try:
return self.parent.get_id()
except:
return ''
def get_satipcap(self):
return self.satipcap or ''
def make_fullyqualified(self,url):
return self.parent.make_fullyqualified(url)
def as_tuples(self):
r = []
def append(name,attribute):
try:
if isinstance(attribute,tuple):
if callable(attribute[0]):
v1 = attribute[0]()
else:
v1 = getattr(self,attribute[0])
if v1 in [None,'None']:
return
if callable(attribute[1]):
v2 = attribute[1]()
else:
v2 = getattr(self,attribute[1])
if v2 in [None,'None']:
return
r.append((name,(v1,v2)))
return
elif callable(attribute):
v = attribute()
else:
v = getattr(self,attribute)
if v not in [None,'None']:
r.append((name,v))
except:
import traceback
self.debug(traceback.format_exc())
try:
r.append(('Location',(self.get_location(),self.get_location())))
except:
pass
try:
append('URL base',self.get_urlbase)
except:
pass
try:
r.append(('UDN',self.get_id()))
except:
pass
try:
r.append(('Type',self.device_type))
except:
pass
try:
r.append(('UPnP Version',self.upnp_version))
except:
pass
try:
r.append(('DLNA Device Class',','.join(self.dlna_dc)))
except:
pass
try:
r.append(('DLNA Device Capability',','.join(self.dlna_cap)))
except:
pass
try:
r.append(('Friendly Name',self.friendly_name))
except:
pass
try:
append('Manufacturer','manufacturer')
except:
pass
try:
append('Manufacturer URL',('manufacturer_url','manufacturer_url'))
except:
pass
try:
append('Model Description','model_description')
except:
pass
try:
append('Model Name','model_name')
except:
pass
try:
append('Model Number','model_number')
except:
pass
try:
append('Model URL',('model_url','model_url'))
except:
pass
try:
append('Serial Number','serial_number')
except:
pass
try:
append('UPC','upc')
except:
pass
try:
append('Presentation URL',('presentation_url',lambda: self.make_fullyqualified(getattr(self,'presentation_url'))))
except:
pass
for icon in self.icons:
r.append(('Icon', (icon['realurl'],
self.make_fullyqualified(icon['realurl']),
{'Mimetype': icon['mimetype'],
'Width':icon['width'],
'Height':icon['height'],
'Depth':icon['depth']})))
return r
class RootDevice(Device):
def __init__(self, infos):
self.usn = infos['USN']
self.server = infos['SERVER']
self.st = infos['ST']
self.location = infos['LOCATION']
self.manifestation = infos['MANIFESTATION']
self.host = infos['HOST']
self.root_detection_completed = False
Device.__init__(self, None)
louie.connect( self.device_detect, 'Coherence.UPnP.Device.detection_completed', self)
# we need to handle root device completion
# these events could be ourself or our children.
reactor.callLater(0.5, self.parse_description)
def __repr__(self):
return "rootdevice %r %r %r %r, manifestation %r" % (self.friendly_name,self.udn,self.st,self.host,self.manifestation)
def remove(self, *args):
result = Device.remove(self, *args)
louie.send('Coherence.UPnP.RootDevice.removed', self, usn=self.get_usn())
return result
def get_usn(self):
return self.usn
def get_st(self):
return self.st
def get_location(self):
return self.location
def get_upnp_version(self):
return self.upnp_version
def get_urlbase(self):
return self.urlbase
def get_host(self):
return self.host
def is_local(self):
if self.manifestation == 'local':
return True
return False
def is_remote(self):
if self.manifestation != 'local':
return True
return False
def device_detect( self, *args, **kwargs):
self.debug("device_detect %r", kwargs)
self.debug("root_detection_completed %r", self.root_detection_completed)
if self.root_detection_completed == True:
return
# our self is not complete yet
self.debug("detection_completed %r", self.detection_completed)
if self.detection_completed == False:
return
# now check child devices.
self.debug("self.devices %r", self.devices)
for d in self.devices:
self.debug("check device %r %r", d.detection_completed, d)
if d.detection_completed == False:
return
# now must be done, so notify root done
self.root_detection_completed = True
self.info("rootdevice %r %r %r initialized, manifestation %r" % (self.friendly_name,self.st,self.host,self.manifestation))
louie.send('Coherence.UPnP.RootDevice.detection_completed', None, device=self)
def add_device(self, device):
self.debug("RootDevice add_device %r", device)
self.devices.append(device)
def get_devices(self):
self.debug("RootDevice get_devices:", self.devices)
return self.devices
def parse_description(self):
def gotPage(x):
self.debug("got device description from %r" % self.location)
data, headers = x
xml_data = None
try:
xml_data = utils.parse_xml(data, 'utf-8')
except:
self.warning("Invalid device description received from %r", self.location)
import traceback
self.debug(traceback.format_exc())
if xml_data is not None:
tree = xml_data.getroot()
major = tree.findtext('./{%s}specVersion/{%s}major' % (ns,ns))
minor = tree.findtext('./{%s}specVersion/{%s}minor' % (ns,ns))
try:
self.upnp_version = '.'.join((major,minor))
except:
self.upnp_version = 'n/a'
try:
self.urlbase = tree.findtext('./{%s}URLBase' % ns)
except:
import traceback
self.debug(traceback.format_exc())
d = tree.find('./{%s}device' % ns)
if d is not None:
self.parse_device(d) # root device
def gotError(failure, url):
self.warning("error getting device description from %r", url)
self.info(failure)
utils.getPage(self.location).addCallbacks(gotPage, gotError, None, None, [self.location], None)
def make_fullyqualified(self,url):
if url.startswith('http://'):
return url
import urlparse
base = self.get_urlbase()
if base:
if base[-1] != '/':
base += '/'
r = urlparse.urljoin(base,url)
else:
r = urlparse.urljoin(self.get_location(),url)
return r
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~ui~av_widgets.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
""" simple and hopefully reusable widgets to ease
the creation of UPnP UI applications
icons taken from the Tango Desktop Project
"""
import os.path
import urllib
import traceback
import pygtk
pygtk.require("2.0")
import gtk
import gobject
import dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
import dbus.service
import mimetypes
mimetypes.init()
# dbus defines
BUS_NAME = 'org.Coherence'
OBJECT_PATH = '/org/Coherence'
# gtk store defines
NAME_COLUMN = 0
ID_COLUMN = 1
UPNP_CLASS_COLUMN = 2
CHILD_COUNT_COLUMN = 3
UDN_COLUMN = 4
SERVICE_COLUMN = 5
ICON_COLUMN = 6
DIDL_COLUMN = 7
TOOLTIP_ICON_COLUMN = 8
from pkg_resources import resource_filename
class ControlPoint(object):
_instance_ = None # Singleton
def __new__(cls, *args, **kwargs):
obj = getattr(cls, '_instance_', None)
if obj is not None:
return obj
else:
obj = super(ControlPoint, cls).__new__(cls, *args, **kwargs)
cls._instance_ = obj
obj._connect(*args, **kwargs)
return obj
def __init__(self):
pass
def _connect(self):
self.bus = dbus.SessionBus()
self.coherence = self.bus.get_object(BUS_NAME,OBJECT_PATH)
class DeviceExportWidget(object):
def __init__(self,name='Nautilus',standalone=True,root=None):
self.root=root
self.uuid = None
self.name = name
self.standalone=standalone
icon = resource_filename(__name__, os.path.join('icons','emblem-new.png'))
self.new_icon = gtk.gdk.pixbuf_new_from_file(icon)
icon = resource_filename(__name__, os.path.join('icons','emblem-shared.png'))
self.shared_icon = gtk.gdk.pixbuf_new_from_file(icon)
icon = resource_filename(__name__, os.path.join('icons','emblem-unreadable.png'))
self.unshared_icon = gtk.gdk.pixbuf_new_from_file(icon)
self.filestore = gtk.ListStore(str,gtk.gdk.Pixbuf)
self.coherence = ControlPoint().coherence
def build_ui(self,root=None):
if root != None:
self.root = root
self.window = gtk.VBox(homogeneous=False, spacing=0)
self.fileview = gtk.TreeView(self.filestore)
column = gtk.TreeViewColumn('Folders to share')
self.fileview.append_column(column)
icon_cell = gtk.CellRendererPixbuf()
text_cell = gtk.CellRendererText()
column.pack_start(icon_cell, False)
column.pack_start(text_cell, True)
column.set_attributes(text_cell, text=0)
column.add_attribute(icon_cell, "pixbuf",1)
self.window.pack_start(self.fileview,expand=True,fill=True)
buttonbox = gtk.HBox(homogeneous=False, spacing=0)
button = gtk.Button(stock=gtk.STOCK_ADD)
button.set_sensitive(False)
button.connect("clicked", self.new_files)
buttonbox.pack_start(button, expand=False,fill=False, padding=2)
button = gtk.Button(stock=gtk.STOCK_REMOVE)
#button.set_sensitive(False)
button.connect("clicked", self.remove_files)
buttonbox.pack_start(button, expand=False,fill=False, padding=2)
button = gtk.Button(stock=gtk.STOCK_CANCEL)
button.connect("clicked", self.share_cancel)
buttonbox.pack_start(button, expand=False,fill=False, padding=2)
button = gtk.Button(stock=gtk.STOCK_APPLY)
button.connect("clicked", self.share_files)
buttonbox.pack_start(button, expand=False,fill=False, padding=2)
self.window.pack_end(buttonbox,expand=False,fill=False)
return self.window
def share_cancel(self,button):
for row in self.filestore:
print row
if row[1] == self.new_icon:
del row
continue
if row[1] == self.unshared_icon:
row[1] = self.shared_icon
if self.standalone:
gtk.main_quit()
else:
self.root.hide()
def share_files(self,button):
print "share_files with", self.uuid
folders = []
for row in self.filestore:
if row[1] == self.unshared_icon:
del row
continue
folders.append(row[0])
if self.uuid == None:
if len(folders) > 0:
self.uuid = self.coherence.add_plugin('FSStore', {'name': self.name,
'version':'1',
'create_root': 'yes',
'import_folder': '/tmp/UPnP Imports',
'content':','.join(folders)},
dbus_interface=BUS_NAME)
#self.coherence.pin('Nautilus::MediaServer::%d'%os.getpid(),self.uuid)
else:
result = self.coherence.call_plugin(self.uuid,'update_config',{'content':','.join(folders)})
if result != self.uuid:
print "something failed", result
for row in self.filestore:
row[1] = self.shared_icon
self.root.hide()
def add_files(self,files):
print "add_files", files
for filename in files:
for row in self.filestore:
if os.path.abspath(filename) == row[0]:
break
else:
self.add_file(filename)
def add_file(self,filename):
self.filestore.append([os.path.abspath(filename),self.new_icon])
def new_files(self,button):
print "new_files"
def remove_files(self,button):
print "remove_files"
selection = self.fileview.get_selection()
print selection
model, selected_rows = selection.get_selected_rows()
for row_path in selected_rows:
#model.remove(model.get_iter(row_path))
row = model[row_path]
row[1] = self.unshared_icon
class DeviceImportWidget(object):
def __init__(self,standalone=True,root=None):
self.standalone=standalone
self.root=root
self.build_ui()
self.init_controlpoint()
def build_ui(self):
self.window = gtk.VBox(homogeneous=False, spacing=0)
self.combobox = gtk.ComboBox()
self.store = gtk.ListStore(str, # 0: friendly name
str, # 1: device udn
gtk.gdk.Pixbuf)
icon = resource_filename(__name__, os.path.join('icons','network-server.png'))
self.device_icon = gtk.gdk.pixbuf_new_from_file(icon)
# create a CellRenderers to render the data
icon_cell = gtk.CellRendererPixbuf()
text_cell = gtk.CellRendererText()
self.combobox.pack_start(icon_cell, False)
self.combobox.pack_start(text_cell, True)
self.combobox.set_attributes(text_cell, text=0)
self.combobox.add_attribute(icon_cell, "pixbuf",2)
self.combobox.set_model(self.store)
item = self.store.append(None)
self.store.set_value(item, 0, 'Select a MediaServer...')
self.store.set_value(item, 1, '')
self.store.set_value(item, 2, None)
self.combobox.set_active(0)
self.window.pack_start(self.combobox,expand=False,fill=False)
self.filestore = gtk.ListStore(str)
self.fileview = gtk.TreeView(self.filestore)
column = gtk.TreeViewColumn('Files')
self.fileview.append_column(column)
text_cell = gtk.CellRendererText()
column.pack_start(text_cell, True)
column.set_attributes(text_cell, text=0)
self.window.pack_start(self.fileview,expand=True,fill=True)
buttonbox = gtk.HBox(homogeneous=False, spacing=0)
button = gtk.Button(stock=gtk.STOCK_ADD)
button.set_sensitive(False)
button.connect("clicked", self.new_files)
buttonbox.pack_start(button, expand=False,fill=False, padding=2)
button = gtk.Button(stock=gtk.STOCK_REMOVE)
button.set_sensitive(False)
button.connect("clicked", self.remove_files)
buttonbox.pack_start(button, expand=False,fill=False, padding=2)
button = gtk.Button(stock=gtk.STOCK_CANCEL)
if self.standalone:
button.connect("clicked", gtk.main_quit)
else:
button.connect("clicked", lambda x: self.root.destroy())
buttonbox.pack_start(button, expand=False,fill=False, padding=2)
button = gtk.Button(stock=gtk.STOCK_APPLY)
button.connect("clicked", self.import_files)
buttonbox.pack_start(button, expand=False,fill=False, padding=2)
self.window.pack_end(buttonbox,expand=False,fill=False)
def add_file(self,filename):
self.filestore.append([os.path.abspath(filename)])
def new_files(self,button):
print "new_files"
def remove_files(self,button):
print "remove_files"
def import_files(self,button):
print "import_files"
active = self.combobox.get_active()
if active <= 0:
print "no MediaServer selected"
return None
friendlyname, uuid,_ = self.store[active]
try:
row = self.filestore[0]
print 'import to', friendlyname,os.path.basename(row[0])
def success(r):
print 'success',r
self.filestore.remove(self.filestore.get_iter(0))
self.import_files(None)
def reply(r):
print 'reply',r['Result'], r['ObjectID']
from coherence.upnp.core import DIDLLite
didl = DIDLLite.DIDLElement.fromString(r['Result'])
item = didl.getItems()[0]
res = item.res.get_matching(['*:*:*:*'], protocol_type='http-get')
if len(res) > 0:
print 'importURI',res[0].importUri
self.coherence.put_resource(res[0].importUri,row[0],
reply_handler=success,
error_handler=self.handle_error)
mimetype,_ = mimetypes.guess_type(row[0], strict=False)
if mimetype.startswith('image/'):
upnp_class = 'object.item.imageItem'
elif mimetype.startswith('video/'):
upnp_class = 'object.item.videoItem'
elif mimetype.startswith('audio/'):
upnp_class = 'object.item.audioItem'
else:
upnp_class = 'object.item'
self.coherence.create_object(uuid,'DLNA.ORG_AnyContainer',
{'parentID':'DLNA.ORG_AnyContainer','upnp_class':upnp_class,'title':os.path.basename(row[0])},
reply_handler=reply,
error_handler=self.handle_error)
except IndexError:
pass
def handle_error(self,error):
print error
def handle_devices_reply(self,devices):
for device in devices:
if device['device_type'].split(':')[3] == 'MediaServer':
self.media_server_found(device)
def init_controlpoint(self):
cp = ControlPoint()
self.bus = cp.bus
self.coherence = cp.coherence
self.coherence.get_devices(dbus_interface=BUS_NAME,
reply_handler=self.handle_devices_reply,
error_handler=self.handle_error)
self.coherence.connect_to_signal('UPnP_ControlPoint_MediaServer_detected', self.media_server_found, dbus_interface=BUS_NAME)
self.coherence.connect_to_signal('UPnP_ControlPoint_MediaServer_removed', self.media_server_removed, dbus_interface=BUS_NAME)
self.devices = {}
def media_server_found(self,device,udn=None):
for service in device['services']:
service_type = service.split('/')[-1]
if service_type == 'ContentDirectory':
def got_icons(r,udn,item):
print 'got_icons', r
for icon in r:
###FIXME, we shouldn't just use the first icon
icon_loader = gtk.gdk.PixbufLoader()
icon_loader.write(urllib.urlopen(str(icon['url'])).read())
icon_loader.close()
icon = icon_loader.get_pixbuf()
icon = icon.scale_simple(16,16,gtk.gdk.INTERP_BILINEAR)
self.store.set_value(item, 2, icon)
break
def reply(r,udn):
if 'CreateObject' in r:
self.devices[udn] = {'ContentDirectory':{}}
self.devices[udn]['ContentDirectory']['actions'] = r
item = self.store.append(None)
self.store.set_value(item, 0, str(device['friendly_name']))
self.store.set_value(item, 1, str(device['udn']))
self.store.set_value(item, 2, self.device_icon)
d = self.bus.get_object(BUS_NAME+'.device',device['path'])
d.get_device_icons(reply_handler=lambda x : got_icons(x,str(device['udn']),item),error_handler=self.handle_error)
s = self.bus.get_object(BUS_NAME+'.service',service)
s.get_available_actions(reply_handler=lambda x : reply(x,str(device['udn'])),error_handler=self.handle_error)
def media_server_removed(self,udn):
row_count = 0
for row in self.store:
if udn == row[1]:
self.store.remove(self.store.get_iter(row_count))
del self.devices[str(udn)]
break
row_count += 1
class TreeWidget(object):
def __init__(self,cb_item_dbl_click=None,
cb_resource_chooser=None):
self.cb_item_dbl_click = cb_item_dbl_click
self.cb_item_right_click = None
self.cb_resource_chooser = cb_resource_chooser
self.build_ui()
self.init_controlpoint()
def build_ui(self):
self.window = gtk.ScrolledWindow()
self.window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
icon = resource_filename(__name__, os.path.join('icons','network-server.png'))
self.device_icon = gtk.gdk.pixbuf_new_from_file(icon)
icon = resource_filename(__name__, os.path.join('icons','folder.png'))
self.folder_icon = gtk.gdk.pixbuf_new_from_file(icon)
icon = resource_filename(__name__, os.path.join('icons','audio-x-generic.png'))
self.audio_icon = gtk.gdk.pixbuf_new_from_file(icon)
icon = resource_filename(__name__, os.path.join('icons','video-x-generic.png'))
self.video_icon = gtk.gdk.pixbuf_new_from_file(icon)
icon = resource_filename(__name__, os.path.join('icons','image-x-generic.png'))
self.image_icon = gtk.gdk.pixbuf_new_from_file(icon)
self.store = gtk.TreeStore(str, # 0: name or title
str, # 1: id, '0' for the device
str, # 2: upnp_class, 'root' for the device
int, # 3: child count, -1 if not available
str, # 4: device udn, '' for an item
str, # 5: service path, '' for a non container item
gtk.gdk.Pixbuf,
str, # 7: DIDLLite fragment, '' for a non upnp item
gtk.gdk.Pixbuf
)
self.treeview = gtk.TreeView(self.store)
self.column = gtk.TreeViewColumn('MediaServers')
self.treeview.append_column(self.column)
# create a CellRenderers to render the data
icon_cell = gtk.CellRendererPixbuf()
text_cell = gtk.CellRendererText()
self.column.pack_start(icon_cell, False)
self.column.pack_start(text_cell, True)
self.column.set_attributes(text_cell, text=0)
self.column.add_attribute(icon_cell, "pixbuf",6)
#self.column.set_cell_data_func(self.cellpb, get_icon)
#self.treeview.insert_column_with_attributes(-1, 'MediaServers', cell, text=0)
self.treeview.connect("row-activated", self.browse)
self.treeview.connect("row-expanded", self.row_expanded)
self.treeview.connect("button_press_event", self.button_action)
self.treeview.set_property("has-tooltip", True)
self.treeview.connect("query-tooltip", self.show_tooltip)
self.tooltip_path = None
self.we_are_scrolling = None
def end_scrolling():
self.we_are_scrolling = None
def start_scrolling(w,e):
if self.we_are_scrolling != None:
gobject.source_remove(self.we_are_scrolling)
self.we_are_scrolling = gobject.timeout_add(800, end_scrolling)
self.treeview.connect('scroll-event', start_scrolling)
self.window.add(self.treeview)
def show_tooltip(self, widget, x, y, keyboard_mode, tooltip):
if self.we_are_scrolling != None:
return False
ret = False
try:
path = self.treeview.get_dest_row_at_pos(x, y)
iter = self.store.get_iter(path[0])
title,object_id,upnp_class,item = self.store.get(iter,NAME_COLUMN,ID_COLUMN,UPNP_CLASS_COLUMN,DIDL_COLUMN)
from coherence.upnp.core import DIDLLite
if upnp_class == 'object.item.videoItem':
self.tooltip_path = object_id
item = DIDLLite.DIDLElement.fromString(item).getItems()[0]
tooltip_icon, = self.store.get(iter,TOOLTIP_ICON_COLUMN)
if tooltip_icon != None:
tooltip.set_icon(tooltip_icon)
else:
tooltip.set_icon(self.video_icon)
for res in item.res:
protocol,network,content_format,additional_info = res.protocolInfo.split(':')
if(content_format == 'image/jpeg' and
'DLNA.ORG_PN=JPEG_TN' in additional_info.split(';')):
icon_loader = gtk.gdk.PixbufLoader()
icon_loader.write(urllib.urlopen(str(res.data)).read())
icon_loader.close()
icon = icon_loader.get_pixbuf()
tooltip.set_icon(icon)
self.store.set_value(iter, TOOLTIP_ICON_COLUMN, icon)
#print "got poster", icon
break
title = title.replace('&','&')
try:
director = item.director.replace('&','&')
except AttributeError:
director = ""
try:
description = item.description.replace('&','&')
except AttributeError:
description = ""
tooltip.set_markup("<b>%s</b>\n"
"<b>Director:</b> %s\n"
"<b>Description:</b> %s" % (title,
director,
description))
ret = True
except TypeError:
#print traceback.format_exc()
pass
except Exception:
#print traceback.format_exc()
#print "something wrong"
pass
return ret
def button_action(self, widget, event):
#print "button_action", widget, event, event.button
if self.cb_item_right_click != None:
return self.cb_item_right_click(widget, event)
return 0
def handle_error(self,error):
print error
def handle_devices_reply(self,devices):
for device in devices:
if device['device_type'].split(':')[3] == 'MediaServer':
self.media_server_found(device)
def init_controlpoint(self):
cp = ControlPoint()
self.bus = cp.bus
self.coherence = cp.coherence
self.hostname = self.coherence.hostname(dbus_interface=BUS_NAME)
self.coherence.get_devices(dbus_interface=BUS_NAME,
reply_handler=self.handle_devices_reply,
error_handler=self.handle_error)
self.coherence.connect_to_signal('UPnP_ControlPoint_MediaServer_detected', self.media_server_found, dbus_interface=BUS_NAME)
self.coherence.connect_to_signal('UPnP_ControlPoint_MediaServer_removed', self.media_server_removed, dbus_interface=BUS_NAME)
self.devices = {}
def device_has_action(self,udn,service,action):
try:
self.devices[udn][service]['actions'].index(action)
return True
except:
return False
def state_variable_change( self, udn, service, variable, value):
#print "state_variable_change", udn, service, variable, 'changed to', value
if variable == 'ContainerUpdateIDs':
changes = value.split(',')
while len(changes) > 1:
container = changes.pop(0).strip()
update_id = changes.pop(0).strip()
def match_func(model, iter, data):
column, key = data # data is a tuple containing column number, key
value = model.get_value(iter, column)
return value == key
def search(model, iter, func, data):
#print "search", model, iter, data
while iter:
if func(model, iter, data):
return iter
result = search(model, model.iter_children(iter), func, data)
if result: return result
iter = model.iter_next(iter)
return None
row_count = 0
for row in self.store:
if udn == row[UDN_COLUMN]:
iter = self.store.get_iter(row_count)
match_iter = search(self.store, self.store.iter_children(iter),
match_func, (ID_COLUMN, container))
if match_iter:
print "heureka, we have a change in ", container, ", container needs a reload"
path = self.store.get_path(match_iter)
expanded = self.treeview.row_expanded(path)
child = self.store.iter_children(match_iter)
while child:
self.store.remove(child)
child = self.store.iter_children(match_iter)
self.browse(self.treeview,path,None,
starting_index=0,requested_count=0,force=True,expand=expanded)
break
row_count += 1
def media_server_found(self,device,udn=None):
#print "media_server_found", device['friendly_name']
item = self.store.append(None)
self.store.set_value(item, NAME_COLUMN, device['friendly_name'])
self.store.set_value(item, ID_COLUMN, '0')
self.store.set_value(item, UPNP_CLASS_COLUMN, 'root')
self.store.set_value(item, CHILD_COUNT_COLUMN, -1)
self.store.set_value(item, UDN_COLUMN, str(device['udn']))
self.store.set_value(item, ICON_COLUMN, self.device_icon)
self.store.set_value(item, DIDL_COLUMN, '')
self.store.set_value(item, TOOLTIP_ICON_COLUMN, None)
self.store.append(item, ('...loading...','','placeholder',-1,'','',None,'',None))
self.devices[str(device['udn'])] = {'ContentDirectory':{}}
for service in device['services']:
service_type = service.split('/')[-1]
if service_type == 'ContentDirectory':
self.store.set_value(item, SERVICE_COLUMN, service)
self.devices[str(device['udn'])]['ContentDirectory'] = {}
def reply(r,udn):
self.devices[udn]['ContentDirectory']['actions'] = r
def got_icons(r,udn,item):
#print 'got_icons', r
for icon in r:
###FIXME, we shouldn't just use the first icon
icon_loader = gtk.gdk.PixbufLoader()
icon_loader.write(urllib.urlopen(str(icon['url'])).read())
icon_loader.close()
icon = icon_loader.get_pixbuf()
icon = icon.scale_simple(16,16,gtk.gdk.INTERP_BILINEAR)
self.store.set_value(item, ICON_COLUMN, icon)
break
def reply_subscribe(udn, service, r):
for k,v in r.iteritems():
self.state_variable_change(udn,service,k,v)
s = self.bus.get_object(BUS_NAME+'.service',service)
s.connect_to_signal('StateVariableChanged', self.state_variable_change, dbus_interface=BUS_NAME+'.service')
s.get_available_actions(reply_handler=lambda x : reply(x,str(device['udn'])),error_handler=self.handle_error)
s.subscribe(reply_handler=reply_subscribe,error_handler=self.handle_error)
d = self.bus.get_object(BUS_NAME+'.device',device['path'])
d.get_device_icons(reply_handler=lambda x : got_icons(x,str(device['udn']),item),error_handler=self.handle_error)
def media_server_removed(self,udn):
#print "media_server_removed", udn
row_count = 0
for row in self.store:
if udn == row[UDN_COLUMN]:
self.store.remove(self.store.get_iter(row_count))
del self.devices[str(udn)]
break
row_count += 1
def row_expanded(self,view,iter,row_path):
#print "row_expanded", view,iter,row_path
child = self.store.iter_children(iter)
if child:
upnp_class, = self.store.get(child,UPNP_CLASS_COLUMN)
if upnp_class == 'placeholder':
self.browse(view,row_path,None)
def browse(self,view,row_path,column,starting_index=0,requested_count=0,force=False,expand=False):
#print "browse", view,row_path,column,starting_index,requested_count,force
iter = self.store.get_iter(row_path)
child = self.store.iter_children(iter)
if child:
upnp_class, = self.store.get(child,UPNP_CLASS_COLUMN)
if upnp_class != 'placeholder':
if force == False:
if view.row_expanded(row_path):
view.collapse_row(row_path)
else:
view.expand_row(row_path, False)
return
title,object_id,upnp_class = self.store.get(iter,NAME_COLUMN,ID_COLUMN,UPNP_CLASS_COLUMN)
if(not upnp_class.startswith('object.container') and
not upnp_class == 'root'):
url, = self.store.get(iter,SERVICE_COLUMN)
if url == '':
return
print "request to play:", title,object_id,url
if self.cb_item_dbl_click != None:
self.cb_item_dbl_click(url)
return
def reply(r):
#print "browse_reply - %s of %s returned" % (r['NumberReturned'],r['TotalMatches'])
from coherence.upnp.core import DIDLLite
child = self.store.iter_children(iter)
if child:
upnp_class, = self.store.get(child,UPNP_CLASS_COLUMN)
if upnp_class == 'placeholder':
self.store.remove(child)
title, = self.store.get(iter,NAME_COLUMN)
try:
title = title[:title.rindex('(')]
self.store.set_value(iter,NAME_COLUMN, "%s(%d)" % (title,int(r['TotalMatches'])))
except ValueError:
pass
didl = DIDLLite.DIDLElement.fromString(r['Result'])
for item in didl.getItems():
#print item.title, item.id, item.upnp_class
if item.upnp_class.startswith('object.container'):
icon = self.folder_icon
service, = self.store.get(iter,SERVICE_COLUMN)
child_count = item.childCount
try:
title = "%s (%d)" % (item.title,item.childCount)
except TypeError:
title = "%s (n/a)" % item.title
child_count = -1
else:
icon=None
service = ''
if callable(self.cb_resource_chooser):
service = self.cb_resource_chooser(item.res)
else:
res = item.res.get_matching(['*:%s:*:*' % self.hostname], protocol_type='internal')
if len(res) == 0:
res = item.res.get_matching(['*:*:*:*'], protocol_type='http-get')
if len(res) > 0:
res = res[0]
remote_protocol,remote_network,remote_content_format,_ = res.protocolInfo.split(':')
service = res.data
child_count = -1
title = item.title
if item.upnp_class.startswith('object.item.audioItem'):
icon = self.audio_icon
elif item.upnp_class.startswith('object.item.videoItem'):
icon = self.video_icon
elif item.upnp_class.startswith('object.item.imageItem'):
icon = self.image_icon
stored_didl = DIDLLite.DIDLElement()
stored_didl.addItem(item)
new_iter = self.store.append(iter, (title,item.id,item.upnp_class,child_count,'',service,icon,stored_didl.toString(),None))
if item.upnp_class.startswith('object.container'):
self.store.append(new_iter, ('...loading...','','placeholder',-1,'','',None,'',None))
if((int(r['TotalMatches']) > 0 and force==False) or
expand==True):
view.expand_row(row_path, False)
if(requested_count != int(r['NumberReturned']) and
int(r['NumberReturned']) < (int(r['TotalMatches'])-starting_index)):
print "seems we have been returned only a part of the result"
print "requested %d, starting at %d" % (requested_count,starting_index)
print "got %d out of %d" % (int(r['NumberReturned']), int(r['TotalMatches']))
print "requesting more starting now at %d" % (starting_index+int(r['NumberReturned']))
self.browse(view,row_path,column,
starting_index=starting_index+int(r['NumberReturned']),
force=True)
service, = self.store.get(iter,SERVICE_COLUMN)
if service == '':
return
s = self.bus.get_object(BUS_NAME+'.service',service)
s.action('browse',
{'object_id':object_id,'process_result':'no',
'starting_index':str(starting_index),'requested_count':str(requested_count)},
reply_handler=reply,error_handler=self.handle_error)
def destroy_object(self, row_path):
#print "destroy_object", row_path
iter = self.store.get_iter(row_path)
object_id, = self.store.get(iter,ID_COLUMN)
parent_iter = self.store.iter_parent(iter)
service, = self.store.get(parent_iter,SERVICE_COLUMN)
if service == '':
return
def reply(r):
#print "destroy_object reply", r
pass
s = self.bus.get_object(BUS_NAME+'.service',service)
s.action('destroy_object',
{'object_id':object_id},
reply_handler=reply,error_handler=self.handle_error)
if __name__ == '__main__':
ui=TreeWidget()
window = gtk.Window()
window.connect("delete_event", gtk.main_quit)
window.set_default_size(350, 550)
window.add(ui.window)
window.show_all()
gtk.gdk.threads_init()
gtk.main() | [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~core~service.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006, Frank Scholz <[email protected]>
import os
import time
import urllib2
from coherence.upnp.core import action
from coherence.upnp.core import event
from coherence.upnp.core import variable
from coherence.upnp.core import utils
from coherence.upnp.core.soap_proxy import SOAPProxy
from coherence.upnp.core.soap_service import errorCode
from coherence.upnp.core.event import EventSubscriptionServer
from coherence.extern.et import ET
from twisted.web import static
from twisted.internet import defer, reactor
from twisted.python import failure, util
from twisted.internet import task
import coherence.extern.louie as louie
from coherence import log
global subscribers
subscribers = {}
def subscribe(service):
subscribers[service.get_sid()] = service
def unsubscribe(service):
if subscribers.has_key(service.get_sid()):
del subscribers[service.get_sid()]
class Service(log.Loggable):
logCategory = 'service_client'
def __init__(self, service_type, service_id, location, control_url,
event_sub_url, presentation_url, scpd_url, device):
#if not control_url.startswith('/'):
# control_url = "/%s" % control_url
#if not event_sub_url.startswith('/'):
# event_sub_url = "/%s" % event_sub_url
#if presentation_url and not presentation_url.startswith('/'):
# presentation_url = "/%s" % presentation_url
#if not scpd_url.startswith('/'):
# scpd_url = "/%s" % scpd_url
self.service_type = service_type
self.detection_completed = False
self.id = service_id
self.control_url = control_url
self.event_sub_url = event_sub_url
self.presentation_url = presentation_url
self.scpd_url = scpd_url
self.device = device
self._actions = {}
self._variables = { 0: {}}
self._var_subscribers = {}
self.subscription_id = None
self.timeout = 0
self.event_connection = None
self.last_time_updated = None
self.client = None
parsed = urllib2.urlparse.urlparse(location)
self.url_base = "%s://%s" % (parsed[0], parsed[1])
self.parse_actions()
self.info("%s %s %s initialized" % (self.device.friendly_name,self.service_type,self.id))
def as_tuples(self):
r = []
def append(name,attribute):
try:
if isinstance(attribute,tuple):
if callable(attribute[0]):
v1 = attribute[0]()
elif hasattr(self,attribute[0]):
v1 = getattr(self,attribute[0])
else:
v1 = attribute[0]
if v1 in [None,'None']:
return
if callable(attribute[1]):
v2 = attribute[1]()
elif hasattr(self,attribute[1]):
v2 = getattr(self,attribute[1])
else:
v2 = attribute[1]
if v2 in [None,'None']:
return
if len(attribute)> 2:
r.append((name,(v1,v2,attribute[2])))
else:
r.append((name,(v1,v2)))
return
elif callable(attribute):
v = attribute()
elif hasattr(self,attribute):
v = getattr(self,attribute)
else:
v = attribute
if v not in [None,'None']:
r.append((name,v))
except:
import traceback
self.debug(traceback.format_exc())
r.append(('Location',(self.device.get_location(),self.device.get_location())))
append('URL base',self.device.get_urlbase)
r.append(('UDN',self.device.get_id()))
r.append(('Type',self.service_type))
r.append(('ID',self.id))
append('Service Description URL',(self.scpd_url,lambda: self.device.make_fullyqualified(self.scpd_url)))
append('Control URL',(self.control_url,lambda: self.device.make_fullyqualified(self.control_url),False))
append('Event Subscription URL',(self.event_sub_url,lambda: self.device.make_fullyqualified(self.event_sub_url),False))
return r
def as_dict(self):
d = {'type':self.service_type}
d['actions'] = [a.as_dict() for a in self._actions.values()]
return d
def __repr__(self):
return "Service %s %s" % (self.service_type,self.id)
#def __del__(self):
# print "Service deleted"
# pass
def _get_client(self, name):
url = self.get_control_url()
namespace = self.get_type()
action = "%s#%s" % (namespace, name)
client = SOAPProxy( url, namespace=("u",namespace), soapaction=action)
return client
def remove(self):
self.info("removal of ", self.device.friendly_name, self.service_type, self.id)
try:
self.renew_subscription_call.cancel()
except:
pass
if self.event_connection != None:
self.event_connection.teardown()
if self.subscription_id != None:
self.unsubscribe()
for name,action in self._actions.items():
self.debug("remove", name,action)
del self._actions[name]
del action
for instance,variables in self._variables.items():
for name, variable in variables.items():
del variables[name]
del variable
if variables.has_key(instance):
del variables[instance]
del variables
del self
def get_device(self):
return self.device
def get_type(self):
return self.service_type
def set_timeout(self, timeout):
self.info("set timout for %s/%s to %d" %(self.device.friendly_name,self.service_type,int(timeout)))
self.timeout = timeout
try:
self.renew_subscription_call.reset(int(self.timeout)-30)
self.info("reset renew subscription call for %s/%s to %d" % (self.device.friendly_name,self.service_type,int(self.timeout)-30))
except:
self.renew_subscription_call = reactor.callLater(int(self.timeout)-30,
self.renew_subscription)
self.info("starting renew subscription call for %s/%s to %d" % (self.device.friendly_name,self.service_type,int(self.timeout)-30))
def get_timeout(self):
return self.timeout
def get_id(self):
return self.id
def get_sid(self):
return self.subscription_id
def set_sid(self, sid):
self.info("set subscription id for %s/%s to %s" %(self.device.friendly_name,self.service_type,sid))
self.subscription_id = sid
if sid is not None:
subscribe(self)
self.debug("add subscription for %s", self.id)
def get_actions(self):
return self._actions
def get_scpdXML(self):
return self.scpdXML
def get_action( self, name):
try:
return self._actions[name]
except KeyError:
return None # not implemented
def get_state_variables(self, instance):
return self._variables.get(int(instance))
def get_state_variable(self, name, instance=0):
return self._variables.get(int(instance)).get(name)
def get_control_url(self):
return self.device.make_fullyqualified(self.control_url)
def get_event_sub_url(self):
return self.device.make_fullyqualified(self.event_sub_url)
def get_presentation_url(self):
return self.device.make_fullyqualified(self.presentation_url)
def get_scpd_url(self):
return self.device.make_fullyqualified(self.scpd_url)
def get_base_url(self):
return self.device.make_fullyqualified('.')
def subscribe(self):
self.debug("subscribe %s", self.id)
event.subscribe(self)
#global subscribers
#subscribers[self.get_sid()] = self
def unsubscribe(self):
def remove_it(r, sid):
self.debug("remove subscription for %s", self.id)
unsubscribe(self)
self.subscription_id = None
#global subscribers
#if subscribers.has_key(sid):
# del subscribers[sid]
self.debug("unsubscribe %s", self.id)
d = event.unsubscribe(self)
d.addCallback(remove_it, self.get_sid())
return d
def subscribe_for_variable(self, var_name, instance=0, callback=None, signal=False):
variable = self.get_state_variable(var_name)
if variable:
if callback != None:
if signal == True:
callback(variable)
louie.connect(callback, signal='Coherence.UPnP.StateVariable.%s.changed' % var_name, sender=self)
else:
variable.subscribe(callback)
def renew_subscription(self):
self.info("renew_subscription")
event.subscribe(self)
def process_event(self,event):
self.info("process event %r %r" % (self,event))
for var_name, var_value in event.items():
if var_name == 'LastChange':
self.info("we have a LastChange event")
self.get_state_variable(var_name, 0).update(var_value)
if len(var_value) == 0:
continue
tree = utils.parse_xml(var_value, 'utf-8').getroot()
namespace_uri, tag = tree.tag[1:].split( "}", 1)
for instance in tree.findall('{%s}InstanceID' % namespace_uri):
instance_id = instance.attrib['val']
self.info("instance_id %r %r" % (instance,instance_id))
for var in instance.getchildren():
self.info("var %r" % var)
namespace_uri, tag = var.tag[1:].split("}", 1)
self.info("%r %r %r" % (namespace_uri, tag,var.attrib['val']))
self.get_state_variable(tag, instance_id).update(var.attrib['val'])
self.info("updated var %r" % var)
if len(var.attrib) > 1:
self.info("Extended StateVariable %s - %r", var.tag, var.attrib)
if var.attrib.has_key('channel') and var.attrib['channel'] != 'Master':
# TODO handle attributes that them selves have multiple instances
self.info("Skipping update to %s its not for master channel %s", var.tag, var.attrib)
pass
else:
if not self.get_state_variables(instance_id):
# TODO Create instance ?
self.error("%r update failed (not self.get_state_variables(instance_id)) %r", self, instance_id)
elif not self.get_state_variables(instance_id).has_key(tag):
# TODO Create instance StateVariable?
# SONOS stuff
self.error("%r update failed (not self.get_state_variables(instance_id).has_key(tag)) %r", self, tag)
else:
val = None
if var.attrib.has_key('val'):
val = var.attrib['val']
#self.debug("%r update %r %r %r", self,namespace_uri, tag, var.attrib['val'])
self.get_state_variable(tag, instance_id).update(var.attrib['val'])
self.debug("updated 'attributed' var %r", var)
louie.send('Coherence.UPnP.DeviceClient.Service.Event.processed',None,self,(var_name,var_value,event.raw))
else:
self.get_state_variable(var_name, 0).update(var_value)
louie.send('Coherence.UPnP.DeviceClient.Service.Event.processed',None,self,(var_name,var_value,event.raw))
if self.last_time_updated == None:
# The clients (e.g. media_server_client) check for last time to detect whether service detection is complete
# so we need to set it here and now to avoid a potential race condition
self.last_time_updated = time.time()
louie.send('Coherence.UPnP.DeviceClient.Service.notified', sender=self.device, service=self)
self.info("send signal Coherence.UPnP.DeviceClient.Service.notified for %r" % self)
self.last_time_updated = time.time()
def parse_actions(self):
def gotPage(x):
#print "gotPage"
#print x
self.scpdXML, headers = x
try:
tree = utils.parse_xml(self.scpdXML, 'utf-8').getroot()
ns = "urn:schemas-upnp-org:service-1-0"
for action_node in tree.findall('.//{%s}action' % ns):
name = action_node.findtext('{%s}name' % ns)
arguments = []
for argument in action_node.findall('.//{%s}argument' % ns):
arg_name = argument.findtext('{%s}name' % ns)
arg_direction = argument.findtext('{%s}direction' % ns)
arg_state_var = argument.findtext('{%s}relatedStateVariable' % ns)
arguments.append(action.Argument(arg_name, arg_direction,
arg_state_var))
self._actions[name] = action.Action(self, name, 'n/a', arguments)
for var_node in tree.findall('.//{%s}stateVariable' % ns):
send_events = var_node.attrib.get('sendEvents','yes')
name = var_node.findtext('{%s}name' % ns)
data_type = var_node.findtext('{%s}dataType' % ns)
values = []
""" we need to ignore this, as there we don't get there our
{urn:schemas-beebits-net:service-1-0}X_withVendorDefines
attibute there
"""
for allowed in var_node.findall('.//{%s}allowedValue' % ns):
values.append(allowed.text)
instance = 0
self._variables.get(instance)[name] = variable.StateVariable(self, name,
'n/a',
instance, send_events,
data_type, values)
""" we need to do this here, as there we don't get there our
{urn:schemas-beebits-net:service-1-0}X_withVendorDefines
attibute there
"""
self._variables.get(instance)[name].has_vendor_values = True
except Exception as e:
self.warning("error parsing service xml, service skipped!", e)
#print 'service parse:', self, self.device
self.detection_completed = True
self.process_event({}) #process_event will set self.last_time_updated which is in return checked by the clients to ensure service detection has completed
louie.send('Coherence.UPnP.Service.detection_completed', sender=self.device, device=self.device)
self.info("send signal Coherence.UPnP.Service.detection_completed for %r" % self)
def gotError(failure, url):
self.warning('error requesting', url)
self.info('failure', failure)
louie.send('Coherence.UPnP.Service.detection_failed', self.device, device=self.device)
#print 'getPage', self.get_scpd_url()
utils.getPage(self.get_scpd_url()).addCallbacks(gotPage, gotError, None, None, [self.get_scpd_url()], None)
moderated_variables = \
{'urn:schemas-upnp-org:service:AVTransport:2':
['LastChange'],
'urn:schemas-upnp-org:service:AVTransport:1':
['LastChange'],
'urn:schemas-upnp-org:service:ContentDirectory:2':
['SystemUpdateID', 'ContainerUpdateIDs'],
'urn:schemas-upnp-org:service:ContentDirectory:1':
['SystemUpdateID', 'ContainerUpdateIDs'],
'urn:schemas-upnp-org:service:RenderingControl:2':
['LastChange'],
'urn:schemas-upnp-org:service:RenderingControl:1':
['LastChange'],
'urn:schemas-upnp-org:service:ScheduledRecording:1':
['LastChange'],
}
class ServiceServer(log.Loggable):
logCategory = 'service_server'
def __init__(self, id, version, backend):
self.id = id
self.version = version
self.backend = backend
if getattr(self, "namespace", None) == None:
self.namespace = 'schemas-upnp-org'
if getattr(self, "id_namespace", None) == None:
self.id_namespace = 'upnp-org'
self.service_type = 'urn:%s:service:%s:%d' % (self.namespace, id, int(self.version))
self.scpd_url = 'scpd.xml'
self.control_url = 'control'
self.subscription_url = 'subscribe'
self.event_metadata = ''
if id == 'AVTransport':
self.event_metadata = 'urn:schemas-upnp-org:metadata-1-0/AVT/'
if id == 'RenderingControl':
self.event_metadata = 'urn:schemas-upnp-org:metadata-1-0/RCS/'
if id == 'ScheduledRecording':
self.event_metadata = 'urn:schemas-upnp-org:av:srs-event'
self._actions = {}
self._variables = {0: {}}
self._subscribers = {}
self._pending_notifications = {}
self.last_change = None
self.init_var_and_actions()
try:
if 'LastChange' in moderated_variables[self.service_type]:
self.last_change = self._variables[0]['LastChange']
except:
pass
self.putChild(self.subscription_url, EventSubscriptionServer(self))
self.check_subscribers_loop = task.LoopingCall(self.check_subscribers)
self.check_subscribers_loop.start(120.0, now=False)
self.check_moderated_loop = None
if moderated_variables.has_key(self.service_type):
self.check_moderated_loop = task.LoopingCall(self.check_moderated_variables)
#self.check_moderated_loop.start(5.0, now=False)
self.check_moderated_loop.start(0.5, now=False)
def _release(self):
for p in self._pending_notifications.values():
p.disconnect()
self._pending_notifications = {}
def get_action(self, action_name):
try:
return self._actions[action_name]
except KeyError:
return None # not implemented
def get_actions(self):
return self._actions
def get_variables(self):
return self._variables
def get_subscribers(self):
return self._subscribers
def rm_notification(self,result,d):
del self._pending_notifications[d]
def new_subscriber(self, subscriber):
notify = []
for vdict in self._variables.values():
notify += [v for v in vdict.values() if v.send_events == True]
self.info("new_subscriber", subscriber, notify)
if len(notify) <= 0:
return
root = ET.Element('e:propertyset')
root.attrib['xmlns:e']='urn:schemas-upnp-org:event-1-0'
evented_variables = 0
for n in notify:
e = ET.SubElement( root, 'e:property')
if n.name == 'LastChange':
if subscriber['seq'] == 0:
text = self.build_last_change_event(n.instance, force=True)
else:
text = self.build_last_change_event(n.instance)
if text is not None:
ET.SubElement( e, n.name).text = text
evented_variables += 1
else:
ET.SubElement( e, n.name).text = str(n.value)
evented_variables += 1
if evented_variables > 0:
xml = ET.tostring( root, encoding='utf-8')
d,p = event.send_notification(subscriber, xml)
self._pending_notifications[d] = p
d.addBoth(self.rm_notification,d)
self._subscribers[subscriber['sid']] = subscriber
def get_id(self):
return self.id
def get_type(self):
return self.service_type
def create_new_instance(self, instance):
self._variables[instance] = {}
for v in self._variables[0].values():
self._variables[instance][v.name] = variable.StateVariable( v.service,
v.name,
v.implementation,
instance,
v.send_events,
v.data_type,
v.allowed_values)
self._variables[instance][v.name].has_vendor_values = v.has_vendor_values
self._variables[instance][v.name].default_value = v.default_value
#self._variables[instance][v.name].value = v.default_value # FIXME
self._variables[instance][v.name].old_value = v.old_value
self._variables[instance][v.name].value = v.value
self._variables[instance][v.name].dependant_variable = v.dependant_variable
def remove_instance(self, instance):
if instance == 0:
return
del(self._variables[instance])
def set_variable(self, instance, variable_name, value, default=False):
def process_value(result):
variable.update(result)
if default == True:
variable.default_value = variable.value
if(variable.send_events == True and
variable.moderated == False and
len(self._subscribers) > 0):
xml = self.build_single_notification(instance, variable_name, variable.value)
for s in self._subscribers.values():
d,p = event.send_notification(s, xml)
self._pending_notifications[d] = p
d.addBoth(self.rm_notification,d)
try:
variable = self._variables[int(instance)][variable_name]
if isinstance( value, defer.Deferred):
value.addCallback(process_value)
else:
process_value(value)
except:
pass
def get_variable(self, variable_name, instance=0):
try:
return self._variables[int(instance)][variable_name]
except:
return None
def build_single_notification(self, instance, variable_name, value):
root = ET.Element('e:propertyset')
root.attrib['xmlns:e']='urn:schemas-upnp-org:event-1-0'
e = ET.SubElement( root, 'e:property')
s = ET.SubElement( e, variable_name).text = str(value)
return ET.tostring( root, encoding='utf-8')
def build_last_change_event(self, instance=0, force=False):
got_one = False
root = ET.Element('Event')
root.attrib['xmlns']=self.event_metadata
for instance, vdict in self._variables.items():
e = ET.SubElement( root, 'InstanceID')
e.attrib['val']=str(instance)
for variable in vdict.values():
if( variable.name != 'LastChange' and
variable.name[0:11] != 'A_ARG_TYPE_' and
variable.never_evented == False and
(variable.updated == True or force == True)):
s = ET.SubElement( e, variable.name)
s.attrib['val'] = str(variable.value)
variable.updated = False
got_one = True
if variable.dependant_variable != None:
dependants = variable.dependant_variable.get_allowed_values()
if dependants != None and len(dependants) > 0:
s.attrib['channel']=dependants[0]
if got_one == True:
return ET.tostring( root, encoding='utf-8')
else:
return None
def propagate_notification(self, notify):
#print "propagate_notification", notify
if len(self._subscribers) <= 0:
return
if len(notify) <= 0:
return
root = ET.Element('e:propertyset')
root.attrib['xmlns:e']='urn:schemas-upnp-org:event-1-0'
if isinstance( notify, variable.StateVariable):
notify = [notify,]
evented_variables = 0
for n in notify:
e = ET.SubElement( root, 'e:property')
if n.name == 'LastChange':
text = self.build_last_change_event(instance=n.instance)
if text is not None:
ET.SubElement( e, n.name).text = text
evented_variables += 1
else:
s = ET.SubElement( e, n.name).text = str(n.value)
evented_variables += 1
if n.dependant_variable != None:
dependants = n.dependant_variable.get_allowed_values()
if dependants != None and len(dependants) > 0:
s.attrib['channel']=dependants[0]
if evented_variables == 0:
return
xml = ET.tostring( root, encoding='utf-8')
#print "propagate_notification", xml
for s in self._subscribers.values():
d,p = event.send_notification(s,xml)
self._pending_notifications[d] = p
d.addBoth(self.rm_notification,d)
def check_subscribers(self):
for s in self._subscribers.values():
timeout = 86400
#print s
timeout = s['timeout']
if s['timeout'].endswith("infinite"):
timeout = time.time() + 1800
elif s['timeout'].startswith('Second-'):
timeout = int(timeout[len('Second-'):])
if time.time() > s['created'] + timeout:
del s
def check_moderated_variables(self):
#print "check_moderated for %s" % self.id
#print self._subscribers
if len(self._subscribers) <= 0:
return
variables = moderated_variables[self.get_type()]
notify = []
for v in variables:
#print self._variables[0][v].name, self._variables[0][v].updated
for vdict in self._variables.values():
if vdict[v].updated == True:
vdict[v].updated = False
notify.append(vdict[v])
self.propagate_notification(notify)
def is_variable_moderated(self, name):
try:
variables = moderated_variables[self.get_type()]
if name in variables:
return True
except:
pass
return False
def simulate_notification(self):
print "simulate_notification for", self.id
self.set_variable(0, 'CurrentConnectionIDs', '0')
def get_scpdXML(self):
if not hasattr(self,'scpdXML') or self.scpdXML == None:
self.scpdXML = scpdXML(self)
self.scpdXML = self.scpdXML.build_xml()
return self.scpdXML
def register_vendor_variable(self,name,implementation='optional',
instance=0, evented='no',
data_type='string',
dependant_variable=None,
default_value=None,
allowed_values=None,has_vendor_values=False,allowed_value_range=None,
moderated=False):
"""
enables a backend to add an own, vendor defined, StateVariable to the service
@ivar name: the name of the new StateVariable
@ivar implementation: either 'optional' or 'required'
@ivar instance: the instance number of the service that variable should be assigned to, usually '0'
@ivar evented: boolean, or the special keyword 'never' if the variable doesn't show up in a LastChange event too
@ivar data_type: 'string','boolean','bin.base64' or various number formats
@ivar dependant_variable: the name of another StateVariable that depends on this one
@ivar default_value: the value this StateVariable should have by default when created
for another instance of in the service
@ivar allowed_values: a C{list} of values this StateVariable can have
@ivar has_vendor_values: boolean if there are values outside the allowed_values list too
@ivar allowed_value_range: a C{dict} of 'minimum','maximum' and 'step' values
@ivar moderated: boolean, True if this StateVariable should only be evented via a LastChange event
"""
# FIXME
# we should raise an Exception when there as a StateVariable with that name already
if evented == 'never':
send_events = 'no'
else:
send_events = evented
new_variable = variable.StateVariable(self,name,implementation,instance,send_events,
data_type,allowed_values)
if default_value == None:
new_variable.default_value = ''
else:
new_variable.default_value = new_variable.old_value = new_variable.value = default_value
new_variable.dependant_variable = dependant_variable
new_variable.has_vendor_values = has_vendor_values
new_variable.allowed_value_range = allowed_value_range
new_variable.moderated = moderated
if evented == 'never':
new_variable.never_evented = True
self._variables.get(instance)[name] = new_variable
return new_variable
def register_vendor_action(self,name,implementation,arguments=None,needs_callback=True):
"""
enables a backend to add an own, vendor defined, Action to the service
@ivar name: the name of the new Action
@ivar implementation: either 'optional' or 'required'
@ivar arguments: a C{list} if argument C{tuples},
like (name,direction,relatedStateVariable)
@ivar needs_callback: this Action needs a method in the backend or service class
"""
# FIXME
# we should raise an Exception when there as an Action with that name already
# we should raise an Exception when there is no related StateVariable for an Argument
""" check for action in backend """
callback = getattr(self.backend, "upnp_%s" % name, None)
if callback == None:
""" check for action in ServiceServer """
callback = getattr(self, "upnp_%s" % name, None)
if( needs_callback == True and
callback == None):
""" we have one or more 'A_ARG_TYPE_' variables
issue a warning for now
"""
if implementation == 'optional':
self.info('%s has a missing callback for %s action %s, action disabled' % (self.id,implementation,name))
return
else:
if((hasattr(self,'implementation') and self.implementation == 'required') or
not hasattr(self,'implementation')):
self.warning('%s has a missing callback for %s action %s, service disabled' % (self.id,implementation,name))
raise LookupError("missing callback")
arguments_list = []
for argument in arguments:
arguments_list.append(action.Argument(argument[0],argument[1].lower(),argument[2]))
new_action = action.Action(self, name, implementation, arguments_list)
self._actions[name] = new_action
if callback != None:
new_action.set_callback(callback)
self.info('Add callback %s for %s/%s' % (callback, self.id, name))
return new_action
def init_var_and_actions(self):
desc_file = util.sibpath(__file__, os.path.join('xml-service-descriptions', '%s%d.xml' % (self.id, int(self.version))))
tree = ET.parse(desc_file)
for action_node in tree.findall('.//action'):
name = action_node.findtext('name')
implementation = 'required'
needs_callback = False
if action_node.attrib.get('{urn:schemas-beebits-net:service-1-0}X_needs_backend',
None) != None:
needs_callback = True
if action_node.find('Optional') != None:
implementation = 'optional'
if(action_node.find('Optional').attrib.get(
'{urn:schemas-beebits-net:service-1-0}X_needs_backend',
None) != None or
action_node.attrib.get('{urn:schemas-beebits-net:service-1-0}X_needs_backend',
None) != None):
needs_callback = True
arguments = []
for argument in action_node.findall('.//argument'):
arg_name = argument.findtext('name')
arg_direction = argument.findtext('direction')
arg_state_var = argument.findtext('relatedStateVariable')
arguments.append(action.Argument(arg_name, arg_direction,
arg_state_var))
if( arg_state_var[0:11] == 'A_ARG_TYPE_' and
arg_direction == 'out'):
needs_callback = True
#print arg_name, arg_direction, needs_callback
""" check for action in backend """
callback = getattr(self.backend, "upnp_%s" % name, None)
if callback == None:
""" check for action in ServiceServer """
callback = getattr(self, "upnp_%s" % name, None)
if( needs_callback == True and
callback == None):
""" we have one or more 'A_ARG_TYPE_' variables
issue a warning for now
"""
if implementation == 'optional':
self.info('%s has a missing callback for %s action %s, action disabled' % (self.id,implementation,name))
continue
else:
if((hasattr(self,'implementation') and self.implementation == 'required') or
not hasattr(self,'implementation')):
self.warning('%s has a missing callback for %s action %s, service disabled' % (self.id,implementation,name))
raise LookupError,"missing callback"
new_action = action.Action(self, name, implementation, arguments)
self._actions[name] = new_action
if callback != None:
new_action.set_callback(callback)
self.info('Add callback %s for %s/%s' % (callback, self.id, name))
backend_vendor_value_defaults = getattr(self.backend, "vendor_value_defaults", None)
service_value_defaults = None
if backend_vendor_value_defaults:
service_value_defaults = backend_vendor_value_defaults.get(self.id,None)
backend_vendor_range_defaults = getattr(self.backend, "vendor_range_defaults", None)
service_range_defaults = None
if backend_vendor_range_defaults:
service_range_defaults = backend_vendor_range_defaults.get(self.id)
for var_node in tree.findall('.//stateVariable'):
instance = 0
name = var_node.findtext('name')
implementation = 'required'
if action_node.find('Optional') != None:
implementation = 'optional'
#if implementation == 'optional':
# for action_object in self._actions.values():
# if name in [a.get_state_variable() for a in action_object.arguments_list]:
# break
# else:
# continue
send_events = var_node.findtext('sendEventsAttribute')
data_type = var_node.findtext('dataType')
values = []
for allowed in var_node.findall('.//allowedValue'):
values.append(allowed.text)
self._variables.get(instance)[name] = variable.StateVariable(self, name,
implementation,
instance, send_events,
data_type, values)
dependant_variable = var_node.findtext('{urn:schemas-beebits-net:service-1-0}X_dependantVariable')
if dependant_variable:
self._variables.get(instance)[name].dependant_variable = dependant_variable
default_value = var_node.findtext('defaultValue')
if default_value:
self._variables.get(instance)[name].set_default_value(default_value)
if var_node.find('sendEventsAttribute') != None:
never_evented = var_node.find('sendEventsAttribute').attrib.get(
'{urn:schemas-beebits-net:service-1-0}X_no_means_never',
None)
if never_evented is not None:
self._variables.get(instance)[name].set_never_evented(never_evented)
allowed_value_list = var_node.find('allowedValueList')
if allowed_value_list != None:
vendor_values = allowed_value_list.attrib.get(
'{urn:schemas-beebits-net:service-1-0}X_withVendorDefines',
None)
if service_value_defaults:
variable_value_defaults = service_value_defaults.get(name, None)
if variable_value_defaults:
self.info("overwriting %s default value with %s" % (name,
variable_value_defaults))
self._variables.get(instance)[name].set_allowed_values(variable_value_defaults)
if vendor_values != None:
self._variables.get(instance)[name].has_vendor_values = True
allowed_value_range = var_node.find('allowedValueRange')
if allowed_value_range:
vendor_values = allowed_value_range.attrib.get(
'{urn:schemas-beebits-net:service-1-0}X_withVendorDefines',
None)
range = {}
for e in list(allowed_value_range):
range[e.tag] = e.text
if( vendor_values != None):
if service_range_defaults:
variable_range_defaults = service_range_defaults.get(name)
if( variable_range_defaults != None and
variable_range_defaults.get(e.tag) != None):
self.info("overwriting %s attribute %s with %s" % (name,
e.tag, str(variable_range_defaults[e.tag])))
range[e.tag] = variable_range_defaults[e.tag]
elif e.text == None:
self.info("missing vendor definition for %s, attribute %s" % (name, e.tag))
self._variables.get(instance)[name].set_allowed_value_range(**range)
if vendor_values != None:
self._variables.get(instance)[name].has_vendor_values = True
elif service_range_defaults:
variable_range_defaults = service_range_defaults.get(name)
if variable_range_defaults != None:
self._variables.get(instance)[name].set_allowed_value_range(**variable_range_defaults)
self._variables.get(instance)[name].has_vendor_values = True
for v in self._variables.get(0).values():
if isinstance( v.dependant_variable, str):
v.dependant_variable = self._variables.get(instance).get(v.dependant_variable)
class scpdXML(static.Data):
def __init__(self, server, control=None):
self.service_server = server
self.control = control
static.Data.__init__(self, None, 'text/xml')
def render(self, request):
if self.data == None:
self.data = self.build_xml()
return static.Data.render(self,request)
def build_xml(self):
root = ET.Element('scpd')
root.attrib['xmlns']='urn:schemas-upnp-org:service-1-0'
e = ET.SubElement(root, 'specVersion')
ET.SubElement( e, 'major').text = '1'
ET.SubElement( e, 'minor').text = '0'
e = ET.SubElement( root, 'actionList')
for action in self.service_server._actions.values():
s = ET.SubElement( e, 'action')
ET.SubElement( s, 'name').text = action.get_name()
al = ET.SubElement( s, 'argumentList')
for argument in action.get_arguments_list():
a = ET.SubElement( al, 'argument')
ET.SubElement( a, 'name').text = argument.get_name()
ET.SubElement( a, 'direction').text = argument.get_direction()
ET.SubElement( a, 'relatedStateVariable').text = argument.get_state_variable()
e = ET.SubElement( root, 'serviceStateTable')
for var in self.service_server._variables[0].values():
s = ET.SubElement( e, 'stateVariable')
if var.send_events == True:
s.attrib['sendEvents'] = 'yes'
else:
s.attrib['sendEvents'] = 'no'
ET.SubElement( s, 'name').text = var.name
ET.SubElement( s, 'dataType').text = var.data_type
if(not var.has_vendor_values and len(var.allowed_values)):
#if len(var.allowed_values):
v = ET.SubElement( s, 'allowedValueList')
for value in var.allowed_values:
ET.SubElement( v, 'allowedValue').text = value
if( var.allowed_value_range != None and
len(var.allowed_value_range) > 0):
complete = True
for name,value in var.allowed_value_range.items():
if value == None:
complete = False
if complete == True:
avl = ET.SubElement( s, 'allowedValueRange')
for name,value in var.allowed_value_range.items():
if value != None:
ET.SubElement( avl, name).text = str(value)
return """<?xml version="1.0" encoding="utf-8"?>""" + ET.tostring( root, encoding='utf-8')
from twisted.python.util import OrderedDict
class ServiceControl:
def get_action_results(self, result, action, instance):
""" check for out arguments
if yes: check if there are related ones to StateVariables with
non A_ARG_TYPE_ prefix
if yes: check if there is a call plugin method for this action
if yes: update StateVariable values with call result
if no: get StateVariable values and
add them to result dict
"""
self.debug('get_action_results', result)
#print 'get_action_results', action, instance
r = result
notify = []
for argument in action.get_out_arguments():
#print 'get_state_variable_contents', argument.name
if argument.name[0:11] != 'A_ARG_TYPE_':
if action.get_callback() != None:
variable = self.variables[instance][argument.get_state_variable()]
variable.update(r[argument.name])
#print 'update state variable contents', variable.name, variable.value, variable.send_events
if(variable.send_events == 'yes' and variable.moderated == False):
notify.append(variable)
else:
variable = self.variables[instance][argument.get_state_variable()]
#print 'get state variable contents', variable.name, variable.value
r[argument.name] = variable.value
#print "r", r
self.service.propagate_notification(notify)
#r= { '%sResponse'%action.name: r}
self.info( 'action_results unsorted', action.name, r)
if len(r) == 0:
return r
ordered_result = OrderedDict()
for argument in action.get_out_arguments():
ordered_result[argument.name] = r[argument.name]
self.info( 'action_results sorted', action.name, ordered_result)
return ordered_result
def soap__generic(self, *args, **kwargs):
""" generic UPnP service control method,
which will be used if no soap_ACTIONNAME method
in the server service control class can be found
"""
try:
action = self.actions[kwargs['soap_methodName']]
except:
return failure.Failure(errorCode(401))
try:
instance = int(kwargs['InstanceID'])
except:
instance = 0
self.info("soap__generic", action, __name__, kwargs)
del kwargs['soap_methodName']
if( kwargs.has_key('X_UPnPClient') and
kwargs['X_UPnPClient'] == 'XBox'):
if(action.name == 'Browse' and
kwargs.has_key('ContainerID')):
""" XXX: THIS IS SICK """
kwargs['ObjectID'] = kwargs['ContainerID']
del kwargs['ContainerID']
in_arguments = action.get_in_arguments()
for arg_name, arg in kwargs.iteritems():
if arg_name.find('X_') == 0:
continue
l = [ a for a in in_arguments if arg_name == a.get_name()]
if len(l) > 0:
in_arguments.remove(l[0])
else:
self.critical('argument %s not valid for action %s' % (arg_name,action.name))
return failure.Failure(errorCode(402))
if len(in_arguments) > 0:
self.critical('argument %s missing for action %s' %
([ a.get_name() for a in in_arguments],action.name))
return failure.Failure(errorCode(402))
def callit( *args, **kwargs):
#print 'callit args', args
#print 'callit kwargs', kwargs
result = {}
callback = action.get_callback()
if callback != None:
return callback( **kwargs)
return result
def got_error(x):
#print 'failure', x
self.info('soap__generic error during call processing')
return x
# call plugin method for this action
d = defer.maybeDeferred( callit, *args, **kwargs)
d.addCallback( self.get_action_results, action, instance)
d.addErrback(got_error)
return d
| [] |
2024-01-10 | opendreambox/python-coherence | misc~media_server_observer.py |
from twisted.internet import reactor
from coherence.base import Coherence
from coherence.upnp.devices.control_point import ControlPoint
from coherence.upnp.core import DIDLLite
# browse callback
def process_media_server_browse(result, client):
print "browsing root of", client.device.get_friendly_name()
print "result contains %d out of %d total matches" % \
(int(result['NumberReturned']), int(result['TotalMatches']))
elt = DIDLLite.DIDLElement.fromString(result['Result'])
for item in elt.getItems():
if item.upnp_class.startswith("object.container"):
print " container %s (%s) with %d items" % \
(item.title,item.id, item.childCount)
if item.upnp_class.startswith("object.item"):
print " item %s (%s)" % (item.title, item.id)
# called for each media server found
def media_server_found(client, udn):
print "media_server_found", client
print "media_server_found", client.device.get_friendly_name()
d = client.content_directory.browse(0,
browse_flag='BrowseDirectChildren', process_result=False,
backward_compatibility=False)
d.addCallback(process_media_server_browse, client)
# sadly they sometimes get removed as well :(
def media_server_removed(udn):
print "media_server_removed", udn
def start():
control_point = ControlPoint(Coherence({'logmode':'warning'}),
auto_client=['MediaServer'])
control_point.connect(media_server_found,
'Coherence.UPnP.ControlPoint.MediaServer.detected')
control_point.connect(media_server_removed,
'Coherence.UPnP.ControlPoint.MediaServer.removed')
# now we should also try to discover the ones that are already there:
for device in control_point.coherence.devices:
print device
if __name__ == "__main__":
reactor.callWhenRunning(start)
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~lastfm_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
"""
INFO lastFM_user Dez 14 17:35:27 Got new sessionid: '1488f34a1cbed7c9f4232f8fd563c3bd' (coherence/backends/lastfm_storage.py:60)
DEBUG lastFM_stream Dez 14 17:35:53 render <GET /da525474-5357-4d1b-a894-76b1293224c9/1005 HTTP/1.1> (coherence/backends/lastfm_storage.py:148)
command GET
rest /user/e0362c757ef49169e9a0f0970cc2d367.mp3
headers {'icy-metadata': '1', 'host': 'kingpin5.last.fm', 'te': 'trailers', 'connection': 'TE', 'user-agent': 'gnome-vfs/2.12.0.19 neon/0.24.7'}
ProxyClient handleStatus HTTP/1.1 200 OK
ProxyClient handleHeader Content-Type audio/mpeg
ProxyClient handleHeader Content-Length 4050441
ProxyClient handleHeader Cache-Control no-cache, must-revalidate
DEBUG lastFM_stream Dez 14 17:35:53 render <GET /da525474-5357-4d1b-a894-76b1293224c9/1005 HTTP/1.1> (coherence/backends/lastfm_storage.py:148)
command GET
rest /user/e0362c757ef49169e9a0f0970cc2d367.mp3
headers {'icy-metadata': '1', 'host': 'kingpin5.last.fm', 'te': 'trailers', 'connection': 'TE', 'user-agent': 'gnome-vfs/2.12.0.19 neon/0.24.7'}
ProxyClient handleStatus HTTP/1.1 403 Invalid ticket
"""
# Copyright 2007, Frank Scholz <[email protected]>
# Copyright 2007, Moritz Struebe <[email protected]>
from twisted.internet import defer
from coherence.upnp.core import utils
from coherence.upnp.core.DIDLLite import classChooser, Container, Resource, DIDLElement
import coherence.extern.louie as louie
from coherence.extern.simple_plugin import Plugin
from coherence import log
from coherence.backend import BackendItem, BackendStore
from urlparse import urlsplit
try:
from hashlib import md5
except ImportError:
# hashlib is new in Python 2.5
from md5 import md5
import string
class LastFMUser(log.Loggable):
logCategory = 'lastFM_user'
user = None
passwd = None
host = "ws.audioscrobbler.com"
basepath = "/radio"
sessionid = None
parent = None
getting_tracks = False
tracks = []
def __init__(self, user, passwd):
if user is None:
self.warn("No User",)
if passwd is None:
self.warn("No Passwd",)
self.user = user
self.passwd = passwd
def login(self):
if self.sessionid != None:
self.warning("Session seems to be valid",)
return
def got_page(result):
lines = result[0].split("\n")
for line in lines:
tuple = line.rstrip().split("=", 1)
if len(tuple) == 2:
if tuple[0] == "session":
self.sessionid = tuple[1]
self.info("Got new sessionid: %r",self.sessionid )
if tuple[0] == "base_url":
if(self.host != tuple[1]):
self.host = tuple[1]
self.info("Got new host: %s",self.host )
if tuple[0] == "base_path":
if(self.basepath != tuple[1]):
self.basepath = tuple[1]
self.info("Got new path: %s",self.basepath)
self.get_tracks()
def got_error(error):
self.warning("Login to LastFM Failed! %r", error)
self.debug("%r", error.getTraceback())
def hexify(s): # This function might be GPL! Found this code in some other Projects, too.
result = ""
for c in s:
result = result + ("%02x" % ord(c))
return result
password = hexify(md5(self.passwd).digest())
req = self.basepath + "/handshake.php/?version=1&platform=win&username=" + self.user + "&passwordmd5=" + password + "&language=en&player=coherence"
utils.getPage("http://" + self.host + req).addCallbacks(got_page, got_error, None, None, None, None)
def get_tracks(self):
if self.getting_tracks == True:
return
def got_page(result):
result = utils.parse_xml(result, encoding='utf-8')
self.getting_tracks = False
print self.getting_tracks
print "got Tracks"
for track in result.findall('trackList/track'):
data = {}
def get_data(name):
#print track.find(name).text.encode('utf-8')
return track.find(name).text.encode('utf-8')
#Fixme: This section needs some work
print "adding Track"
data['mimetype'] = 'audio/mpeg'
data['name'] =get_data('creator') + " - " + get_data('title')
data['title'] = get_data('title')
data['artist'] = get_data('creator')
data['creator'] = get_data('creator')
data['album'] = get_data('album')
data['duration'] = get_data('duration')
#FIXME: Image is the wrong tag.
data['image'] =get_data('image')
data['url'] = track.find('location').text.encode('utf-8')
item = self.parent.store.append(data, self.parent)
self.tracks.append(item)
def got_error(error):
self.warning("Problem getting Tracks! %r", error)
self.debug("%r", error.getTraceback())
self.getting_tracks = False
self.getting_tracks = True
req = self.basepath + "/xspf.php?sk=" + self.sessionid + "&discovery=0&desktop=1.3.1.1"
utils.getPage("http://" + self.host + req).addCallbacks(got_page, got_error, None, None, None, None)
def update(self, item):
if 0 < self.tracks.count(item):
while True:
track = self.tracks[0]
if track == item:
break
self.tracks.remove(track)
# Do not remoce so the tracks to answer the browse
# request correctly.
#track.store.remove(track)
#del track
#if len(self.tracks) < 5:
self.get_tracks()
class LFMProxyStream(utils.ReverseProxyResource,log.Loggable):
logCategory = 'lastFM_stream'
def __init__(self, uri, parent):
self.uri = uri
self.parent = parent
_,host_port,path,_,_ = urlsplit(uri)
if host_port.find(':') != -1:
host,port = tuple(host_port.split(':'))
port = int(port)
else:
host = host_port
port = 80
if path == '':
path = '/'
#print "ProxyStream init", host, port, path
utils.ReverseProxyResource.__init__(self, host, port, path)
def render(self, request):
self.debug("render %r", request)
self.parent.store.LFM.update(self.parent)
self.parent.played = True
return utils.ReverseProxyResource.render(self, request)
class LastFMItem(log.Loggable):
logCategory = 'LastFM_item'
def __init__(self, id, obj, parent, mimetype, urlbase, UPnPClass,update=False):
self.id = id
self.name = obj.get('name')
self.title = obj.get('title')
self.artist = obj.get('artist')
self.creator = obj.get('creator')
self.album = obj.get('album')
self.duration = obj.get('duration')
self.mimetype = mimetype
self.parent = parent
if parent:
parent.add_child(self,update=update)
if parent == None:
parent_id = -1
else:
parent_id = parent.get_id()
self.item = UPnPClass(id, parent_id, self.title,False ,self.creator)
if isinstance(self.item, Container):
self.item.childCount = 0
self.child_count = 0
self.children = []
if( len(urlbase) and urlbase[-1] != '/'):
urlbase += '/'
if self.mimetype == 'directory':
self.url = urlbase + str(self.id)
else:
self.url = urlbase + str(self.id)
self.location = LFMProxyStream(obj.get('url'), self)
#self.url = obj.get('url')
if self.mimetype == 'directory':
self.update_id = 0
else:
res = Resource(self.url, 'http-get:*:%s:%s' % (obj.get('mimetype'),
';'.join(('DLNA.ORG_PN=MP3',
'DLNA.ORG_CI=0',
'DLNA.ORG_OP=01',
'DLNA.ORG_FLAGS=01700000000000000000000000000000'))))
res.size = -1 #None
self.item.res.append(res)
def remove(self):
if self.parent:
self.parent.remove_child(self)
del self.item
def add_child(self, child, update=False):
if self.children == None:
self.children = []
self.children.append(child)
self.child_count += 1
if isinstance(self.item, Container):
self.item.childCount += 1
if update == True:
self.update_id += 1
def remove_child(self, child):
self.info("remove_from %d (%s) child %d (%s)" % (self.id, self.get_name(), child.id, child.get_name()))
if child in self.children:
self.child_count -= 1
if isinstance(self.item, Container):
self.item.childCount -= 1
self.children.remove(child)
self.update_id += 1
def get_children(self,start=0,request_count=0):
if request_count == 0:
return self.children[start:]
else:
return self.children[start:request_count]
def get_child_count(self):
if self.mimetype == 'directory':
return 100 #Some Testing, with strange Numbers: 0/lots
return self.child_count
def get_id(self):
return self.id
def get_update_id(self):
if hasattr(self, 'update_id'):
return self.update_id
else:
return None
def get_path(self):
return self.url
def get_name(self):
return self.name
def get_parent(self):
return self.parent
def get_item(self):
return self.item
def get_xml(self):
return self.item.toString()
def __repr__(self):
return 'id: ' + str(self.id) + ' @ ' + self.url + ' ' + self.name
class LastFMStore(log.Loggable,Plugin):
logCategory = 'lastFM_store'
implements = ['MediaServer']
def __init__(self, server, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.next_id = 1000
self.config = kwargs
self.name = kwargs.get('name','LastFMStore')
self.update_id = 0
self.store = {}
self.wmc_mapping = {'4': 1000}
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
def __repr__(self):
return str(self.__class__).split('.')[-1]
def append( self, obj, parent):
if isinstance(obj, basestring):
mimetype = 'directory'
else:
mimetype = obj['mimetype']
UPnPClass = classChooser(mimetype)
id = self.getnextID()
update = False
if hasattr(self, 'update_id'):
update = True
self.store[id] = LastFMItem( id, obj, parent, mimetype, self.urlbase,
UPnPClass, update=update)
self.store[id].store = self
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
if parent:
#value = '%d,%d' % (parent.get_id(),parent_get_update_id())
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
return self.store[id]
def remove(self, item):
try:
parent = item.get_parent()
item.remove()
del self.store[int(id)]
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
#value = '%d,%d' % (parent.get_id(),parent_get_update_id())
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
except:
pass
def len(self):
return len(self.store)
def get_by_id(self,id):
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
id = int(id)
if id == 0:
id = 1000
try:
return self.store[id]
except:
return None
def getnextID(self):
ret = self.next_id
self.next_id += 1
return ret
def upnp_init(self):
self.current_connection_id = None
parent = self.append({'name':'LastFM','mimetype':'directory'}, None)
self.LFM = LastFMUser(self.config.get("login"), self.config.get("password"))
self.LFM.parent = parent
self.LFM.login()
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
['http-get:*:audio/mpeg:*'],
default=True)
def main():
f = LastFMStore(None)
def got_upnp_result(result):
print "upnp", result
f.upnp_init()
if __name__ == '__main__':
from twisted.internet import reactor
reactor.callWhenRunning(main)
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~extern~telepathy~mirabeau_tube_consumer.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2009 Philippe Normand <[email protected]>
from dbus import PROPERTIES_IFACE
from telepathy.interfaces import CHANNEL_TYPE_DBUS_TUBE, CONN_INTERFACE, \
CHANNEL_INTERFACE, CHANNEL_INTERFACE_TUBE, CONNECTION
from coherence.extern.telepathy import client, tube
from coherence.dbus_constants import BUS_NAME, OBJECT_PATH, DEVICE_IFACE, SERVICE_IFACE
from coherence import dbus_service
class MirabeauTubeConsumerMixin(tube.TubeConsumerMixin):
def __init__(self, found_peer_callback=None, disapeared_peer_callback=None,
got_devices_callback=None):
tube.TubeConsumerMixin.__init__(self,
found_peer_callback=found_peer_callback,
disapeared_peer_callback=disapeared_peer_callback)
self.got_devices_callback = got_devices_callback
self.info("MirabeauTubeConsumer created")
self._coherence_tubes = {}
def pre_accept_tube(self, tube):
params = tube[PROPERTIES_IFACE].Get(CHANNEL_INTERFACE_TUBE, 'Parameters')
initiator = params.get("initiator")
for group in ("publish", "subscribe"):
try:
contacts = self.roster[group]
except KeyError:
self.debug("Group %r not in roster...", group)
continue
for contact_handle, contact in contacts.iteritems():
if contact[CONNECTION + "/contact-id"] == initiator:
return True
return False
def post_tube_accept(self, tube, tube_conn, initiator_handle):
service = tube.props[CHANNEL_TYPE_DBUS_TUBE + ".ServiceName"]
if service == BUS_NAME:
tube.remote_object = dbus_service.DBusPontoon(None, tube_conn)
elif service == DEVICE_IFACE:
tube.remote_object = dbus_service.DBusDevice(None, tube_conn)
elif service == SERVICE_IFACE:
tube.remote_object = dbus_service.DBusService(None, None, tube_conn)
else:
self.info("tube %r is not coming from Coherence", service)
return tube_conn
if initiator_handle not in self._coherence_tubes:
self._coherence_tubes[initiator_handle] = {}
self._coherence_tubes[initiator_handle][service] = tube
if len(self._coherence_tubes[initiator_handle]) == 3:
self.announce(initiator_handle)
def tube_closed(self, tube):
self.disapeared_peer_callback(tube)
super(MirabeauTubeConsumerMixin, self).tube_closed(tube)
def announce(self, initiator_handle):
service_name = BUS_NAME
pontoon_tube = self._coherence_tubes[initiator_handle][service_name]
def cb(participants, removed):
if participants and initiator_handle in participants:
initiator_bus_name = participants[initiator_handle]
self.info("bus name %r for service %r", initiator_bus_name,
service_name)
if initiator_bus_name is not None:
self.found_devices(initiator_handle, initiator_bus_name)
for handle in removed:
try:
tube_channels = self._coherence_tubes[handle]
except KeyError:
self.debug("tube with handle %d not registered", handle)
else:
for service_iface_name, channel in tube_channels.iteritems():
channel[CHANNEL_INTERFACE].Close()
del self._coherence_tubes[handle]
pontoon_tube.remote_object.tube.watch_participants(cb)
def found_devices(self, initiator_handle, initiator_bus_name):
devices = []
tubes = self._coherence_tubes[initiator_handle]
pontoon_tube = tubes[BUS_NAME].remote_object.tube
device_tube = tubes[DEVICE_IFACE].remote_object.tube
service_tube = tubes[SERVICE_IFACE].remote_object.tube
self.info("using pontoon tube at %r", tubes[BUS_NAME].object_path)
def got_devices(pontoon_devices):
self.info("%r devices registered in remote pontoon", len(pontoon_devices))
for device_dict in pontoon_devices:
device_path = device_dict["path"]
self.info("getting object at %r from %r", device_path,
initiator_bus_name)
proxy = device_tube.get_object(initiator_bus_name, device_path)
infos = proxy.get_info(dbus_interface=DEVICE_IFACE)
service_proxies = []
for service_path in device_dict["services"]:
service_proxy = service_tube.get_object(initiator_bus_name,
service_path)
service_proxies.append(service_proxy)
proxy.services = service_proxies
devices.append(proxy)
self.got_devices_callback(devices)
def got_error(exception):
print ">>>", exception
pontoon = pontoon_tube.get_object(initiator_bus_name, OBJECT_PATH)
pontoon.get_devices_async(1, reply_handler=got_devices,
error_handler=got_error)
class MirabeauTubeConsumer(MirabeauTubeConsumerMixin, client.Client):
logCategory = "mirabeau_tube_consumer"
def __init__(self, manager, protocol, account, muc_id, conference_server,
found_peer_callback=None, disapeared_peer_callback=None,
got_devices_callback=None):
MirabeauTubeConsumerMixin.__init__(self,
found_peer_callback=found_peer_callback,
disapeared_peer_callback=disapeared_peer_callback,
got_devices_callback=got_devices_callback)
client.Client.__init__(self, manager, protocol, account, muc_id, conference_server)
def got_tube(self, tube):
client.Client.got_tube(self, tube)
self.accept_tube(tube)
def tube_opened(self, tube):
tube_conn = super(MirabeauTubePublisherConsumer, self).tube_opened(tube)
self.post_tube_accept(tube, tube_conn)
return tube_conn
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~services~clients~content_directory_client.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006, Frank Scholz <[email protected]>
import sys, threading
from twisted.internet import reactor, defer
from twisted.python import log
from coherence.upnp.core import DIDLLite
from coherence.upnp.core import utils
global work, pending
work = []
pending = {}
class ContentDirectoryClient:
def __init__(self, service):
self.service = service
self.namespace = service.get_type()
self.url = service.get_control_url()
self.service.subscribe()
self.service.client = self
#print "ContentDirectoryClient __init__", self.url
#def __del__(self):
# print "ContentDirectoryClient deleted"
# pass
def remove(self):
self.service.remove()
self.service = None
self.namespace = None
self.url = None
del self
def subscribe_for_variable(self, var_name, callback,signal=False):
self.service.subscribe_for_variable(var_name, instance=0, callback=callback,signal=signal)
def get_search_capabilities(self):
action = self.service.get_action('GetSearchCapabilities')
return action.call()
def get_sort_extension_capabilities(self):
action = self.service.get_action('GetSortExtensionCapabilities')
return action.call()
def get_feature_list(self):
action = self.service.get_action('GetFeatureList')
return action.call()
def get_system_update_id(self):
action = self.service.get_action('GetSystemUpdateID')
return action.call()
def browse(self, object_id=0, browse_flag='BrowseDirectChildren',
filter='*', sort_criteria='',
starting_index=0, requested_count=0,
process_result=True,
backward_compatibility=False):
def got_result(results):
items = []
if results is not None:
elt = DIDLLite.DIDLElement.fromString(results['Result'])
items = elt.getItems()
return items
def got_process_result(result):
#print result
r = {}
r['number_returned'] = result['NumberReturned']
r['total_matches'] = result['TotalMatches']
r['update_id'] = result['UpdateID']
r['items'] = {}
elt = DIDLLite.DIDLElement.fromString(result['Result'])
for item in elt.getItems():
#print "process_result", item
i = {}
i['upnp_class'] = item.upnp_class
i['id'] = item.id
i['title'] = item.title
i['parent_id'] = item.parentID
if hasattr(item,'childCount'):
i['child_count'] = str(item.childCount)
if hasattr(item,'date') and item.date:
i['date'] = item.date
if hasattr(item,'album') and item.album:
i['album'] = item.album
if hasattr(item,'artist') and item.artist:
i['artist'] = item.artist
if hasattr(item,'albumArtURI') and item.albumArtURI:
i['album_art_uri'] = item.albumArtURI
if hasattr(item,'res'):
resources = {}
for res in item.res:
url = res.data
resources[url] = res.protocolInfo
if len(resources):
i['resources']= resources
r['items'][item.id] = i
return r
action = self.service.get_action('Browse')
d = action.call( ObjectID=object_id,
BrowseFlag=browse_flag,
Filter=filter,SortCriteria=sort_criteria,
StartingIndex=str(starting_index),
RequestedCount=str(requested_count))
if process_result in [True,1,'1','true','True','yes','Yes']:
d.addCallback(got_process_result)
#else:
# d.addCallback(got_result)
return d
def search(self, container_id, criteria, starting_index=0,
requested_count=0):
#print "search:", criteria
starting_index = str(starting_index)
requested_count = str(requested_count)
action = self.service.get_action('Search')
if action == None:
return None
d = action.call( ContainerID=container_id,
SearchCriteria=criteria,
Filter="*",
StartingIndex=starting_index,
RequestedCount=requested_count,
SortCriteria="")
d.addErrback(self._failure)
def gotResults(results):
items = []
if results is not None:
elt = DIDLLite.DIDLElement.fromString(results['Result'])
items = elt.getItems()
return items
d.addCallback(gotResults)
return d
def dict2item(self, elements):
upnp_class = DIDLLite.upnp_classes.get(elements.get('upnp_class',None),None)
if upnp_class is None:
return None
del elements['upnp_class']
item = upnp_class(id='',
parentID=elements.get('parentID',None),
title=elements.get('title',None),
restricted=elements.get('restricted',None))
for k, v in elements.items():
attribute = getattr(item, k, None)
if attribute is None:
continue
attribute = v
return item
def create_object(self, container_id, elements):
if isinstance(elements, dict):
elements = self.dict2item(elements)
if isinstance(elements,DIDLLite.Object):
didl = DIDLLite.DIDLElement()
didl.addItem(elements)
elements=didl.toString()
if elements is None:
elements = ''
action = self.service.get_action('CreateObject')
if action: # optional
return action.call( ContainerID=container_id,
Elements=elements)
return None
def destroy_object(self, object_id):
action = self.service.get_action('DestroyObject')
if action: # optional
return action.call( ObjectID=object_id)
return None
def update_object(self, object_id, current_tag_value, new_tag_value):
action = self.service.get_action('UpdateObject')
if action: # optional
return action.call( ObjectID=object_id,
CurrentTagValue=current_tag_value,
NewTagValue=new_tag_value)
return None
def move_object(self, object_id, new_parent_id):
action = self.service.get_action('MoveObject')
if action: # optional
return action.call( ObjectID=object_id,
NewParentID=new_parent_id)
return None
def import_resource(self, source_uri, destination_uri):
action = self.service.get_action('ImportResource')
if action: # optional
return action.call( SourceURI=source_uri,
DestinationURI=destination_uri)
return None
def export_resource(self, source_uri, destination_uri):
action = self.service.get_action('ExportResource')
if action: # optional
return action.call( SourceURI=source_uri,
DestinationURI=destination_uri)
return None
def delete_resource(self, resource_uri):
action = self.service.get_action('DeleteResource')
if action: # optional
return action.call( ResourceURI=resource_uri)
return None
def stop_transfer_resource(self, transfer_id):
action = self.service.get_action('StopTransferResource')
if action: # optional
return action.call( TransferID=transfer_id)
return None
def get_transfer_progress(self, transfer_id):
action = self.service.get_action('GetTransferProgress')
if action: # optional
return action.call( TransferID=transfer_id)
return None
def create_reference(self, container_id, object_id):
action = self.service.get_action('CreateReference')
if action: # optional
return action.call( ContainerID=container_id,
ObjectID=object_id)
return None
def _failure(self, error):
log.msg(error.getTraceback(), debug=True)
error.trap(Exception)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~ted_storage.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Benjamin Kampmann <[email protected]>
"""
Another simple rss based Media Server, this time for TED.com content
"""
# I can reuse stuff. cool. But that also means we might want to refactor it into
# a base class to reuse
from coherence.backends.lolcats_storage import LolcatsStore
from coherence.backends.appletrailers_storage import Container
from coherence.backend import BackendItem
from coherence.upnp.core import DIDLLite
class TedTalk(BackendItem):
def __init__(self, parent_id, id, title=None, url=None,
duration=None, size=None):
self.parentid = parent_id
self.update_id = 0
self.id = id
self.location = url
self.name = title
self.item = DIDLLite.VideoItem(id, parent_id, self.name)
res = DIDLLite.Resource(self.location, 'http-get:*:video/mp4:*') # FIXME should be video/x-m4a
res.size = size
res.duration = duration
self.item.res.append(res)
class TEDStore(LolcatsStore):
implements = ['MediaServer']
rss_url = "http://feeds.feedburner.com/tedtalks_video?format=xml"
ROOT_ID = 0
def __init__(self, server, *args, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.name = kwargs.get('name', 'TEDtalks')
self.refresh = int(kwargs.get('refresh', 1)) * (60 *60)
self.next_id = 1001
self.last_updated = None
self.container = Container(None, self.ROOT_ID, self.name)
self.videos = {}
dfr = self.update_data()
dfr.addCallback(self.init_completed)
def get_by_id(self, id):
if int(id) == self.ROOT_ID:
return self.container
return self.videos.get(int(id), None)
def upnp_init(self):
if self.server:
self.server.connection_manager_server.set_variable( \
0, 'SourceProtocolInfo', ['http-get:*:video/mp4:*'])
def parse_data(self, xml_data):
root = xml_data.getroot()
pub_date = root.find('./channel/lastBuildDate').text
if pub_date == self.last_updated:
return
self.last_updated = pub_date
self.container.children = []
self.videos = {}
# FIXME: move these to generic constants somewhere
mrss = './{http://search.yahoo.com/mrss/}'
itunes = './{http://www.itunes.com/dtds/podcast-1.0.dtd}'
url_item = mrss + 'content'
duration = itunes + 'duration'
summary = itunes + 'summary'
for item in root.findall('./channel/item'):
data = {}
data['parent_id'] = self.ROOT_ID
data['id'] = self.next_id
data['title'] = item.find('./title').text.replace('TEDTalks : ', '')
# data ['summary'] = item.find(summary).text
# data ['duration'] = item.find(duration).text
try:
media_entry = item.find(url_item)
data['url'] = media_entry.get('url', None)
data['size'] = media_entry.get('size', None)
except IndexError:
continue
video = TedTalk(**data)
self.container.children.append(video)
self.videos[self.next_id] = video
self.next_id += 1
self.container.update_id += 1
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
value = (self.ROOT_ID,self.container.update_id)
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~picasa_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2009, Jean-Michel Sizun
# Copyright 2009 Frank Scholz <[email protected]>
import os.path
import time
from twisted.internet import threads
from twisted.web import server, static
from twisted.web.error import PageRedirect
from coherence.upnp.core.utils import ReverseProxyUriResource
from twisted.internet import task
from coherence.upnp.core import utils
from coherence.upnp.core import DIDLLite
from coherence.backend import BackendStore, BackendItem, Container, LazyContainer, \
AbstractBackendStore
from coherence import log
from urlparse import urlsplit
import gdata.photos.service
import gdata.media
import gdata.geo
class PicasaProxy(ReverseProxyUriResource):
def __init__(self, uri):
ReverseProxyUriResource.__init__(self, uri)
def render(self, request):
if request.responseHeaders.has_key('referer'):
del request.responseHeaders['referer']
return ReverseProxyUriResource.render(self, request)
class PicasaPhotoItem(BackendItem):
def __init__(self, photo):
#print photo
self.photo = photo
self.name = photo.summary.text
if self.name is None:
self.name = photo.title.text
self.duration = None
self.size = None
self.mimetype = photo.content.type
self.description = photo.summary.text
self.date = None
self.item = None
self.photo_url = photo.content.src
self.thumbnail_url = photo.media.thumbnail[0].url
self.url = None
self.location = PicasaProxy(self.photo_url)
def replace_by(self, item):
#print photo
self.photo = item.photo
self.name = photo.summary.text
if self.name is None:
self.name = photo.title.text
self.mimetype = self.photo.content.type
self.description = self.photo.summary.text
self.photo_url = self.photo.content.src
self.thumbnail_url = self.photo.media.thumbnail[0].url
self.location = PicasaProxy(self.photo_url)
return True
def get_item(self):
if self.item == None:
upnp_id = self.get_id()
upnp_parent_id = self.parent.get_id()
self.item = DIDLLite.Photo(upnp_id,upnp_parent_id,self.name)
res = DIDLLite.Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
self.item.res.append(res)
self.item.childCount = 0
return self.item
def get_path(self):
return self.url
def get_id(self):
return self.storage_id
class PicasaStore(AbstractBackendStore):
logCategory = 'picasa_store'
implements = ['MediaServer']
description = ('Picasa Web Albums', 'connects to the Picasa Web Albums service and exposes the featured photos and albums for a given user.', None)
options = [{'option':'name', 'text':'Server Name:', 'type':'string','default':'my media','help': 'the name under this MediaServer shall show up with on other UPnP clients'},
{'option':'version','text':'UPnP Version:','type':'int','default':2,'enum': (2,1),'help': 'the highest UPnP version this MediaServer shall support','level':'advance'},
{'option':'uuid','text':'UUID Identifier:','type':'string','help':'the unique (UPnP) identifier for this MediaServer, usually automatically set','level':'advance'},
{'option':'refresh','text':'Refresh period','type':'string'},
{'option':'login','text':'User ID:','type':'string','group':'User Account'},
{'option':'password','text':'Password:','type':'string','group':'User Account'},
]
def __init__(self, server, **kwargs):
AbstractBackendStore.__init__(self, server, **kwargs)
self.name = kwargs.get('name','Picasa Web Albums')
self.refresh = int(kwargs.get('refresh',60))*60
self.login = kwargs.get('userid',kwargs.get('login',''))
self.password = kwargs.get('password','')
rootContainer = Container(None, self.name)
self.set_root_item(rootContainer)
self.AlbumsContainer = LazyContainer(rootContainer, 'My Albums', None, self.refresh, self.retrieveAlbums)
rootContainer.add_child(self.AlbumsContainer)
self.FeaturedContainer = LazyContainer(rootContainer, 'Featured photos', None, self.refresh, self.retrieveFeaturedPhotos)
rootContainer.add_child(self.FeaturedContainer)
self.init_completed()
def __repr__(self):
return self.__class__.__name__
def upnp_init(self):
self.current_connection_id = None
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_SM;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_MED;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_LRG;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
'http-get:*:image/jpeg:*,'
'http-get:*:image/gif:*,'
'http-get:*:image/png:*',
default=True)
self.wmc_mapping = {'16': self.get_root_id()}
self.gd_client = gdata.photos.service.PhotosService()
self.gd_client.email = self.login
self.gd_client.password = self.password
self.gd_client.source = 'Coherence UPnP backend'
if len(self.login) > 0:
d = threads.deferToThread(self.gd_client.ProgrammaticLogin)
def retrieveAlbums(self, parent=None):
albums = threads.deferToThread(self.gd_client.GetUserFeed)
def gotAlbums(albums):
if albums is None:
print "Unable to retrieve albums"
return
for album in albums.entry:
title = album.title.text
album_id = album.gphoto_id.text
item = LazyContainer(parent, title, album_id, self.refresh, self.retrieveAlbumPhotos, album_id=album_id)
parent.add_child(item, external_id=album_id)
def gotError(error):
print "ERROR: %s" % error
albums.addCallbacks(gotAlbums, gotError)
return albums
def retrieveFeedPhotos (self, parent=None, feed_uri=''):
#print feed_uri
photos = threads.deferToThread(self.gd_client.GetFeed, feed_uri)
def gotPhotos(photos):
if photos is None:
print "Unable to retrieve photos for feed %s" % feed_uri
return
for photo in photos.entry:
photo_id = photo.gphoto_id.text
item = PicasaPhotoItem(photo)
item.parent = parent
parent.add_child(item, external_id=photo_id)
def gotError(error):
print "ERROR: %s" % error
photos.addCallbacks(gotPhotos, gotError)
return photos
def retrieveAlbumPhotos (self, parent=None, album_id=''):
album_feed_uri = '/data/feed/api/user/%s/albumid/%s?kind=photo' % (self.login, album_id)
return self.retrieveFeedPhotos(parent, album_feed_uri)
def retrieveFeaturedPhotos (self, parent=None):
feed_uri = 'http://picasaweb.google.com/data/feed/api/featured'
return self.retrieveFeedPhotos(parent, feed_uri)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~devices~media_renderer_client.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006, Frank Scholz <[email protected]>
from coherence.upnp.services.clients.connection_manager_client import ConnectionManagerClient
from coherence.upnp.services.clients.rendering_control_client import RenderingControlClient
from coherence.upnp.services.clients.av_transport_client import AVTransportClient
from coherence import log
import coherence.extern.louie as louie
class MediaRendererClient(log.Loggable):
logCategory = 'mr_client'
def __init__(self, device):
self.device = device
self.device_type = self.device.get_friendly_device_type()
self.version = int(self.device.get_device_type_version())
self.icons = device.icons
self.rendering_control = None
self.connection_manager = None
self.av_transport = None
self.detection_completed = False
louie.connect(self.service_notified, signal='Coherence.UPnP.DeviceClient.Service.notified', sender=self.device)
for service in self.device.get_services():
if service.get_type() in ["urn:schemas-upnp-org:service:RenderingControl:1",
"urn:schemas-upnp-org:service:RenderingControl:2"]:
self.rendering_control = RenderingControlClient( service)
if service.get_type() in ["urn:schemas-upnp-org:service:ConnectionManager:1",
"urn:schemas-upnp-org:service:ConnectionManager:2"]:
self.connection_manager = ConnectionManagerClient( service)
if service.get_type() in ["urn:schemas-upnp-org:service:AVTransport:1",
"urn:schemas-upnp-org:service:AVTransport:2"]:
self.av_transport = AVTransportClient( service)
self.info("MediaRenderer %s" % (self.device.get_friendly_name()))
if self.rendering_control:
self.info("RenderingControl available")
"""
actions = self.rendering_control.service.get_actions()
print actions
for action in actions:
print "Action:", action
for arg in actions[action].get_arguments_list():
print " ", arg
"""
#self.rendering_control.list_presets()
#self.rendering_control.get_mute()
#self.rendering_control.get_volume()
#self.rendering_control.set_mute(desired_mute=1)
else:
self.warning("RenderingControl not available, device not implemented properly according to the UPnP specification")
return
if self.connection_manager:
self.info("ConnectionManager available")
#self.connection_manager.get_protocol_info()
else:
self.warning("ConnectionManager not available, device not implemented properly according to the UPnP specification")
return
if self.av_transport:
self.info("AVTransport (optional) available")
#self.av_transport.service.subscribe_for_variable('LastChange', 0, self.state_variable_change)
#self.av_transport.service.subscribe_for_variable('TransportState', 0, self.state_variable_change)
#self.av_transport.service.subscribe_for_variable('CurrentTransportActions', 0, self.state_variable_change)
#self.av_transport.get_transport_info()
#self.av_transport.get_current_transport_actions()
#def __del__(self):
# #print "MediaRendererClient deleted"
# pass
def remove(self):
self.info("removal of MediaRendererClient started")
if self.rendering_control != None:
self.rendering_control.remove()
if self.connection_manager != None:
self.connection_manager.remove()
if self.av_transport != None:
self.av_transport.remove()
#del self
def service_notified(self, service):
self.info("Service %r sent notification" % service);
if self.detection_completed == True:
return
if self.rendering_control != None:
if not hasattr(self.rendering_control.service, 'last_time_updated'):
return
if self.rendering_control.service.last_time_updated == None:
return
if self.connection_manager != None:
if not hasattr(self.connection_manager.service, 'last_time_updated'):
return
if self.connection_manager.service.last_time_updated == None:
return
if self.av_transport != None:
if not hasattr(self.av_transport.service, 'last_time_updated'):
return
if self.av_transport.service.last_time_updated == None:
return
self.detection_completed = True
louie.send('Coherence.UPnP.DeviceClient.detection_completed', None,
client=self,udn=self.device.udn)
def state_variable_change( self, variable):
self.info(variable.name, 'changed from', variable.old_value, 'to', variable.value)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~core~action.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006,2007,2008,2009 Frank Scholz <[email protected]>
from twisted.python import failure
from twisted.python.util import OrderedDict
from coherence import log
class Argument:
def __init__(self, name, direction, state_variable):
self.name = name
self.direction = direction
self.state_variable = state_variable
def get_name(self):
return self.name
def get_direction(self):
return self.direction
def get_state_variable(self):
return self.state_variable
def __repr__(self):
return "Argument: %s, %s, %s" % (self.get_name(),
self.get_direction(), self.get_state_variable())
def as_tuples(self):
r = []
r.append(('Name',self.name))
r.append(('Direction',self.direction))
r.append(('Related State Variable',self.state_variable))
return r
def as_dict(self):
return {'name':self.name,'direction':self.direction,'related_state_variable':self.state_variable}
class Action(log.Loggable):
logCategory = 'action'
def __init__(self, service, name, implementation, arguments_list):
self.service = service
self.name = name
self.implementation = implementation
self.arguments_list = arguments_list
def _get_client(self):
client = self.service._get_client( self.name)
return client
def get_name(self):
return self.name
def get_implementation(self):
return self.implementation
def get_arguments_list(self):
return self.arguments_list
def get_in_arguments(self):
return [arg for arg in self.arguments_list if arg.get_direction() == 'in']
def get_out_arguments(self):
return [arg for arg in self.arguments_list if arg.get_direction() == 'out']
def get_service(self):
return self.service
def set_callback(self, callback):
self.callback = callback
def get_callback(self):
try:
return self.callback
except:
return None
def call(self, *args, **kwargs):
self.info("calling", self.name)
in_arguments = self.get_in_arguments()
self.info("in arguments", [a.get_name() for a in in_arguments])
instance_id = 0
for arg_name, arg in kwargs.iteritems():
l = [ a for a in in_arguments if arg_name == a.get_name()]
if len(l) > 0:
in_arguments.remove(l[0])
else:
self.error("argument %s not valid for action %s" % (arg_name,self.name))
return
if arg_name == 'InstanceID':
instance_id = int(arg)
if len(in_arguments) > 0:
self.error("argument %s missing for action %s" % ([ a.get_name() for a in in_arguments],self.name))
return
action_name = self.name
if(hasattr(self.service.device.client, 'overlay_actions') and
self.service.device.client.overlay_actions.has_key(self.name)):
self.info("we have an overlay method %r for action %r", self.service.device.client.overlay_actions[self.name], self.name)
action_name, kwargs = self.service.device.client.overlay_actions[self.name](**kwargs)
self.info("changing action to %r %r", action_name, kwargs)
def got_error(failure):
self.warning("error on %s request with %s %s" % (self.name,self.
service.service_type,
self.service.control_url))
self.info(failure)
return failure
if hasattr(self.service.device.client, 'overlay_headers'):
self.info("action call has headers %r", kwargs.has_key('headers'))
if kwargs.has_key('headers'):
kwargs['headers'].update(self.service.device.client.overlay_headers)
else:
kwargs['headers'] = self.service.device.client.overlay_headers
self.info("action call with new/updated headers %r", kwargs['headers'])
client = self._get_client()
ordered_arguments = OrderedDict()
for argument in self.get_in_arguments():
ordered_arguments[argument.name] = kwargs[argument.name]
d = client.callRemote(action_name, ordered_arguments)
d.addCallback(self.got_results, instance_id=instance_id, name=action_name)
d.addErrback(got_error)
return d
def got_results( self, results, instance_id, name):
instance_id = int(instance_id)
out_arguments = self.get_out_arguments()
self.info( "call %s (instance %d) returns %d arguments: %r" % (name,
instance_id,
len(out_arguments),
results))
# XXX A_ARG_TYPE_ arguments probably don't need a variable update
#if len(out_arguments) == 1:
# self.service.get_state_variable(out_arguments[0].get_state_variable(), instance_id).update(results)
#elif len(out_arguments) > 1:
if len(out_arguments) > 0:
for arg_name, value in results.items():
state_variable_name = [a.get_state_variable() for a in out_arguments if a.get_name() == arg_name]
self.service.get_state_variable(state_variable_name[0], instance_id).update(value)
return results
def __repr__(self):
return "Action: %s [%s], (%s args)" % (self.get_name(), self.get_implementation(),
len(self.get_arguments_list()))
def as_tuples(self):
r = []
r.append(('Name',self.get_name()))
r.append(("Number of 'in' arguments",len(self.get_in_arguments())))
r.append(("Number of 'out' arguments",len(self.get_out_arguments())))
return r
def as_dict(self):
return {'name': self.get_name(),'arguments':[a.as_dict() for a in self.arguments_list]}
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~mirabeau.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2009 Philippe Normand <[email protected]>
from telepathy.interfaces import ACCOUNT_MANAGER, ACCOUNT
import dbus
from coherence.dbus_constants import BUS_NAME, DEVICE_IFACE, SERVICE_IFACE
from coherence.extern.telepathy.mirabeau_tube_publisher import MirabeauTubePublisherConsumer
from coherence.tube_service import TubeDeviceProxy
from coherence import log
from coherence.upnp.devices.control_point import ControlPoint
from twisted.internet import defer
class Mirabeau(log.Loggable):
logCategory = "mirabeau"
def __init__(self, config, coherence_instance):
log.Loggable.__init__(self)
self._tube_proxies = []
self._coherence = coherence_instance
chatroom = config['chatroom']
conference_server = config['account']['fallback-conference-server']
manager = config['manager']
protocol = config['protocol']
# account dict keys are different for each protocol so we
# assume the user gave the right account parameters depending
# on the specified protocol.
account = config['account']
if isinstance(account, basestring):
bus = dbus.SessionBus()
account = bus.get_object(ACCOUNT_MANAGER, account)
#account_obj = bus.get_object(ACCOUNT_MANAGER, account)
#account = account_obj.Get(ACCOUNT, 'Parameters')
try:
allowed_devices = config["allowed_devices"].split(",")
except KeyError:
allowed_devices = None
tubes_to_offer = {BUS_NAME: {}, DEVICE_IFACE: {}, SERVICE_IFACE: {}}
callbacks = dict(found_peer_callback=self.found_peer,
disapeared_peer_callback=self.disapeared_peer,
got_devices_callback=self.got_devices)
self.tube_publisher = MirabeauTubePublisherConsumer(manager, protocol,
account, chatroom,
conference_server,
tubes_to_offer,
self._coherence,
allowed_devices,
**callbacks)
# set external address to our hostname, if a IGD device is
# detected it means we are inside a LAN and the IGD will give
# us our real external address.
self._external_address = coherence_instance.hostname
self._external_port = 30020
self._portmapping_ready = False
control_point = self._coherence.ctrl
igd_signal_name = 'Coherence.UPnP.ControlPoint.InternetGatewayDevice'
control_point.connect(self._igd_found, '%s.detected' % igd_signal_name)
control_point.connect(self._igd_removed, '%s.removed' % igd_signal_name)
def _igd_found(self, client, udn):
print "IGD found", client.device.get_friendly_name()
device = client.wan_device.wan_connection_device
self._igd_service = device.wan_ppp_connection or device.wan_ip_connection
if self._igd_service:
self._igd_service.subscribe_for_variable('ExternalIPAddress',
callback=self.state_variable_change)
d = self._igd_service.get_all_port_mapping_entries()
d.addCallback(self._got_port_mappings)
def _got_port_mappings(self, mappings):
if mappings == None:
self.warning("Mappings changed during query, trying again...")
dfr = service.get_all_port_mapping_entries()
dfr.addCallback(self._got_port_mappings)
else:
description = "Coherence-Mirabeau"
for mapping in mappings:
if mapping["NewPortMappingDescription"] == description:
self.warning("UPnP port-mapping available")
self._portmapping_ready = (mapping["NewRemoteHost"],mapping["NewExternalPort"])
return None
internal_port = self._coherence.web_server_port
self._external_port = internal_port
internal_client = self._coherence.hostname
service = self._igd_service
dfr = service.add_port_mapping(remote_host='',
external_port=internal_port,
protocol='TCP',
internal_port=internal_port,
internal_client=internal_client,
enabled=True,
port_mapping_description=description,
lease_duration=0)
def mapping_ok(r,t):
self._portmapping_ready = t
self.warning("UPnP port-mapping succeeded")
return None
def mapping_failed(r):
self.warning("UPnP port-mapping failed")
return None
dfr.addCallback(mapping_ok,('',internal_port))
dfr.addErrback(mapping_failed)
return dfr
def state_variable_change(self, variable):
if variable.name == 'ExternalIPAddress':
print "our external IP address is %s" % variable.value
self._external_address = variable.value
def _igd_removed(self, udn):
self._igd_service = None
self._portmapping_ready = False
def found_peer(self, peer):
print "found", peer
def disapeared_peer(self, peer):
print "disapeared", peer
def got_devices(self, devices):
for device in devices:
uuid = device.get_id()
print "MIRABEAU found:", uuid
self._tube_proxies.append(TubeDeviceProxy(self._coherence, device,
self._external_address))
def start(self):
self.tube_publisher.start()
def stop(self):
control_point = self._coherence.ctrl
igd_signal_name = 'Coherence.UPnP.ControlPoint.InternetGatewayDevice'
control_point.disconnect(self._igd_found, '%s.detected' % igd_signal_name)
control_point.disconnect(self._igd_removed, '%s.removed' % igd_signal_name)
self.tube_publisher.stop()
if self._portmapping_ready:
remote_host,external_port = self._portmapping_ready
dfr = self._igd_service.delete_port_mapping(remote_host=remote_host,
external_port=external_port,
protocol='TCP')
return dfr
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~devices~dimmable_light_client.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
from coherence.upnp.services.clients.switch_power_client import SwitchPowerClient
from coherence.upnp.services.clients.dimming_client import DimmingClient
from coherence import log
import coherence.extern.louie as louie
class DimmableLightClient(log.Loggable):
logCategory = 'dimminglight_client'
def __init__(self, device):
self.device = device
self.device_type = self.device.get_friendly_device_type()
self.version = int(self.device.get_device_type_version())
self.icons = device.icons
self.switch_power = None
self.dimming = None
self.detection_completed = False
louie.connect(self.service_notified, signal='Coherence.UPnP.DeviceClient.Service.notified', sender=self.device)
for service in self.device.get_services():
if service.get_type() in ["urn:schemas-upnp-org:service:SwitchPower:1"]:
self.switch_power = SwitchPowerClient(service)
if service.get_type() in ["urn:schemas-upnp-org:service:Dimming:1"]:
self.dimming = DimmingClient(service)
self.info("DimmingLight %s" % (self.device.get_friendly_name()))
if self.switch_power:
self.info("SwitchPower service available")
else:
self.warning("SwitchPower service not available, device not implemented properly according to the UPnP specification")
return
if self.dimming:
self.info("Dimming service available")
else:
self.warning("Dimming service not available, device not implemented properly according to the UPnP specification")
def remove(self):
self.info("removal of DimmingLightClient started")
if self.dimming != None:
self.dimming.remove()
if self.switch_power != None:
self.switch_power.remove()
def service_notified(self, service):
self.info("Service %r sent notification" % service);
if self.detection_completed == True:
return
if self.switch_power != None:
if not hasattr(self.switch_power.service, 'last_time_updated'):
return
if self.switch_power.service.last_time_updated == None:
return
if self.dimming != None:
if not hasattr(self.dimming.service, 'last_time_updated'):
return
if self.dimming.service.last_time_updated == None:
return
self.detection_completed = True
louie.send('Coherence.UPnP.DeviceClient.detection_completed', None,
client=self,udn=self.device.udn)
def state_variable_change( self, variable):
self.info(variable.name, 'changed from', variable.old_value, 'to', variable.value)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~core~soap_proxy.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007 - Frank Scholz <[email protected]>
from twisted.python import failure
from coherence import log
from coherence.extern.et import ET, namespace_map_update
from coherence.upnp.core.utils import getPage, parse_xml
from coherence.upnp.core import soap_lite
class SOAPProxy(log.Loggable):
""" A Proxy for making remote SOAP calls.
Based upon twisted.web.soap.Proxy and
extracted to remove the SOAPpy dependency
Pass the URL of the remote SOAP server to the constructor.
Use proxy.callRemote('foobar', 1, 2) to call remote method
'foobar' with args 1 and 2, proxy.callRemote('foobar', x=1)
will call foobar with named argument 'x'.
"""
logCategory = 'soap'
def __init__(self, url, namespace=None, envelope_attrib=None, header=None, soapaction=None):
self.url = url
self.namespace = namespace
self.header = header
self.action = None
self.soapaction = soapaction
self.envelope_attrib = envelope_attrib
def callRemote(self, soapmethod, arguments):
soapaction = soapmethod or self.soapaction
if '#' not in soapaction:
soapaction = '#'.join((self.namespace[1],soapaction))
self.action = soapaction.split('#')[1]
self.info("callRemote %r %r %r %r", self.soapaction, soapmethod, self.namespace, self.action)
headers = { 'content-type': 'text/xml ;charset="utf-8"',
'SOAPACTION': '"%s"' % soapaction,}
if arguments.has_key('headers'):
headers.update(arguments['headers'])
del arguments['headers']
payload = soap_lite.build_soap_call("{%s}%s" % (self.namespace[1], self.action), arguments,
encoding=None)
self.info("callRemote soapaction: ", self.action,self.url)
self.debug("callRemote payload: ", payload)
def gotError(error, url):
self.warning("error requesting url %r" % url)
self.debug(error)
try:
tree = parse_xml(error.value.response)
body = tree.find('{http://schemas.xmlsoap.org/soap/envelope/}Body')
return failure.Failure(Exception("%s - %s" % (body.find('.//{urn:schemas-upnp-org:control-1-0}errorCode').text,
body.find('.//{urn:schemas-upnp-org:control-1-0}errorDescription').text)))
except:
import traceback
self.debug(traceback.format_exc())
return error
return getPage(self.url, postdata=payload, method="POST",
headers=headers
).addCallbacks(self._cbGotResult, gotError, None, None, [self.url], None)
def _cbGotResult(self, result):
#print "_cbGotResult 1", result
page, headers = result
#result = SOAPpy.parseSOAPRPC(page)
#print "_cbGotResult 2", result
def print_c(e):
for c in e.getchildren():
print c, c.tag
print_c(c)
self.debug("result: %r" % page)
tree = parse_xml(page)
#print tree, "find %s" % self.action
#root = tree.getroot()
#print_c(root)
body = tree.find('{http://schemas.xmlsoap.org/soap/envelope/}Body')
#print "body", body
response = body.find('{%s}%sResponse' % (self.namespace[1], self.action))
if response == None:
""" fallback for improper SOAP action responses """
response = body.find('%sResponse' % self.action)
self.debug("callRemote response ", response)
result = {}
if response != None:
for elem in response:
result[elem.tag] = self.decode_result(elem)
#print "_cbGotResult 3", result
return result
def decode_result(self, element):
type = element.get('{http://www.w3.org/1999/XMLSchema-instance}type')
if type is not None:
try:
prefix, local = type.split(":")
if prefix == 'xsd':
type = local
except ValueError:
pass
if type == "integer" or type == "int":
return int(element.text)
if type == "float" or type == "double":
return float(element.text)
if type == "boolean":
return element.text == "true"
return element.text or ""
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~core~utils.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006, Frank Scholz <[email protected]>
from os.path import abspath
import urlparse
from urlparse import urlsplit
from coherence.extern.et import parse_xml as et_parse_xml
from coherence import SERVER_ID
from twisted.web import server, http, static
from twisted.web import client, error
from twisted.web import proxy, resource, server
from twisted.internet import reactor,protocol,defer,abstract
from twisted.python import failure
from twisted.python.util import InsensitiveDict
try:
from twisted.protocols._c_urlarg import unquote
except ImportError:
from urllib import unquote
try:
import netifaces
have_netifaces = True
except ImportError:
have_netifaces = False
def means_true(value):
if isinstance(value,basestring):
value = value.lower()
return value in [True,1,'1','true','yes','ok']
def generalise_boolean(value):
""" standardize the different boolean incarnations
transform anything that looks like a "True" into a '1',
and everything else into a '0'
"""
if means_true(value):
return '1'
return '0'
generalize_boolean = generalise_boolean
def parse_xml(data, encoding="utf-8"):
return et_parse_xml(data,encoding)
def parse_http_response(data):
""" don't try to get the body, there are reponses without """
header = data.split('\r\n\r\n')[0]
lines = header.split('\r\n')
cmd = lines[0].split(' ')
lines = map(lambda x: x.replace(': ', ':', 1), lines[1:])
lines = filter(lambda x: len(x) > 0, lines)
headers = [x.split(':', 1) for x in lines]
headers = dict(map(lambda x: (x[0].lower(), x[1]), headers))
return cmd, headers
def get_ip_address(ifname):
"""
determine the IP address by interface name
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439094
(c) Paul Cannon
Uses the Linux SIOCGIFADDR ioctl to find the IP address associated
with a network interface, given the name of that interface, e.g. "eth0".
The address is returned as a string containing a dotted quad.
Updated to work on BSD. OpenBSD and OSX share the same value for
SIOCGIFADDR, and its likely that other BSDs do too.
Updated to work on Windows,
using the optional Python module netifaces
http://alastairs-place.net/netifaces/
Thx Lawrence for that patch!
"""
if have_netifaces:
if ifname in netifaces.interfaces():
iface = netifaces.ifaddresses(ifname)
ifaceadr = iface[netifaces.AF_INET]
# we now have a list of address dictionaries, there may be multiple addresses bound
return ifaceadr[0]['addr']
import sys
if sys.platform in ('win32','sunos5'):
return '127.0.0.1'
from os import uname
import socket
import fcntl
import struct
system_type = uname()[0]
if system_type == "Linux":
SIOCGIFADDR = 0x8915
else:
SIOCGIFADDR = 0xc0206921
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
SIOCGIFADDR,
struct.pack('256s', ifname[:15])
)[20:24])
except:
return '127.0.0.1'
def get_host_address():
""" try to get determine the interface used for
the default route, as this is most likely
the interface we should bind to (on a single homed host!)
"""
import sys
if sys.platform == 'win32':
if have_netifaces:
interfaces = netifaces.interfaces()
if len(interfaces):
return get_ip_address(interfaces[0]) # on windows assume first interface is primary
else:
try:
route_file = '/proc/net/route'
route = open(route_file)
if(route):
tmp = route.readline() #skip first line
while (tmp != ''):
tmp = route.readline()
l = tmp.split('\t')
if (len(l) > 2):
if l[1] == '00000000': #default route...
route.close()
return get_ip_address(l[0])
except IOError, msg:
""" fallback to parsing the output of netstat """
from twisted.internet import utils
def result(r):
from os import uname
(osname,_, _, _,_) = uname()
osname = osname.lower()
lines = r.split('\n')
for l in lines:
l = l.strip(' \r\n')
parts = [x.strip() for x in l.split(' ') if len(x) > 0]
if parts[0] in ('0.0.0.0','default'):
if osname[:6] == 'darwin':
return get_ip_address(parts[5])
else:
return get_ip_address(parts[-1])
return '127.0.0.1'
def fail(f):
return '127.0.0.1'
d = utils.getProcessOutput('netstat', ['-rn'])
d.addCallback(result)
d.addErrback(fail)
return d
except Exception, msg:
import traceback
traceback.print_exc()
""" return localhost if we haven't found anything """
return '127.0.0.1'
def de_chunk_payload(response):
try:
import cStringIO as StringIO
except ImportError:
import StringIO
""" This method takes a chunked HTTP data object and unchunks it."""
newresponse = StringIO.StringIO()
# chunked encoding consists of a bunch of lines with
# a length in hex followed by a data chunk and a CRLF pair.
response = StringIO.StringIO(response)
def read_chunk_length():
line = response.readline()
try:
len = int(line.strip(),16)
except ValueError:
len = 0
return len
len = read_chunk_length()
while (len > 0):
newresponse.write(response.read(len))
line = response.readline() # after chunk and before next chunk length
len = read_chunk_length()
return newresponse.getvalue()
class Request(server.Request):
def process(self):
"Process a request."
# get site from channel
self.site = self.channel.site
# set various default headers
self.setHeader('server', SERVER_ID)
self.setHeader('date', http.datetimeToString())
self.setHeader('content-type', "text/html")
# Resource Identification
url = self.path
#remove trailing "/", if ever
url = url.rstrip('/')
scheme, netloc, path, query, fragment = urlsplit(url)
self.prepath = []
if path == "":
self.postpath = []
else:
self.postpath = map(unquote, path[1:].split('/'))
try:
def deferred_rendering(r):
self.render(r)
try:
resrc = self.site.getResourceFor(self)
except:
resrc = None
if resrc is None:
self.setResponseCode(http.NOT_FOUND, "Error: No resource for path %s" % path)
self.finish()
elif isinstance(resrc, defer.Deferred):
resrc.addCallback(deferred_rendering)
resrc.addErrback(self.processingFailed)
else:
self.render(resrc)
except:
self.processingFailed(failure.Failure())
class Site(server.Site):
noisy = False
requestFactory = Request
def startFactory(self):
pass
#http._logDateTimeStart()
class ProxyClient(http.HTTPClient):
"""Used by ProxyClientFactory to implement a simple web proxy."""
def __init__(self, command, rest, version, headers, data, father):
self.father = father
self.command = command
self.rest = rest
if headers.has_key("proxy-connection"):
del headers["proxy-connection"]
#headers["connection"] = "close"
self.headers = headers
#print "command", command
#print "rest", rest
#print "headers", headers
self.data = data
self.send_data = 0
def connectionMade(self):
self.sendCommand(self.command, self.rest)
for header, value in self.headers.items():
self.sendHeader(header, value)
self.endHeaders()
self.transport.write(self.data)
def handleStatus(self, version, code, message):
if message:
# Add a whitespace to message, this allows empty messages
# transparently
message = " %s" % (message,)
if version == 'ICY':
version = 'HTTP/1.1'
#print "ProxyClient handleStatus", version, code, message
self.father.transport.write("%s %s %s\r\n" % (version, code, message))
def handleHeader(self, key, value):
#print "ProxyClient handleHeader", key, value
if not key.startswith('icy-'):
#print "ProxyClient handleHeader", key, value
self.father.transport.write("%s: %s\r\n" % (key, value))
def handleEndHeaders(self):
#self.father.transport.write("%s: %s\r\n" % ( 'Keep-Alive', ''))
#self.father.transport.write("%s: %s\r\n" % ( 'Accept-Ranges', 'bytes'))
#self.father.transport.write("%s: %s\r\n" % ( 'Content-Length', '2000000'))
#self.father.transport.write("%s: %s\r\n" % ( 'Date', 'Mon, 26 Nov 2007 11:04:12 GMT'))
#self.father.transport.write("%s: %s\r\n" % ( 'Last-Modified', 'Sun, 25 Nov 2007 23:19:51 GMT'))
##self.father.transport.write("%s: %s\r\n" % ( 'Server', 'Apache/2.0.52 (Red Hat)'))
self.father.transport.write("\r\n")
def handleResponsePart(self, buffer):
#print "ProxyClient handleResponsePart", len(buffer), self.father.chunked
self.send_data += len(buffer)
self.father.write(buffer)
def handleResponseEnd(self):
#print "handleResponseEnd", self.send_data
self.transport.loseConnection()
self.father.channel.transport.loseConnection()
class ProxyClientFactory(protocol.ClientFactory):
"""
Used by ProxyRequest to implement a simple web proxy.
"""
protocol = proxy.ProxyClient
def __init__(self, command, rest, version, headers, data, father):
self.father = father
self.command = command
self.rest = rest
self.headers = headers
self.data = data
self.version = version
def buildProtocol(self, addr):
return self.protocol(self.command, self.rest, self.version,
self.headers, self.data, self.father)
def clientConnectionFailed(self, connector, reason):
self.father.transport.write("HTTP/1.0 501 Gateway error\r\n")
self.father.transport.write("Content-Type: text/html\r\n")
self.father.transport.write("\r\n")
self.father.transport.write('''<H1>Could not connect</H1>''')
self.father.transport.loseConnection()
class ReverseProxyResource(proxy.ReverseProxyResource):
"""
Resource that renders the results gotten from another server
Put this resource in the tree to cause everything below it to be relayed
to a different server.
@ivar proxyClientFactoryClass: a proxy client factory class, used to create
new connections.
@type proxyClientFactoryClass: L{ClientFactory}
@ivar reactor: the reactor used to create connections.
@type reactor: object providing L{twisted.internet.interfaces.IReactorTCP}
"""
proxyClientFactoryClass = ProxyClientFactory
def __init__(self, host, port, path, reactor=reactor):
"""
@param host: the host of the web server to proxy.
@type host: C{str}
@param port: the port of the web server to proxy.
@type port: C{port}
@param path: the base path to fetch data from. Note that you shouldn't
put any trailing slashes in it, it will be added automatically in
request. For example, if you put B{/foo}, a request on B{/bar} will
be proxied to B{/foo/bar}.
@type path: C{str}
"""
resource.Resource.__init__(self)
self.host = host
self.port = port
self.path = path
self.qs = ''
self.reactor = reactor
def getChild(self, path, request):
return ReverseProxyResource(
self.host, self.port, self.path + '/' + path)
def render(self, request):
"""
Render a request by forwarding it to the proxied server.
"""
# RFC 2616 tells us that we can omit the port if it's the default port,
# but we have to provide it otherwise
if self.port == 80:
request.responseHeaders['host'] = self.host
else:
request.responseHeaders['host'] = "%s:%d" % (self.host, self.port)
request.content.seek(0, 0)
qs = urlparse.urlparse(request.uri)[4]
if qs == '':
qs = self.qs
if qs:
rest = self.path + '?' + qs
else:
rest = self.path
clientFactory = self.proxyClientFactoryClass(
request.method, rest, request.clientproto,
request.getAllHeaders(), request.content.read(), request)
self.reactor.connectTCP(self.host, self.port, clientFactory)
return server.NOT_DONE_YET
def resetTarget(self,host,port,path,qs=''):
self.host = host
self.port = port
self.path = path
self.qs = qs
class ReverseProxyUriResource(ReverseProxyResource):
uri = None
def __init__(self, uri, reactor=reactor):
self.uri = uri
_,host_port,path,params,_ = urlsplit(uri)
if host_port.find(':') != -1:
host,port = tuple(host_port.split(':'))
port = int(port)
else:
host = host_port
port = 80
if path =='':
path = '/'
if params == '':
rest = path
else:
rest = '?'.join((path, params))
ReverseProxyResource.__init__(self, host, port, rest, reactor)
def resetUri (self, uri):
self.uri = uri
_,host_port,path,params,_ = urlsplit(uri)
if host_port.find(':') != -1:
host,port = tuple(host_port.split(':'))
port = int(port)
else:
host = host_port
port = 80
self.resetTarget(host, port, path, params)
class myHTTPPageGetter(client.HTTPPageGetter):
followRedirect = True
def connectionMade(self):
method = getattr(self, 'method', 'GET')
#print "myHTTPPageGetter", method, self.factory.path
self.sendCommand(method, self.factory.path)
self.sendHeader('Host', self.factory.headers.get("host", self.factory.host))
self.sendHeader('User-Agent', self.factory.agent)
if self.factory.cookies:
l=[]
for cookie, cookval in self.factory.cookies.items():
l.append('%s=%s' % (cookie, cookval))
self.sendHeader('Cookie', '; '.join(l))
data = getattr(self.factory, 'postdata', None)
if data is not None:
self.sendHeader("Content-Length", str(len(data)))
for (key, value) in self.factory.headers.items():
if key.lower() != "content-length":
# we calculated it on our own
self.sendHeader(key, value)
self.endHeaders()
self.headers = {}
if data is not None:
self.transport.write(data)
def handleResponse(self, response):
if self.quietLoss:
return
if self.failed:
self.factory.noPage(
failure.Failure(
error.Error(
self.status, self.message, response)))
elif self.factory.method != 'HEAD' and self.length != None and self.length != 0:
self.factory.noPage(failure.Failure(
client.PartialDownloadError(self.status, self.message, response)))
else:
if(self.headers.has_key('transfer-encoding') and
self.headers['transfer-encoding'][0].lower() == 'chunked'):
self.factory.page(de_chunk_payload(response))
else:
self.factory.page(response)
# server might be stupid and not close connection. admittedly
# the fact we do only one request per connection is also
# stupid...
self.quietLoss = 1
self.transport.loseConnection()
class HeaderAwareHTTPClientFactory(client.HTTPClientFactory):
protocol = myHTTPPageGetter
noisy = False
def buildProtocol(self, addr):
p = client.HTTPClientFactory.buildProtocol(self, addr)
p.method = self.method
p.followRedirect = self.followRedirect
return p
def page(self, page):
client.HTTPClientFactory.page(self, (page, self.response_headers))
class HeaderAwareHTTPDownloader(client.HTTPDownloader):
def gotHeaders(self, headers):
self.value = headers
if self.requestedPartial:
contentRange = headers.get("content-range", None)
if not contentRange:
# server doesn't support partial requests, oh well
self.requestedPartial = 0
return
start, end, realLength = http.parseContentRange(contentRange[0])
if start != self.requestedPartial:
# server is acting wierdly
self.requestedPartial = 0
def getPage(url, contextFactory=None, *args, **kwargs):
"""
Download a web page as a string.
Download a page. Return a deferred, which will callback with a
page (as a string) or errback with a description of the error.
See HTTPClientFactory to see what extra args can be passed.
"""
kwargs['agent'] = "Coherence PageGetter"
return client._makeGetterFactory(
url,
HeaderAwareHTTPClientFactory,
contextFactory=contextFactory,
*args, **kwargs).deferred
def downloadPage(url, file, contextFactory=None, *args, **kwargs):
"""Download a web page to a file.
@param file: path to file on filesystem, or file-like object.
See HTTPDownloader to see what extra args can be passed.
"""
scheme, host, port, path = client._parse(url)
factory = HeaderAwareHTTPDownloader(url, file, *args, **kwargs)
factory.noisy = False
if scheme == 'https':
from twisted.internet import ssl
if contextFactory is None:
contextFactory = ssl.ClientContextFactory()
reactor.connectSSL(host, port, factory, contextFactory)
else:
reactor.connectTCP(host, port, factory)
return factory.deferred
# StaticFile used to be a patched version of static.File. The later
# was fixed in TwistedWeb 8.2.0 and 9.0.0, while the patched variant
# contained deprecated and removed code.
StaticFile = static.File
class BufferFile(static.File):
""" taken from twisted.web.static and modified
accordingly to the patch by John-Mark Gurney
http://resnet.uoregon.edu/~gurney_j/jmpc/dist/twisted.web.static.patch
"""
def __init__(self, path, target_size=0, *args):
static.File.__init__(self, path, *args)
self.target_size = target_size
self.upnp_retry = None
def render(self, request):
#print ""
#print "BufferFile", request
# FIXME detect when request is REALLY finished
if request is None or request.finished :
print "No request to render!"
return ''
"""You know what you doing."""
self.restat()
if self.type is None:
self.type, self.encoding = static.getTypeAndEncoding(self.basename(),
self.contentTypes,
self.contentEncodings,
self.defaultType)
if not self.exists():
return self.childNotFound.render(request)
if self.isdir():
return self.redirect(request)
#for content-length
if (self.target_size > 0):
fsize = size = int(self.target_size)
else:
fsize = size = int(self.getFileSize())
#print fsize
if size == int(self.getFileSize()):
request.setHeader('accept-ranges','bytes')
if self.type:
request.setHeader('content-type', self.type)
if self.encoding:
request.setHeader('content-encoding', self.encoding)
try:
f = self.openForReading()
except IOError, e:
import errno
if e[0] == errno.EACCES:
return error.ForbiddenResource().render(request)
else:
raise
if request.setLastModified(self.getmtime()) is http.CACHED:
return ''
trans = True
range = request.getHeader('range')
#print "StaticFile", range
tsize = size
if range is not None:
# This is a request for partial data...
bytesrange = range.split('=')
assert bytesrange[0] == 'bytes',\
"Syntactically invalid http range header!"
start, end = bytesrange[1].split('-', 1)
if start:
start = int(start)
# Are we requesting something beyond the current size of the file?
if (start >= self.getFileSize()):
# Retry later!
print bytesrange
print "Requesting data beyond current scope -> postpone rendering!"
self.upnp_retry = reactor.callLater(1.0, self.render, request)
return server.NOT_DONE_YET
f.seek(start)
if end:
#print ":%s" % end
end = int(end)
else:
end = size - 1
else:
lastbytes = int(end)
if size < lastbytes:
lastbytes = size
start = size - lastbytes
f.seek(start)
fsize = lastbytes
end = size - 1
size = end + 1
fsize = end - int(start) + 1
# start is the byte offset to begin, and end is the byte offset
# to end.. fsize is size to send, tsize is the real size of
# the file, and size is the byte position to stop sending.
if fsize <= 0:
request.setResponseCode(http.REQUESTED_RANGE_NOT_SATISFIABLE)
fsize = tsize
trans = False
else:
request.setResponseCode(http.PARTIAL_CONTENT)
request.setHeader('content-range',"bytes %s-%s/%s " % (
str(start), str(end), str(tsize)))
#print "StaticFile", start, end, tsize
request.setHeader('content-length', str(fsize))
if request.method == 'HEAD' or trans == False:
# pretend we're a HEAD request, so content-length
# won't be overwritten.
request.method = 'HEAD'
return ''
#print "StaticFile out", request.headers, request.code
# return data
# size is the byte position to stop sending, not how many bytes to send
BufferFileTransfer(f, size - f.tell(), request)
# and make sure the connection doesn't get closed
return server.NOT_DONE_YET
class BufferFileTransfer(object):
"""
A class to represent the transfer of a file over the network.
"""
request = None
def __init__(self, file, size, request):
self.file = file
self.size = size
self.request = request
self.written = self.file.tell()
request.registerProducer(self, 0)
def resumeProducing(self):
#print "resumeProducing", self.request,self.size,self.written
if not self.request:
return
data = self.file.read(min(abstract.FileDescriptor.bufferSize, self.size - self.written))
if data:
self.written += len(data)
# this .write will spin the reactor, calling .doWrite and then
# .resumeProducing again, so be prepared for a re-entrant call
self.request.write(data)
if self.request and self.file.tell() == self.size:
self.request.unregisterProducer()
self.request.finish()
self.request = None
def pauseProducing(self):
pass
def stopProducing(self):
#print "stopProducing",self.request
self.request.unregisterProducer()
self.file.close()
self.request.finish()
self.request = None
from datetime import datetime, tzinfo, timedelta
import random
class _tz(tzinfo):
def utcoffset(self, dt):
return self._offset
def tzname(self, dt):
return self._name
def dst(self,dt):
return timedelta(0)
class _CET(_tz):
_offset = timedelta(minutes=60)
_name = 'CET'
class _CEST(_tz):
_offset = timedelta(minutes=120)
_name = 'CEST'
_bdates = [datetime(1997,2,28,17,20,tzinfo=_CET()), # Sebastian Oliver
datetime(1999,9,19,4,12,tzinfo=_CEST()), # Patrick Niklas
datetime(2000,9,23,4,8,tzinfo=_CEST()), # Saskia Alexa
datetime(2003,7,23,1,18,tzinfo=_CEST()), # Mara Sophie
# you are the best!
]
def datefaker():
return random.choice(_bdates)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~extern~telepathy~mirabeau_tube_publisher.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2009 Philippe Normand <[email protected]>
import gobject
from dbus import PROPERTIES_IFACE
from telepathy.interfaces import CHANNEL_INTERFACE, CONNECTION_INTERFACE_REQUESTS, \
CHANNEL_TYPE_DBUS_TUBE
from telepathy.constants import CONNECTION_HANDLE_TYPE_ROOM, \
SOCKET_ACCESS_CONTROL_CREDENTIALS
from telepathy.interfaces import CHANNEL_INTERFACE_TUBE, CHANNEL_TYPE_DBUS_TUBE, \
CHANNEL_INTERFACE
from telepathy.constants import TUBE_CHANNEL_STATE_LOCAL_PENDING
from coherence.extern.telepathy import client, tube, mirabeau_tube_consumer
from coherence.dbus_constants import BUS_NAME, OBJECT_PATH, DEVICE_IFACE, SERVICE_IFACE
from coherence import dbus_service
from twisted.internet import task
class MirabeauTubePublisherMixin(tube.TubePublisherMixin):
def __init__(self, tubes_to_offer, application, allowed_devices):
tube.TubePublisherMixin.__init__(self, tubes_to_offer)
self.coherence = application
self.allowed_devices = allowed_devices
self.coherence_tube = None
self.device_tube = None
self.service_tube = None
self.announce_done = False
self._ms_detected_match = None
self._ms_removed_match = None
def _media_server_found(self, infos, udn):
uuid = udn[5:]
for device in self.coherence.dbus.devices.values():
if device.uuid == uuid:
self._register_device(device)
return
def _register_device(self, device):
if self.allowed_devices is not None and device.uuid not in self.allowed_devices:
self.info("device not allowed: %r", device.uuid)
return
device.add_to_connection(self.device_tube, device.path())
self.info("adding device %s to connection: %s",
device.get_markup_name(), self.device_tube)
for service in device.services:
if getattr(service,'NOT_FOR_THE_TUBES', False):
continue
service.add_to_connection(self.service_tube, service.path)
def _media_server_removed(self, udn):
for device in self.coherence.dbus.devices.values():
if udn == device.device.get_id():
if self.allowed_devices != None and device.uuid not in self.allowed_devices:
# the device is not allowed, no reason to
# disconnect from the tube to which it wasn't
# connected in the first place anyway
return
device.remove_from_connection(self.device_tube, device.path())
self.info("remove_from_connection: %s" % device.get_friendly_name())
for service in device.services:
if getattr(service,'NOT_FOR_THE_TUBES', False):
continue
service.remove_from_connection(self.service_tube, service.path)
return
def post_tube_offer(self, tube, tube_conn):
service = tube.props[CHANNEL_TYPE_DBUS_TUBE + ".ServiceName"]
if service == BUS_NAME:
self.coherence.dbus.add_to_connection(tube_conn, OBJECT_PATH)
self.coherence_tube = tube_conn
elif service == DEVICE_IFACE:
self.device_tube = tube_conn
elif service == SERVICE_IFACE:
self.service_tube = tube_conn
if not self.announce_done and None not in (self.coherence_tube,
self.device_tube,
self.service_tube):
self.announce_done = True
allowed_device_types = [u'urn:schemas-upnp-org:device:MediaServer:2',
u'urn:schemas-upnp-org:device:MediaServer:1']
devices = self.coherence.dbus.devices.values()
for device in devices:
if device.get_device_type() in allowed_device_types:
self._register_device(device)
bus = self.coherence.dbus.bus
self._ms_detected_match = bus.add_signal_receiver(self._media_server_found,
"UPnP_ControlPoint_MediaServer_detected")
self._ms_removed_match = bus.add_signal_receiver(self._media_server_removed,
"UPnP_ControlPoint_MediaServer_removed")
def close_tubes(self):
if self._ms_detected_match:
self._ms_detected_match.remove()
self._ms_detected_match = None
if self._ms_removed_match:
self._ms_removed_match.remove()
self._ms_removed_match = None
return tube.TubePublisherMixin.close_tubes(self)
class MirabeauTubePublisherConsumer(MirabeauTubePublisherMixin,
mirabeau_tube_consumer.MirabeauTubeConsumerMixin,
client.Client):
logCategory = "mirabeau_tube_publisher"
def __init__(self, manager, protocol, account, muc_id, conference_server, tubes_to_offer,
application, allowed_devices, found_peer_callback=None,
disapeared_peer_callback=None, got_devices_callback=None):
MirabeauTubePublisherMixin.__init__(self, tubes_to_offer, application,
allowed_devices)
mirabeau_tube_consumer.MirabeauTubeConsumerMixin.__init__(self,
found_peer_callback=found_peer_callback,
disapeared_peer_callback=disapeared_peer_callback,
got_devices_callback=got_devices_callback)
client.Client.__init__(self, manager, protocol, account, muc_id, conference_server)
def got_tube(self, tube):
client.Client.got_tube(self, tube)
initiator_handle = tube.props[CHANNEL_INTERFACE + ".InitiatorHandle"]
if initiator_handle == self.self_handle:
self.finish_tube_offer(tube)
else:
self.accept_tube(tube)
def tube_opened(self, tube):
tube_conn = super(MirabeauTubePublisherConsumer, self).tube_opened(tube)
initiator_handle = tube.props[CHANNEL_INTERFACE + ".InitiatorHandle"]
if initiator_handle == self.self_handle:
self.post_tube_offer(tube, tube_conn)
else:
self.post_tube_accept(tube, tube_conn, initiator_handle)
return tube_conn
def stop(self):
MirabeauTubePublisherMixin.close_tubes(self)
return client.Client.stop(self)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~test~test_dbus.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
"""
Test cases for L{dbus_service}
"""
import os
from twisted.trial import unittest
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from coherence import __version__
from coherence.base import Coherence
from coherence.upnp.core.uuid import UUID
import coherence.extern.louie as louie
BUS_NAME = 'org.Coherence'
OBJECT_PATH = '/org/Coherence'
class TestDBUS(unittest.TestCase):
def setUp(self):
louie.reset()
self.coherence = Coherence({'unittest':'yes','logmode':'error','use_dbus':'yes','controlpoint':'yes'})
self.bus = dbus.SessionBus()
self.coherence_service = self.bus.get_object(BUS_NAME,OBJECT_PATH)
self.uuid = UUID()
def tearDown(self):
def cleaner(r):
self.coherence.clear()
return r
dl = self.coherence.shutdown()
dl.addBoth(cleaner)
return dl
def test_dbus_version(self):
""" tests the version number request via dbus
"""
d = Deferred()
def handle_version_reply(version):
self.assertEqual(version,__version__)
d.callback(version)
def handle_error(err):
d.errback(err)
self.coherence_service.version(dbus_interface=BUS_NAME,
reply_handler=handle_version_reply,
error_handler=handle_error)
return d
def test_dbus_plugin_add_and_remove(self):
""" tests creation and removal of a backend via dbus
"""
d = Deferred()
def handle_error(err):
d.errback(err)
def handle_add_plugin_reply(uuid):
uuid = str(uuid)
self.assertEqual(str(self.uuid),uuid)
def remove_it(uuid):
def handle_remove_plugin_reply(uuid):
self.assertEqual(str(self.uuid),uuid)
d.callback(uuid)
self.coherence_service.remove_plugin(uuid,
dbus_interface=BUS_NAME,
reply_handler=handle_remove_plugin_reply,
error_handler=handle_error)
reactor.callLater(2,remove_it,uuid)
self.coherence_service.add_plugin('SimpleLight',{'name':'dbus-test-light-%d'%os.getpid(),'uuid':str(self.uuid)},
dbus_interface=BUS_NAME,
reply_handler=handle_add_plugin_reply,
error_handler=handle_error)
return d
if reactor.__class__.__name__ != 'Glib2Reactor':
TestDBUS.skip = """This test needs a Glib2Reactor, pls start trial with the '-r glib2' option"""
try:
import dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
import dbus.service
except ImportError:
TestDBUS.skip = "Python dbus-bindings not available"
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~lolcats_storage.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Benjamin Kampmann <[email protected]>
"""
This is a Media Backend that allows you to access the cool and cute pictures
from lolcats.com. This is mainly meant as a Sample Media Backend to learn how to
write a Media Backend.
So. You are still reading which allows me to assume that you want to learn how
to write a Media Backend for Coherence. NICE :) .
Once again: This is a SIMPLE Media Backend. It does not contain any big
requests, searches or even transcoding. The only thing we want to do in this
simple example, is to fetch a rss link on startup, parse it, save it and restart
the process one hour later again. Well, on top of this, we also want to provide
these informations as a Media Server in the UPnP/DLNA Network of course ;) .
Wow. You are still reading. You must be really interessted. Then let's go.
"""
########## NOTE:
# Please don't complain about the coding style of this document - I know. It is
# just this way to make it easier to document and to understand.
########## The imports
# The entry point for each kind of Backend is a 'BackendStore'. The BackendStore
# is the instance that does everything Usually. In this Example it can be
# understood as the 'Server', the object retrieving and serving the data.
from coherence.backend import BackendStore
# The data itself is stored in BackendItems. They are also the first things we
# are going to create.
from coherence.backend import BackendItem
# To make the data 'renderable' we need to define the DIDLite-Class of the Media
# we are providing. For that we have a bunch of helpers that we also want to
# import
from coherence.upnp.core import DIDLLite
# Coherence relies on the Twisted backend. I hope you are familar with the
# concept of deferreds. If not please read:
# http://twistedmatrix.com/projects/core/documentation/howto/async.html
#
# It is a basic concept that you need to understand to understand the following
# code. But why am I talking about it? Oh, right, because we use a http-client
# based on the twisted.web.client module to do our requests.
from coherence.upnp.core.utils import getPage
# And we also import the reactor, that allows us to specify an action to happen
# later
from twisted.internet import reactor
# And to parse the RSS-Data (which is XML), we use the coherence helper
from coherence.extern.et import parse_xml
########## The models
# After the download and parsing of the data is done, we want to save it. In
# this case, we want to fetch the images and store their URL and the title of
# the image. That is the LolcatsImage class:
class LolcatsImage(BackendItem):
# We inherit from BackendItem as it already contains a lot of helper methods
# and implementations. For this simple example, we only have to fill the
# item with data.
def __init__(self, parent_id, id, title, url):
self.parentid = parent_id # used to be able to 'go back'
self.update_id = 0
self.id = id # each item has its own and unique id
self.location = url # the url of the picture
self.name = title # the title of the picture. Inside
# coherence this is called 'name'
# Item.item is a special thing. This is used to explain the client what
# kind of data this is. For e.g. A VideoItem or a MusicTrack. In our
# case, we have an image.
self.item = DIDLLite.ImageItem(id, parent_id, self.name)
# each Item.item has to have one or more Resource objects
# these hold detailed information about the media data
# and can represent variants of it (different sizes, transcoded formats)
res = DIDLLite.Resource(self.location, 'http-get:*:image/jpeg:*')
res.size = None #FIXME: we should have a size here
# and a resolution entry would be nice too
self.item.res.append(res)
class LolcatsContainer(BackendItem):
# The LolcatsContainer will hold the reference to all our LolcatsImages. This
# kind of BackenedItem is a bit different from the normal BackendItem,
# because it has 'children' (the lolcatsimages). Because of that we have
# some more stuff to do in here.
def __init__(self, parent_id, id):
# the ids as above
self.parent_id = parent_id
self.id = id
# we never have a different name anyway
self.name = 'LOLCats'
# but we need to set it to a certain mimetype to explain it, that we
# contain 'children'.
self.mimetype = 'directory'
# As we are updating our data periodically, we increase this value so
# that our clients can check easier if something has changed since their
# last request.
self.update_id = 0
# that is where we hold the children
self.children = []
# and we need to give a DIDLLite again. This time we want to be
# understood as 'Container'.
self.item = DIDLLite.Container(id, parent_id, self.name)
self.item.childCount = None # will be set as soon as we have images
def get_children(self, start=0, end=0):
# This is the only important implementation thing: we have to return our
# list of children
if end != 0:
return self.children[start:end]
return self.children[start:]
# there is nothing special in here
# FIXME: move it to a base BackendContainer class
def get_child_count(self):
return len(self.children)
def get_item(self):
return self.item
def get_name(self):
return self.name
def get_id(self):
return self.id
########## The server
# As already said before the implementation of the server is done in an
# inheritance of a BackendStore. This is where the real code happens (usually).
# In our case this would be: downloading the page, parsing the content, saving
# it in the models and returning them on request.
class LolcatsStore(BackendStore):
# this *must* be set. Because the (most used) MediaServer Coherence also
# allows other kind of Backends (like remote lights).
implements = ['MediaServer']
# this is only for this implementation: the http link to the lolcats rss
# feed that we want to read and parse:
rss_url = "http://feeds.feedburner.com/ICanHasCheezburger?format=xml"
# as we are going to build a (very small) tree with the items, we need to
# define the first (the root) item:
ROOT_ID = 0
def __init__(self, server, *args, **kwargs):
# first we inizialize our heritage
BackendStore.__init__(self,server,**kwargs)
# When a Backend is initialized, the configuration is given as keyword
# arguments to the initialization. We receive it here as a dicitonary
# and allow some values to be set:
# the name of the MediaServer as it appears in the network
self.name = kwargs.get('name', 'Lolcats')
# timeout between updates in hours:
self.refresh = int(kwargs.get('refresh', 1)) * (60 *60)
# the UPnP device that's hosting that backend, that's already done
# in the BackendStore.__init__, just left here the sake of completeness
self.server = server
# internally used to have a new id for each item
self.next_id = 1000
# we store the last update from the rss feed so that we know if we have
# to parse again, or not:
self.last_updated = None
# initialize our lolcats container (no parent, this is the root)
self.container = LolcatsContainer(None, self.ROOT_ID)
# but as we also have to return them on 'get_by_id', we have our local
# store of images per id:
self.images = {}
# we tell that if an XBox sends a request for images we'll
# map the WMC id of that request to our local one
self.wmc_mapping = {'16': 0}
# and trigger an update of the data
dfr = self.update_data()
# So, even though the initialize is kind of done, Coherence does not yet
# announce our Media Server.
# Coherence does wait for signal send by us that we are ready now.
# And we don't want that to happen as long as we don't have succeeded
# in fetching some first data, so we delay this signaling after the update is done:
dfr.addCallback(self.init_completed)
dfr.addCallback(self.queue_update)
def get_by_id(self, id):
print "asked for", id, type(id)
# what ever we are asked for, we want to return the container only
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
if int(id) == self.ROOT_ID:
return self.container
return self.images.get(int(id), None)
def upnp_init(self):
# after the signal was triggered, this method is called by coherence and
# from now on self.server is existing and we can do
# the necessary setup here
# that allows us to specify our server options in more detail.
# here we define what kind of media content we do provide
# mostly needed to make some naughty DLNA devices behave
# will probably move into Coherence internals one day
self.server.connection_manager_server.set_variable( \
0, 'SourceProtocolInfo', ['http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000',
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_SM;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000',
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_MED;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000',
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_LRG;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000',
'http-get:*:image/jpeg:*'])
# and as it was done after we fetched the data the first time
# we want to take care about the server wide updates as well
self._update_container()
def _update_container(self, result=None):
# we need to inform Coherence about these changes
# again this is something that will probably move
# into Coherence internals one day
if self.server:
self.server.content_directory_server.set_variable(0,
'SystemUpdateID', self.update_id)
value = (self.ROOT_ID,self.container.update_id)
self.server.content_directory_server.set_variable(0,
'ContainerUpdateIDs', value)
return result
def update_loop(self):
# in the loop we want to call update_data
dfr = self.update_data()
# aftert it was done we want to take care about updating
# the container
dfr.addCallback(self._update_container)
# in ANY case queue an update of the data
dfr.addBoth(self.queue_update)
def update_data(self):
# trigger an update of the data
# fetch the rss
dfr = getPage(self.rss_url)
# push it through our xml parser
dfr.addCallback(parse_xml)
# then parse the data into our models
dfr.addCallback(self.parse_data)
return dfr
def parse_data(self, xml_data):
# So. xml_data is a cElementTree Element now. We can read our data from
# it now.
# each xml has a root element
root = xml_data.getroot()
# from there, we look for the newest update and compare it with the one
# we have saved. If they are the same, we don't need to go on:
pub_date = root.find('./channel/lastBuildDate').text
if pub_date == self.last_updated:
return
# not the case, set this as the last update and continue
self.last_updated = pub_date
# and reset the childrens list of the container and the local storage
self.container.children = []
self.images = {}
# Attention, as this is an example, this code is meant to be as simple
# as possible and not as efficient as possible. IMHO the following code
# pretty much sucks, because it is totally blocking (even though we have
# 'only' 20 elements)
# we go through our entries and do something specific to the
# lolcats-rss-feed to fetch the data out of it
url_item = './{http://search.yahoo.com/mrss/}content'
for item in root.findall('./channel/item'):
title = item.find('./title').text
try:
url = item.findall(url_item)[1].get('url', None)
except IndexError:
continue
if url is None:
continue
image = LolcatsImage(self.ROOT_ID, self.next_id, title, url)
self.container.children.append(image)
self.images[self.next_id] = image
# increase the next_id entry every time
self.next_id += 1
# and increase the container update id and the system update id
# so that the clients can refresh with the new data
self.container.update_id += 1
self.update_id += 1
def queue_update(self, error_or_failure):
# We use the reactor to queue another updating of our data
print error_or_failure
reactor.callLater(self.refresh, self.update_loop)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~tube_service.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2009 - Frank Scholz <[email protected]>
""" TUBE service classes
"""
import urllib, urlparse
import dbus
from twisted.web import resource
from twisted.internet import defer
from twisted.python.util import OrderedDict
from coherence.upnp.core.utils import parse_xml
from coherence.upnp.devices.basics import RootDeviceXML, DeviceHttpRoot
from coherence.upnp.core import service
from coherence.upnp.core.soap_service import UPnPPublisher
from coherence.upnp.core import action
from coherence.upnp.core import variable
from coherence.upnp.core import DIDLLite
from coherence.upnp.core.utils import ReverseProxyUriResource
from coherence import log
class MirabeauProxy(resource.Resource, log.Loggable):
logCategory = 'mirabeau'
def __init__(self):
resource.Resource.__init__(self)
log.Loggable.__init__(self)
self.isLeaf = 0
def getChildWithDefault(self, path, request):
self.info('MiraBeau getChildWithDefault %s, %s, %s %s' % (request.method, path, request.uri, request.client))
uri = urllib.unquote_plus(path)
self.info('MiraBeau uri %r' % uri)
return ReverseProxyUriResource(uri)
class TubeServiceControl(UPnPPublisher, log.Loggable):
logCategory = 'mirabeau'
def __init__(self, server):
self.service = server
self.variables = server.get_variables()
self.actions = server.get_actions()
def get_action_results(self, result, action, instance):
""" check for out arguments
if yes: check if there are related ones to StateVariables with
non A_ARG_TYPE_ prefix
if yes: check if there is a call plugin method for this action
if yes: update StateVariable values with call result
if no: get StateVariable values and
add them to result dict
"""
self.debug('get_action_results', result)
#print 'get_action_results', action, instance
notify = []
for argument in action.get_out_arguments():
#print 'get_state_variable_contents', argument.name
if argument.name[0:11] != 'A_ARG_TYPE_':
variable = self.variables[instance][argument.get_state_variable()]
variable.update(result[argument.name].decode('utf-8').encode('utf-8'))
#print 'update state variable contents', variable.name, variable.value, variable.send_events
if(variable.send_events == 'yes' and variable.moderated == False):
notify.append(variable)
self.service.propagate_notification(notify)
self.info( 'action_results unsorted', action.name, result)
if len(result) == 0:
return result
ordered_result = OrderedDict()
for argument in action.get_out_arguments():
if action.name == 'XXXBrowse' and argument.name == 'Result':
didl = DIDLLite.DIDLElement.fromString(result['Result'].decode('utf-8'))
changed = False
for item in didl.getItems():
new_res = DIDLLite.Resources()
for res in item.res:
remote_protocol,remote_network,remote_content_format,_ = res.protocolInfo.split(':')
if remote_protocol == 'http-get' and remote_network == '*':
quoted_url = urllib.quote_plus(res.data)
print "modifying", res.data
res.data = urlparse.urlunsplit(('http', self.service.device.external_address,'mirabeau',quoted_url,""))
print "--->", res.data
new_res.append(res)
changed = True
item.res = new_res
if changed == True:
didl.rebuild()
ordered_result[argument.name] = didl.toString() #.replace('<ns0:','<')
else:
ordered_result[argument.name] = result[argument.name].decode('utf-8')
else:
ordered_result[argument.name] = result[argument.name].decode('utf-8').encode('utf-8')
self.info( 'action_results sorted', action.name, ordered_result)
return ordered_result
def soap__generic(self, *args, **kwargs):
""" generic UPnP service control method,
which will be used if no soap_ACTIONNAME method
in the server service control class can be found
"""
try:
action = self.actions[kwargs['soap_methodName']]
except:
return failure.Failure(errorCode(401))
try:
instance = int(kwargs['InstanceID'])
except:
instance = 0
self.info("soap__generic", action, __name__, kwargs)
del kwargs['soap_methodName']
in_arguments = action.get_in_arguments()
for arg_name, arg in kwargs.iteritems():
if arg_name.find('X_') == 0:
continue
l = [ a for a in in_arguments if arg_name == a.get_name()]
if len(l) > 0:
in_arguments.remove(l[0])
else:
self.critical('argument %s not valid for action %s' % (arg_name,action.name))
return failure.Failure(errorCode(402))
if len(in_arguments) > 0:
self.critical('argument %s missing for action %s' %
([ a.get_name() for a in in_arguments],action.name))
return failure.Failure(errorCode(402))
def got_error(x):
self.info('dbus error during call processing')
return x
# call plugin method for this action
#print 'callit args', args
#print 'callit kwargs', kwargs
#print 'callit action', action
#print 'callit dbus action', self.service.service.action
d = defer.Deferred()
self.service.service.call_action( action.name, dbus.Dictionary(kwargs,signature='ss'), reply_handler = d.callback, error_handler = d.errback,utf8_strings=True)
d.addCallback( self.get_action_results, action, instance)
d.addErrback(got_error)
return d
class TubeServiceProxy(service.ServiceServer, resource.Resource,
log.Loggable):
logCategory = 'mirabeau'
def __init__(self, tube_service, device, backend=None):
self.device = device
self.service = tube_service
resource.Resource.__init__(self)
id = self.service.get_id().split(':')[3]
service.ServiceServer.__init__(self, id, self.device.version, None)
self.control = TubeServiceControl(self)
self.putChild(self.scpd_url, service.scpdXML(self, self.control))
self.putChild(self.control_url, self.control)
self.device.web_resource.putChild(id, self)
def init_var_and_actions(self):
""" retrieve all actions and create the Action
classes for our (proxy) server
retrieve all variables and create the StateVariable
classes for our (proxy) server
"""
xml = self.service.get_scpd_xml()
tree = parse_xml(xml, 'utf-8').getroot()
ns = "urn:schemas-upnp-org:service-1-0"
for action_node in tree.findall('.//{%s}action' % ns):
name = action_node.findtext('{%s}name' % ns)
arguments = []
for argument in action_node.findall('.//{%s}argument' % ns):
arg_name = argument.findtext('{%s}name' % ns)
arg_direction = argument.findtext('{%s}direction' % ns)
arg_state_var = argument.findtext('{%s}relatedStateVariable' % ns)
arguments.append(action.Argument(arg_name, arg_direction,
arg_state_var))
self._actions[name] = action.Action(self, name, 'n/a', arguments)
for var_node in tree.findall('.//{%s}stateVariable' % ns):
send_events = var_node.attrib.get('sendEvents','yes')
name = var_node.findtext('{%s}name' % ns)
data_type = var_node.findtext('{%s}dataType' % ns)
values = []
""" we need to ignore this, as there we don't get there our
{urn:schemas-beebits-net:service-1-0}X_withVendorDefines
attibute there
"""
for allowed in var_node.findall('.//{%s}allowedValue' % ns):
values.append(allowed.text)
instance = 0
self._variables.get(instance)[name] = variable.StateVariable(self, name,
'n/a',
instance, send_events,
data_type, values)
""" we need to do this here, as there we don't get there our
{urn:schemas-beebits-net:service-1-0}X_withVendorDefines
attibute there
"""
self._variables.get(instance)[name].has_vendor_values = True
class TubeDeviceProxy(log.Loggable):
logCategory = 'dbus'
def __init__(self, coherence, tube_device,external_address):
log.Loggable.__init__(self)
self.device = tube_device
self.coherence = coherence
self.external_address = external_address
self.uuid = self.device.get_id().split('-')
self.uuid[1] = 'tube'
self.uuid = '-'.join(self.uuid)
self.friendly_name = self.device.get_friendly_name()
self.device_type = self.device.get_friendly_device_type()
self.version = int(self.device.get_device_type_version())
self._services = []
self._devices = []
self.icons = []
self.info("uuid: %s, name: %r, device type: %r, version: %r",
self.uuid, self.friendly_name, self.device_type, self.version)
""" create the http entrypoint """
self.web_resource = DeviceHttpRoot(self)
self.coherence.add_web_resource( str(self.uuid)[5:], self.web_resource)
""" create the Service proxy(s) """
for service in self.device.services:
self.debug("Proxying service %r", service)
new_service = TubeServiceProxy(service, self)
self._services.append(new_service)
""" create a device description xml file(s) """
version = self.version
while version > 0:
self.web_resource.putChild( 'description-%d.xml' % version,
RootDeviceXML( self.coherence.hostname,
str(self.uuid),
self.coherence.urlbase,
device_type=self.device_type, version=version,
friendly_name=self.friendly_name,
model_description='Coherence UPnP %s' % self.device_type,
model_name='Coherence UPnP %s' % self.device_type,
services=self._services,
devices=self._devices,
icons=self.icons))
version -= 1
""" and register with SSDP server """
self.register()
def register(self):
s = self.coherence.ssdp_server
uuid = str(self.uuid)
host = self.coherence.hostname
self.msg('%s register' % self.device_type)
# we need to do this after the children are there, since we send notifies
s.register('local',
'%s::upnp:rootdevice' % uuid,
'upnp:rootdevice',
self.coherence.urlbase + uuid[5:] + '/' + 'description-%d.xml' % self.version,
host=host)
s.register('local',
uuid,
uuid,
self.coherence.urlbase + uuid[5:] + '/' + 'description-%d.xml' % self.version,
host=host)
version = self.version
while version > 0:
if version == self.version:
silent = False
else:
silent = True
s.register('local',
'%s::urn:schemas-upnp-org:device:%s:%d' % (uuid, self.device_type, version),
'urn:schemas-upnp-org:device:%s:%d' % (self.device_type, version),
self.coherence.urlbase + uuid[5:] + '/' + 'description-%d.xml' % version,
silent=silent,
host=host)
version -= 1
for service in self._services:
device_version = self.version
service_version = self.version
if hasattr(service,'version'):
service_version = service.version
silent = False
while service_version > 0:
try:
namespace = service.namespace
except:
namespace = 'schemas-upnp-org'
device_description_tmpl = 'description-%d.xml' % device_version
if hasattr(service,'device_description_tmpl'):
device_description_tmpl = service.device_description_tmpl
s.register('local',
'%s::urn:%s:service:%s:%d' % (uuid,namespace,service.id, service_version),
'urn:%s:service:%s:%d' % (namespace,service.id, service_version),
self.coherence.urlbase + uuid[5:] + '/' + device_description_tmpl,
silent=silent,
host=host)
silent = True
service_version -= 1
device_version -= 1
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~extern~simple_config.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# based on: http://code.activestate.com/recipes/573463/
# Modified by Philippe Normand
# Copyright 2008, Frank Scholz <[email protected]>
from coherence.extern.et import ET as ElementTree, indent, parse_xml
class ConfigItem(object):
""" the base """
class Config(ConfigItem):
def __init__(self,filename,root=None,preamble=False,element2attr_mappings=None):
self.filename = filename
self.element2attr_mappings = element2attr_mappings or {}
self.db = parse_xml(open(self.filename).read())
self.config = self.db = ConvertXmlToDict(self.db.getroot())
self.preamble = ''
if preamble == True:
self.preamble = """<?xml version="1.0" encoding="utf-8"?>\n"""
if root != None:
try:
self.config = self.config[root]
except KeyError:
pass
self.config.save = self.save
def tostring(self):
root = ConvertDictToXml(self.db,self.element2attr_mappings)
tree = ElementTree.ElementTree(root).getroot()
indent(tree,0)
xml = self.preamble + ElementTree.tostring(tree, encoding='utf-8')
return xml
def save(self, new_filename=None):
if new_filename != None:
self.filename = new_filename
xml = self.tostring()
f = open(self.filename, 'wb')
f.write(xml)
f.close()
def get(self,key,default=None):
if key in self.config:
item = self.config[key]
try:
if item['active'] == 'no':
return default
return item
except (TypeError,KeyError):
return item
return default
def set(self,key,value):
self.config[key] = value
class XmlDictObject(dict,ConfigItem):
def __init__(self, initdict=None):
if initdict is None:
initdict = {}
dict.__init__(self, initdict)
self._attrs = {}
def __getattr__(self, item):
value = self.__getitem__(item)
try:
if value['active'] == 'no':
raise KeyError
except (TypeError,KeyError):
return value
return value
def __setattr__(self, item, value):
if item == '_attrs':
object.__setattr__(self, item, value)
else:
self.__setitem__(item, value)
def get(self,key,default=None):
try:
item = self[key]
try:
if item['active'] == 'no':
return default
return item
except (TypeError,KeyError):
return item
except KeyError:
pass
return default
def set(self,key,value):
self[key] = value
def __str__(self):
if self.has_key('_text'):
return self.__getitem__('_text')
else:
return ''
def __repr__(self):
return repr(dict(self))
@staticmethod
def Wrap(x):
if isinstance(x, dict):
return XmlDictObject((k, XmlDictObject.Wrap(v)) for (k, v) in x.iteritems())
elif isinstance(x, list):
return [XmlDictObject.Wrap(v) for v in x]
else:
return x
@staticmethod
def _UnWrap(x):
if isinstance(x, dict):
return dict((k, XmlDictObject._UnWrap(v)) for (k, v) in x.iteritems())
elif isinstance(x, list):
return [XmlDictObject._UnWrap(v) for v in x]
else:
return x
def UnWrap(self):
return XmlDictObject._UnWrap(self)
def _ConvertDictToXmlRecurse(parent, dictitem,element2attr_mappings=None):
assert type(dictitem) is not type([])
if isinstance(dictitem, dict):
for (tag, child) in dictitem.iteritems():
if str(tag) == '_text':
parent.text = str(child)
## elif str(tag) == '_attrs':
## for key, value in child.iteritems():
## parent.set(key, value)
elif element2attr_mappings != None and tag in element2attr_mappings:
parent.set(element2attr_mappings[tag],child)
elif type(child) is type([]):
for listchild in child:
elem = ElementTree.Element(tag)
parent.append(elem)
_ConvertDictToXmlRecurse(elem, listchild,element2attr_mappings=element2attr_mappings)
else:
if(not isinstance(dictitem, XmlDictObject) and
not callable(dictitem)):
attrs = dictitem
dictitem = XmlDictObject()
dictitem._attrs = attrs
if tag in dictitem._attrs:
parent.set(tag, child)
elif not callable(tag) and not callable(child):
elem = ElementTree.Element(tag)
parent.append(elem)
_ConvertDictToXmlRecurse(elem, child,element2attr_mappings=element2attr_mappings)
else:
if not callable(dictitem):
parent.text = str(dictitem)
def ConvertDictToXml(xmldict,element2attr_mappings=None):
roottag = xmldict.keys()[0]
root = ElementTree.Element(roottag)
_ConvertDictToXmlRecurse(root, xmldict[roottag],element2attr_mappings=element2attr_mappings)
return root
def _ConvertXmlToDictRecurse(node, dictclass):
nodedict = dictclass()
## if node.items():
## nodedict.update({'_attrs': dict(node.items())})
if len(node.items()) > 0:
# if we have attributes, set them
attrs = dict(node.items())
nodedict.update(attrs)
nodedict._attrs = attrs
for child in node:
# recursively add the element's children
newitem = _ConvertXmlToDictRecurse(child, dictclass)
if nodedict.has_key(child.tag):
# found duplicate tag, force a list
if type(nodedict[child.tag]) is type([]):
# append to existing list
nodedict[child.tag].append(newitem)
else:
# convert to list
nodedict[child.tag] = [nodedict[child.tag], newitem]
else:
# only one, directly set the dictionary
nodedict[child.tag] = newitem
if node.text is None:
text = ''
else:
text = node.text.strip()
if len(nodedict) > 0:
# if we have a dictionary add the text as a dictionary value (if there is any)
if len(text) > 0:
nodedict['_text'] = text
else:
# if we don't have child nodes or attributes, just set the text
if node.text is not None:
nodedict = node.text.strip()
return nodedict
def ConvertXmlToDict(root,dictclass=XmlDictObject):
return dictclass({root.tag: _ConvertXmlToDictRecurse(root, dictclass)})
def main():
c = Config('config.xml',root='config')
#print '%r' % c.config
#c.save(new_filename='config.new.xml')
print c.config['interface']
#for plugin in c.config.pluginlist.plugin:
# if plugin.active != 'no':
# print '%r' % plugin
if __name__ == '__main__':
main()
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~gallery2_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007, Frank Scholz <[email protected]>
# Copyright 2008, Jean-Michel Sizun <[email protected]>
from twisted.internet import defer
from coherence.upnp.core import utils
from coherence.upnp.core.utils import ReverseProxyUriResource
from coherence.upnp.core.DIDLLite import classChooser, Container, Resource, DIDLElement
from coherence.backend import BackendStore
from coherence.backend import BackendItem
from urlparse import urlsplit
from coherence.extern.galleryremote import Gallery
class ProxyGallery2Image(ReverseProxyUriResource):
def __init__(self, uri):
ReverseProxyUriResource.__init__(self, uri)
def render(self, request):
del request.responseHeaders['referer']
return ReverseProxyUriResource.render(self, request)
class Gallery2Item(BackendItem):
logCategory = 'gallery2_item'
def __init__(self, id, obj, parent, mimetype, urlbase, UPnPClass,update=False):
self.id = id
self.name = obj.get('title')#.encode('utf-8')
if self.name == None:
self.name = obj.get('name')
if self.name == None:
self.name = id
self.mimetype = mimetype
self.gallery2_id = obj.get('gallery2_id')
self.parent = parent
if parent:
parent.add_child(self,update=update)
if parent == None:
parent_id = -1
else:
parent_id = parent.get_id()
self.item = UPnPClass(id, parent_id, self.name)
if isinstance(self.item, Container):
self.item.childCount = 0
self.child_count = 0
self.children = None
if( len(urlbase) and urlbase[-1] != '/'):
urlbase += '/'
if parent == None:
self.gallery2_url = None
self.url = urlbase + str(self.id)
elif self.mimetype == 'directory':
#self.gallery2_url = parent.store.get_url_for_album(self.gallery2_id)
self.url = urlbase + str(self.id)
else:
self.gallery2_url = parent.store.get_url_for_image(self.gallery2_id)
self.url = urlbase + str(self.id)
self.location = ProxyGallery2Image(self.gallery2_url)
if self.mimetype == 'directory':
self.update_id = 0
else:
res = Resource(self.gallery2_url, 'http-get:*:%s:*' % self.mimetype)
res.size = None
self.item.res.append(res)
def remove(self):
if self.parent:
self.parent.remove_child(self)
del self.item
def add_child(self, child, update=False):
if self.children == None:
self.children = []
self.children.append(child)
self.child_count += 1
if isinstance(self.item, Container):
self.item.childCount += 1
if update == True:
self.update_id += 1
def remove_child(self, child):
#self.info("remove_from %d (%s) child %d (%s)" % (self.id, self.get_name(), child.id, child.get_name()))
if child in self.children:
self.child_count -= 1
if isinstance(self.item, Container):
self.item.childCount -= 1
self.children.remove(child)
self.update_id += 1
def get_children(self,start=0,request_count=0):
def process_items(result = None):
if self.children == None:
return []
if request_count == 0:
return self.children[start:]
else:
return self.children[start:request_count]
if (self.children == None):
d = self.store.retrieveItemsForAlbum(self.gallery2_id, self)
d.addCallback(process_items)
return d
else:
return process_items()
def get_child_count(self):
return self.child_count
def get_id(self):
return self.id
def get_update_id(self):
if hasattr(self, 'update_id'):
return self.update_id
else:
return None
def get_path(self):
return self.url
def get_name(self):
return self.name
def get_parent(self):
return self.parent
def get_item(self):
return self.item
def get_xml(self):
return self.item.toString()
def __repr__(self):
return 'id: ' + str(self.id)
class Gallery2Store(BackendStore):
logCategory = 'gallery2_store'
implements = ['MediaServer']
description = ('Gallery2', 'exposes the photos from a Gallery2 photo repository.', None)
options = [{'option':'name', 'text':'Server Name:', 'type':'string','default':'my media','help': 'the name under this MediaServer shall show up with on other UPnP clients'},
{'option':'version','text':'UPnP Version:','type':'int','default':2,'enum': (2,1),'help': 'the highest UPnP version this MediaServer shall support','level':'advance'},
{'option':'uuid','text':'UUID Identifier:','type':'string','help':'the unique (UPnP) identifier for this MediaServer, usually automatically set','level':'advance'},
{'option':'server_url','text':'Server URL:','type':'string'},
{'option':'username','text':'User ID:','type':'string','group':'User Account'},
{'option':'password','text':'Password:','type':'string','group':'User Account'},
]
def __init__(self, server, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.next_id = 1000
self.config = kwargs
self.name = kwargs.get('name','gallery2Store')
self.wmc_mapping = {'16': 1000}
self.update_id = 0
self.store = {}
self.gallery2_server_url = self.config.get('server_url', 'http://localhost/gallery2')
self.gallery2_username = self.config.get('username',None)
self.gallery2_password = self.config.get('password',None)
self.store[1000] = Gallery2Item( 1000, {'title':'Gallery2','gallery2_id':'0','mimetype':'directory'}, None,
'directory', self.urlbase,Container,update=True)
self.store[1000].store = self
self.gallery2_remote = Gallery(self.gallery2_server_url, 2)
if not None in [self.gallery2_username, self.gallery2_password]:
d = self.gallery2_remote.login(self.gallery2_username, self.gallery2_password)
d.addCallback(lambda x : self.retrieveAlbums('0', self.store[1000]))
d.addCallback(self.init_completed)
else:
d = self.retrieveAlbums('0', self.store[1000])
d.addCallback(self.init_completed)
def __repr__(self):
return self.__class__.__name__
def append( self, obj, parent):
if isinstance(obj, basestring):
mimetype = 'directory'
else:
mimetype = obj['mimetype']
UPnPClass = classChooser(mimetype)
id = self.getnextID()
update = False
#if hasattr(self, 'update_id'):
# update = True
item = Gallery2Item( id, obj, parent, mimetype, self.urlbase,
UPnPClass, update=update)
self.store[id] = item
self.store[id].store = self
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
#if parent:
# value = (parent.get_id(),parent.get_update_id())
# if self.server:
# self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
if mimetype == 'directory':
return self.store[id]
return None
def len(self):
return len(self.store)
def get_by_id(self,id):
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
try:
id = int(id)
except ValueError:
id = 1000
if id == 0:
id = 1000
try:
return self.store[id]
except:
return None
def getnextID(self):
self.next_id += 1
return self.next_id
def get_url_for_image(self, gallery2_id):
url = self.gallery2_remote.get_URL_for_image(gallery2_id)
return url
def upnp_init(self):
self.current_connection_id = None
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_SM;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_MED;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_LRG;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
'http-get:*:image/jpeg:*,'
'http-get:*:image/gif:*,'
'http-get:*:image/png:*',
default=True)
def retrieveAlbums(self, album_gallery2_id, parent):
d = self.gallery2_remote.fetch_albums()
def gotAlbums (albums):
if albums :
albums = [album for album in albums.values() if album.get('parent') == album_gallery2_id]
if album_gallery2_id == '0' and len(albums) == 1:
album = albums[0]
self.store[1000].gallery2_id = album.get('name')
self.store[1000].name = album.get('title')
self.store[1000].description = album.get('summary')
else:
for album in albums:
gallery2_id = album.get('name')
parent_gallery2_id = album.get('parent')
title = album.get('title')
description = album.get('summary')
store_item = {
'name':id,
'gallery2_id':gallery2_id,
'parent_id':parent_gallery2_id,
'title':title,
'description':description,
'mimetype':'directory',
}
self.append(store_item, parent)
d.addCallback(gotAlbums)
return d
def retrieveItemsForAlbum (self, album_id, parent):
# retrieve subalbums
d1 = self.retrieveAlbums(album_id, parent)
# retrieve images
d2 = self.gallery2_remote.fetch_album_images(album_id)
def gotImages(images):
if images :
for image in images:
image_gallery2_id = image.get('name')
parent_gallery2_id = image.get('parent')
thumbnail_gallery2_id = image.get('thumbName')
resized_gallery2_id = image.get('resizedName')
title = image.get('title')
description = image.get('description')
gallery2_id = resized_gallery2_id
if gallery2_id == '':
gallery2_id = image_gallery2_id
store_item = {
'name':id,
'gallery2_id':gallery2_id,
'parent_id':parent_gallery2_id,
'thumbnail_gallery2_id':thumbnail_gallery2_id,
'title':title,
'description':description,
'mimetype':'image/jpeg',
}
self.append(store_item, parent)
d2.addCallback(gotImages)
dl = defer.DeferredList([d1,d2])
return dl
def main():
f = Gallery2Store(None)
def got_upnp_result(result):
print "upnp", result
f.upnp_init()
if __name__ == '__main__':
from twisted.internet import reactor
reactor.callWhenRunning(main)
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~log.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007, Philippe Normand <[email protected]>
from coherence.extern.log import log as externlog
from coherence.extern.log.log import *
import os
def human2level(levelname):
levelname = levelname.lower()
if levelname.startswith('none'):
return 0
if levelname.startswith('error'):
return 1
if levelname.startswith('warn'):
return 2
if levelname.startswith('info'):
return 3
if levelname.startswith('debug'):
return 4
return 5
def customStderrHandler(level, object, category, file, line, message):
"""
A log handler that writes to stderr.
@type level: string
@type object: string (or None)
@type category: string
@type message: string
"""
if not isinstance(message, basestring):
message = str(message)
if isinstance(message, unicode):
message = message.encode('utf-8')
message = "".join(message.splitlines())
where = "(%s:%d)" % (file, line)
formatted_level = getFormattedLevelName(level)
formatted_time = time.strftime("%b %d %H:%M:%S")
formatted = '%s %-27s %-15s ' % (formatted_level, category,
formatted_time)
safeprintf(sys.stderr, formatted)
safeprintf(sys.stderr, ' %s %s\n', message, where)
sys.stderr.flush()
def init(logfile=None,loglevel='*:2'):
externlog.init('COHERENCE_DEBUG', True)
externlog.setPackageScrubList('coherence', 'twisted')
if logfile is not None:
outputToFiles(stdout=None, stderr=logfile)
# log WARNINGS by default
if not os.getenv('COHERENCE_DEBUG'):
if loglevel.lower() != 'none':
setDebug(loglevel)
if externlog.stderrHandler in externlog._log_handlers_limited:
externlog.removeLimitedLogHandler(externlog.stderrHandler)
if os.getenv('COHERENCE_DEBUG') or loglevel.lower() != 'none':
"print addLimitedLogHandler(customStderrHandler)"
externlog.addLimitedLogHandler(customStderrHandler)
def set_debug(loglevel):
setDebug(loglevel)
def show_levels():
print externlog._categories
# Make Loggable a new-style object
class Loggable(externlog.Loggable, object):
def logFunction(self, *args):
if len(args) > 1:
format = args[0]
arguments = args[1:]
try:
format % arguments
except TypeError:
format += " ".join(["%r" for i in arguments])
args = (format,) + arguments
return args
def critical(self, msg, *args):
self.warning(msg, *args)
#def error(self, msg, *args):
# self.log(msg, *args)
def msg(self, message, *args):
self.info(message, *args)
| [] |
2024-01-10 | opendreambox/python-coherence | misc~Totem-Plugin~upnp-coherence.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
import pygtk
pygtk.require("2.0")
import gtk
from coherence.ui.av_widgets import TreeWidget
from coherence.ui.av_widgets import UDN_COLUMN,UPNP_CLASS_COLUMN,SERVICE_COLUMN
import totem
class UPnPClient(totem.Plugin):
def __init__ (self):
totem.Plugin.__init__(self)
self.ui = TreeWidget()
self.ui.cb_item_right_click = self.button_pressed
self.ui.window.show_all()
selection = self.ui.treeview.get_selection()
selection.set_mode(gtk.SELECTION_MULTIPLE)
def button_pressed(self, widget, event):
if event.button == 3:
x = int(event.x)
y = int(event.y)
try:
row_path,column,_,_ = self.ui.treeview.get_path_at_pos(x, y)
selection = self.ui.treeview.get_selection()
if not selection.path_is_selected(row_path):
self.ui.treeview.set_cursor(row_path,column,False)
print "button_pressed", row_path, (row_path[0],)
iter = self.ui.store.get_iter((row_path[0],))
udn, = self.ui.store.get(iter,UDN_COLUMN)
iter = self.ui.store.get_iter(row_path)
upnp_class,url = self.ui.store.get(iter,UPNP_CLASS_COLUMN,SERVICE_COLUMN)
print udn, upnp_class, url
if(not upnp_class.startswith('object.container') and
not upnp_class == 'root'):
self.create_item_context(has_delete=self.ui.device_has_action(udn,'ContentDirectory','DestroyObject'))
self.context.popup(None,None,None,event.button,event.time)
return 1
except TypeError:
pass
return 1
def create_item_context(self,has_delete=False):
""" create context menu for right click in treeview item"""
def action(menu, text):
selection = self.ui.treeview.get_selection()
model, selected_rows = selection.get_selected_rows()
if text == 'item.delete':
for row_path in selected_rows:
self.ui.destroy_object(row_path)
return
if(len(selected_rows) > 0 and
text ==' item.play'):
row_path = selected_rows.pop(0)
iter = self.ui.store.get_iter(row_path)
url, = self.ui.store.get(iter,SERVICE_COLUMN)
self.totem_object.action_remote(totem.REMOTE_COMMAND_REPLACE,url)
self.totem_object.action_remote(totem.REMOTE_COMMAND_PLAY,url)
for row_path in selected_rows:
iter = self.ui.store.get_iter(row_path)
url, = self.ui.store.get(iter,SERVICE_COLUMN)
self.totem_object.action_remote(totem.REMOTE_COMMAND_ENQUEUE,url)
self.totem_object.action_remote(totem.REMOTE_COMMAND_PLAY,url)
if not hasattr(self, 'context_no_delete'):
self.context_no_delete = gtk.Menu()
play_menu = gtk.MenuItem("Play")
play_menu.connect("activate", action, 'item.play')
enqueue_menu = gtk.MenuItem("Enqueue")
enqueue_menu.connect("activate", action, 'item.enqueue')
self.context_no_delete.append(play_menu)
self.context_no_delete.append(enqueue_menu)
self.context_no_delete.show_all()
if not hasattr(self, 'context_with_delete'):
self.context_with_delete = gtk.Menu()
play_menu = gtk.MenuItem("Play")
play_menu.connect("activate", action, 'item.play')
enqueue_menu = gtk.MenuItem("Enqueue")
enqueue_menu.connect("activate", action, 'item.enqueue')
self.context_with_delete.append(play_menu)
self.context_with_delete.append(enqueue_menu)
self.context_with_delete.append(gtk.SeparatorMenuItem())
menu = gtk.MenuItem("Delete")
menu.connect("activate", action, 'item.delete')
self.context_with_delete.append(menu)
self.context_with_delete.show_all()
if has_delete:
self.context = self.context_with_delete
else:
self.context = self.context_no_delete
def activate (self, totem_object):
totem_object.add_sidebar_page ("upnp-coherence", _("Coherence DLNA/UPnP Client"), self.ui.window)
self.totem_object = totem_object
def load_and_play(url):
totem_object.action_remote(totem.REMOTE_COMMAND_REPLACE,url)
totem_object.action_remote(totem.REMOTE_COMMAND_PLAY,url)
self.ui.cb_item_dbl_click = load_and_play
def deactivate (self, totem_object):
totem_object.remove_sidebar_page ("upnp-coherence") | [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~radiotime_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# an internet radio media server for the Coherence UPnP Framework
# based on the radiotime (http://radiotime.com) catalog service
# Copyright 2007, Frank Scholz <[email protected]>
# Copyright 2009-2010, Jean-Michel Sizun <jmDOTsizunATfreeDOTfr>
from twisted.internet import defer,reactor
from twisted.python.failure import Failure
from twisted.web import server
from coherence.upnp.core import utils
from coherence.upnp.core import DIDLLite
from coherence.upnp.core.DIDLLite import classChooser, Resource, DIDLElement
from coherence import log
from coherence.backend import BackendItem, BackendStore, Container, LazyContainer, AbstractBackendStore
#from coherence.backends.iradio_storage import PlaylistStreamProxy
from urlparse import urlsplit
from coherence.extern.et import parse_xml
OPML_BROWSE_URL = 'http://opml.radiotime.com/Browse.ashx'
# we only handle mp3 audio streams for now
DEFAULT_FORMAT = "mp3"
DEFAULT_MIMETYPE = "audio/mpeg"
# TODO : extend format handling using radiotime API
class RadiotimeAudioItem(BackendItem):
logCategory = 'radiotime'
def __init__(self, outline):
self.preset_id = outline.get('preset_id')
self.name = outline.get('text')
self.mimetype = DEFAULT_MIMETYPE
self.stream_url = outline.get('URL')
self.image = outline.get('image')
#self.location = PlaylistStreamProxy(self.stream_url)
#self.url = self.stream_url
self.item = None
def replace_by (self, item):
# do nothing: we suppose the replacement item is the same
return
def get_item(self):
if self.item == None:
upnp_id = self.get_id()
upnp_parent_id = self.parent.get_id()
self.item = DIDLLite.AudioBroadcast(upnp_id, upnp_parent_id, self.name)
self.item.albumArtURI = self.image
res = Resource(self.stream_url, 'http-get:*:%s:%s' % (self.mimetype,
';'.join(('DLNA.ORG_PN=MP3',
'DLNA.ORG_CI=0',
'DLNA.ORG_OP=01',
'DLNA.ORG_FLAGS=01700000000000000000000000000000'))))
res.size = 0 #None
self.item.res.append(res)
return self.item
def get_path(self):
return self.url
def get_id(self):
return self.storage_id
class RadiotimeStore(AbstractBackendStore):
logCategory = 'radiotime'
implements = ['MediaServer']
def __init__(self, server, **kwargs):
AbstractBackendStore.__init__(self,server,**kwargs)
self.name = kwargs.get('name','radiotimeStore')
self.refresh = int(kwargs.get('refresh',60))*60
self.browse_url = self.config.get('browse_url', OPML_BROWSE_URL)
self.partner_id = self.config.get('partner_id', 'TMe3Cn6v')
self.username = self.config.get('username', None)
self.locale = self.config.get('locale', 'en')
self.serial = server.uuid
# construct URL for root menu
if self.username is not None:
identification_param = "username=%s" % self.username
else:
identification_param = "serial=%s" % self.serial
formats_value = DEFAULT_FORMAT
root_url = "%s?partnerId=%s&%s&formats=%s&locale=%s" % (self.browse_url, self.partner_id, identification_param, formats_value, self.locale)
# set root item
root_item = LazyContainer(None, "root", "root", self.refresh, self.retrieveItemsForOPML, url=root_url)
self.set_root_item(root_item)
self.init_completed()
def upnp_init(self):
self.current_connection_id = None
self.wmc_mapping = {'4': self.get_root_id()}
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
['http-get:*:audio/mpeg:*',
'http-get:*:audio/x-scpls:*'],
default=True)
def retrieveItemsForOPML (self, parent, url):
def append_outline (parent, outline):
type = outline.get('type')
if type is None:
# This outline is just a classification item containing other outline elements
# the corresponding item will a static Container
text = outline.get('text')
key = outline.get('key')
external_id = None
if external_id is None and key is not None:
external_id = "%s_%s" % (parent.external_id, key)
if external_id is None:
external_id = outline_url
item = Container(parent, text)
item.external_id = external_id
item.store = parent.store
parent.add_child(item, external_id=external_id)
sub_outlines = outline.findall('outline')
for sub_outline in sub_outlines:
append_outline(item, sub_outline)
elif type in ('link'):
# the corresponding item will a self-populating Container
text = outline.get('text')
outline_url = outline.get('URL')
key = outline.get('key')
guide_id = outline.get('guide_id')
external_id = guide_id
if external_id is None and key is not None:
external_id = "%s_%s" % (parent.external_id, key)
if external_id is None:
external_id = outline_url
item = LazyContainer(parent, text, external_id, self.refresh, self.retrieveItemsForOPML, url=outline_url)
parent.add_child(item, external_id=external_id)
elif type in ('audio'):
item = RadiotimeAudioItem(outline)
parent.add_child(item, external_id=item.preset_id)
def got_page(result):
self.info('connection to Radiotime service successful for url %s' % url)
outlines = result.findall('body/outline')
for outline in outlines:
append_outline(parent, outline)
return True
def got_error(error):
self.warning("connection to Radiotime service failed for url %s" % url)
self.debug("%r", error.getTraceback())
parent.childrenRetrievingNeeded = True # we retry
return Failure("Unable to retrieve items for url %s" % url)
def got_xml_error(error):
self.warning("Data received from Radiotime service is invalid: %s" % url)
#self.debug("%r", error.getTraceback())
print error.getTraceback()
parent.childrenRetrievingNeeded = True # we retry
return Failure("Unable to retrieve items for url %s" % url)
d = utils.getPage(url, )
d.addCallback(parse_xml)
d.addErrback(got_error)
d.addCallback(got_page)
d.addErrback(got_xml_error)
return d
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~fs_storage.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006, Frank Scholz <[email protected]>
import os, stat, glob
import tempfile
import shutil
import time
import re
from datetime import datetime
import urllib
from sets import Set
import mimetypes
mimetypes.init()
mimetypes.add_type('audio/x-m4a', '.m4a')
mimetypes.add_type('audio/x-musepack', '.mpc')
mimetypes.add_type('audio/x-wavpack', '.wv')
mimetypes.add_type('video/mp4', '.mp4')
mimetypes.add_type('video/mpegts', '.ts')
mimetypes.add_type('video/divx', '.divx')
mimetypes.add_type('video/divx', '.avi')
mimetypes.add_type('video/x-matroska', '.mkv')
from urlparse import urlsplit
from twisted.python.filepath import FilePath
from twisted.python import failure
from coherence.upnp.core.DIDLLite import classChooser, Container, Resource
from coherence.upnp.core.DIDLLite import DIDLElement
from coherence.upnp.core.DIDLLite import simple_dlna_tags
from coherence.upnp.core.soap_service import errorCode
from coherence.upnp.core import utils
try:
from coherence.extern.inotify import INotify
from coherence.extern.inotify import IN_CREATE, IN_DELETE, IN_MOVED_FROM, IN_MOVED_TO, IN_ISDIR
from coherence.extern.inotify import IN_CHANGED
haz_inotify = True
except Exception,msg:
haz_inotify = False
no_inotify_reason = msg
from coherence.extern.xdg import xdg_content
import coherence.extern.louie as louie
from coherence.backend import BackendItem, BackendStore
## Sorting helpers
NUMS = re.compile('([0-9]+)')
def _natural_key(s):
# strip the spaces
s = s.get_name().strip()
return [ part.isdigit() and int(part) or part.lower() for part in NUMS.split(s) ]
class NoThumbnailFound(Exception):
"""no thumbnail found"""
def _find_thumbnail(filename,thumbnail_folder='.thumbs'):
""" looks for a thumbnail file of the same basename
in a folder named '.thumbs' relative to the file
returns the filename of the thumb, its mimetype and the correspondig DLNA PN string
or throws an Exception otherwise
"""
name,ext = os.path.splitext(os.path.basename(filename))
pattern = os.path.join(os.path.dirname(filename),thumbnail_folder,name+'.*')
for f in glob.glob(pattern):
mimetype,_ = mimetypes.guess_type(f, strict=False)
if mimetype in ('image/jpeg','image/png'):
if mimetype == 'image/jpeg':
dlna_pn = 'DLNA.ORG_PN=JPEG_TN'
else:
dlna_pn = 'DLNA.ORG_PN=PNG_TN'
return os.path.abspath(f),mimetype,dlna_pn
else:
raise NoThumbnailFound()
class FSItem(BackendItem):
logCategory = 'fs_item'
def __init__(self, object_id, parent, path, mimetype, urlbase, UPnPClass,update=False,store=None):
self.id = object_id
self.parent = parent
if parent:
parent.add_child(self,update=update)
if mimetype == 'root':
self.location = unicode(path)
else:
if mimetype == 'item' and path is None:
path = os.path.join(parent.get_realpath(),unicode(self.id))
#self.location = FilePath(unicode(path))
self.location = FilePath(path)
self.mimetype = mimetype
if urlbase[-1] != '/':
urlbase += '/'
self.url = urlbase + str(self.id)
self.store = store
if parent == None:
parent_id = -1
else:
parent_id = parent.get_id()
self.item = UPnPClass(object_id, parent_id, self.get_name())
if isinstance(self.item, Container):
self.item.childCount = 0
self.child_count = 0
self.children = []
self.sorted = False
self.caption = None
if mimetype in ['directory','root']:
self.update_id = 0
self.get_url = lambda : self.url
self.get_path = lambda : None
#self.item.searchable = True
#self.item.searchClass = 'object'
if(isinstance(self.location,FilePath) and
self.location.isdir() == True):
self.check_for_cover_art()
if hasattr(self, 'cover'):
_,ext = os.path.splitext(self.cover)
""" add the cover image extension to help clients not reacting on
the mimetype """
self.item.albumArtURI = ''.join((urlbase,str(self.id),'?cover',ext))
else:
self.get_url = lambda : self.url
if self.mimetype.startswith('audio/'):
if hasattr(parent, 'cover'):
_,ext = os.path.splitext(parent.cover)
""" add the cover image extension to help clients not reacting on
the mimetype """
self.item.albumArtURI = ''.join((urlbase,str(self.id),'?cover',ext))
_,host_port,_,_,_ = urlsplit(urlbase)
if host_port.find(':') != -1:
host,port = tuple(host_port.split(':'))
else:
host = host_port
try:
size = self.location.getsize()
except:
size = 0
if self.store.server.coherence.config.get('transcoding', 'no') == 'yes':
if self.mimetype in ('application/ogg','audio/ogg',
'audio/x-wav',
'audio/x-m4a',
'application/x-flac'):
new_res = Resource(self.url+'/transcoded.mp3',
'http-get:*:%s:*' % 'audio/mpeg')
new_res.size = None
#self.item.res.append(new_res)
if mimetype != 'item':
res = Resource('file://'+ urllib.quote(self.get_path()), 'internal:%s:%s:*' % (host,self.mimetype))
res.size = size
self.item.res.append(res)
if mimetype != 'item':
res = Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
else:
res = Resource(self.url, 'http-get:*:*:*')
res.size = size
self.item.res.append(res)
""" if this item is of type audio and we want to add a transcoding rule for it,
this is the way to do it:
create a new Resource object, at least a 'http-get'
and maybe an 'internal' one too
for transcoding to wav this looks like that
res = Resource(url_for_transcoded audio,
'http-get:*:audio/x-wav:%s'% ';'.join(['DLNA.ORG_PN=JPEG_TN']+simple_dlna_tags))
res.size = None
self.item.res.append(res)
"""
if self.store.server.coherence.config.get('transcoding', 'no') == 'yes':
if self.mimetype in ('audio/mpeg',
'application/ogg','audio/ogg',
'audio/x-wav',
'audio/x-m4a',
'audio/flac',
'application/x-flac'):
dlna_pn = 'DLNA.ORG_PN=LPCM'
dlna_tags = simple_dlna_tags[:]
#dlna_tags[1] = 'DLNA.ORG_OP=00'
dlna_tags[2] = 'DLNA.ORG_CI=1'
new_res = Resource(self.url+'?transcoded=lpcm',
'http-get:*:%s:%s' % ('audio/L16;rate=44100;channels=2', ';'.join([dlna_pn]+dlna_tags)))
new_res.size = None
#self.item.res.append(new_res)
if self.mimetype != 'audio/mpeg':
new_res = Resource(self.url+'?transcoded=mp3',
'http-get:*:%s:*' % 'audio/mpeg')
new_res.size = None
#self.item.res.append(new_res)
""" if this item is an image and we want to add a thumbnail for it
we have to follow these rules:
create a new Resource object, at least a 'http-get'
and maybe an 'internal' one too
for an JPG this looks like that
res = Resource(url_for_thumbnail,
'http-get:*:image/jpg:%s'% ';'.join(['DLNA.ORG_PN=JPEG_TN']+simple_dlna_tags))
res.size = size_of_thumbnail
self.item.res.append(res)
and for a PNG the Resource creation is like that
res = Resource(url_for_thumbnail,
'http-get:*:image/png:%s'% ';'.join(simple_dlna_tags+['DLNA.ORG_PN=PNG_TN']))
if not hasattr(self.item, 'attachments'):
self.item.attachments = {}
self.item.attachments[key] = utils.StaticFile(filename_of_thumbnail)
"""
if(self.mimetype in ('image/jpeg', 'image/png') or
self.mimetype.startswith('video/')):
try:
filename,mimetype,dlna_pn = _find_thumbnail(self.get_path())
except NoThumbnailFound:
pass
except:
self.warning(traceback.format_exc())
else:
dlna_tags = simple_dlna_tags[:]
dlna_tags[3] = 'DLNA.ORG_FLAGS=00f00000000000000000000000000000'
hash_from_path = str(id(filename))
new_res = Resource(self.url+'?attachment='+hash_from_path,
'http-get:*:%s:%s' % (mimetype, ';'.join([dlna_pn]+dlna_tags)))
new_res.size = os.path.getsize(filename)
self.item.res.append(new_res)
if not hasattr(self.item, 'attachments'):
self.item.attachments = {}
self.item.attachments[hash_from_path] = utils.StaticFile(filename)
if self.mimetype.startswith('video/'):
# check for a subtitles file
caption,_ = os.path.splitext(self.get_path())
caption = caption + '.srt'
if os.path.exists(caption):
hash_from_path = str(id(caption))
mimetype = 'smi/caption'
new_res = Resource(self.url+'?attachment='+hash_from_path,
'http-get:*:%s:%s' % (mimetype, '*'))
new_res.size = os.path.getsize(caption)
self.caption = new_res.data
self.item.res.append(new_res)
if not hasattr(self.item, 'attachments'):
self.item.attachments = {}
self.item.attachments[hash_from_path] = utils.StaticFile(caption)
try:
# FIXME: getmtime is deprecated in Twisted 2.6
self.item.date = datetime.fromtimestamp(self.location.getmtime())
except:
self.item.date = None
def rebuild(self, urlbase):
#print "rebuild", self.mimetype
if self.mimetype != 'item':
return
#print "rebuild for", self.get_path()
mimetype,_ = mimetypes.guess_type(self.get_path(),strict=False)
if mimetype == None:
return
self.mimetype = mimetype
#print "rebuild", self.mimetype
UPnPClass = classChooser(self.mimetype)
self.item = UPnPClass(self.id, self.parent.id, self.get_name())
if hasattr(self.parent, 'cover'):
_,ext = os.path.splitext(self.parent.cover)
""" add the cover image extension to help clients not reacting on
the mimetype """
self.item.albumArtURI = ''.join((urlbase,str(self.id),'?cover',ext))
_,host_port,_,_,_ = urlsplit(urlbase)
if host_port.find(':') != -1:
host,port = tuple(host_port.split(':'))
else:
host = host_port
res = Resource('file://'+urllib.quote(self.get_path()), 'internal:%s:%s:*' % (host,self.mimetype))
try:
res.size = self.location.getsize()
except:
res.size = 0
self.item.res.append(res)
res = Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
try:
res.size = self.location.getsize()
except:
res.size = 0
self.item.res.append(res)
try:
# FIXME: getmtime is deprecated in Twisted 2.6
self.item.date = datetime.fromtimestamp(self.location.getmtime())
except:
self.item.date = None
self.parent.update_id += 1
def check_for_cover_art(self):
""" let's try to find in the current directory some jpg file,
or png if the jpg search fails, and take the first one
that comes around
"""
try:
jpgs = [i.path for i in self.location.children() if i.splitext()[1] in ('.jpg', '.JPG')]
try:
self.cover = jpgs[0]
except IndexError:
pngs = [i.path for i in self.location.children() if i.splitext()[1] in ('.png', '.PNG')]
try:
self.cover = pngs[0]
except IndexError:
return
except UnicodeDecodeError:
self.warning("UnicodeDecodeError - there is something wrong with a file located in %r", self.location.path)
def remove(self):
#print "FSItem remove", self.id, self.get_name(), self.parent
if self.parent:
self.parent.remove_child(self)
del self.item
def add_child(self, child, update=False):
self.children.append(child)
self.child_count += 1
if isinstance(self.item, Container):
self.item.childCount += 1
if update == True:
self.update_id += 1
self.sorted = False
def remove_child(self, child):
#print "remove_from %d (%s) child %d (%s)" % (self.id, self.get_name(), child.id, child.get_name())
if child in self.children:
self.child_count -= 1
if isinstance(self.item, Container):
self.item.childCount -= 1
self.children.remove(child)
self.update_id += 1
self.sorted = False
def get_children(self,start=0,request_count=0):
if self.sorted == False:
self.children.sort(key=_natural_key)
self.sorted = True
if request_count == 0:
return self.children[start:]
else:
return self.children[start:request_count]
def get_child_count(self):
return self.child_count
def get_id(self):
return self.id
def get_update_id(self):
if hasattr(self, 'update_id'):
return self.update_id
else:
return None
def get_path(self):
if isinstance( self.location,FilePath):
return self.location.path
else:
self.location
def get_realpath(self):
if isinstance( self.location,FilePath):
return self.location.path
else:
self.location
def set_path(self,path=None,extension=None):
if path is None:
path = self.get_path()
if extension is not None:
path,old_ext = os.path.splitext(path)
path = ''.join((path,extension))
if isinstance( self.location,FilePath):
self.location = FilePath(path)
else:
self.location = path
def get_name(self):
if isinstance(self.location,FilePath):
name = self.location.basename().decode("utf-8", "replace")
else:
name = self.location.decode("utf-8", "replace")
return name
def get_cover(self):
try:
return self.cover
except:
try:
return self.parent.cover
except:
return ''
def get_parent(self):
return self.parent
def get_item(self):
return self.item
def get_xml(self):
return self.item.toString()
def __repr__(self):
return 'id: ' + str(self.id) + ' @ ' + self.get_name().encode('ascii','xmlcharrefreplace')
class FSStore(BackendStore):
logCategory = 'fs_store'
implements = ['MediaServer']
description = """MediaServer exporting files from the file-system"""
options = [{'option':'name','type':'string','default':'my media','help': 'the name under this MediaServer shall show up with on other UPnP clients'},
{'option':'version','type':'int','default':2,'enum': (2,1),'help': 'the highest UPnP version this MediaServer shall support','level':'advance'},
{'option':'uuid','type':'string','help':'the unique (UPnP) identifier for this MediaServer, usually automatically set','level':'advance'},
{'option':'content','type':'string','default':xdg_content(),'help':'the path(s) this MediaServer shall export'},
{'option':'ignore_patterns','type':'string','help':'list of regex patterns, matching filenames will be ignored'},
{'option':'enable_inotify','type':'string','default':'yes','help':'enable real-time monitoring of the content folders'},
{'option':'enable_destroy','type':'string','default':'no','help':'enable deleting a file via an UPnP method'},
{'option':'import_folder','type':'string','help':'The path to store files imported via an UPnP method, if empty the Import method is disabled'}
]
def __init__(self, server, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.next_id = 1000
self.name = kwargs.get('name','my media')
self.content = kwargs.get('content',None)
if self.content != None:
if isinstance(self.content,basestring):
self.content = [self.content]
l = []
for a in self.content:
l += a.split(',')
self.content = l
else:
self.content = xdg_content()
self.content = [x[0] for x in self.content]
if self.content == None:
self.content = 'tests/content'
if not isinstance( self.content, list):
self.content = [self.content]
self.content = Set([os.path.abspath(x) for x in self.content])
ignore_patterns = kwargs.get('ignore_patterns',[])
self.store = {}
self.inotify = None
if kwargs.get('enable_inotify','yes') == 'yes':
if haz_inotify == True:
try:
self.inotify = INotify()
except Exception,msg:
self.info("%s" %msg)
else:
self.info("%s" %no_inotify_reason)
else:
self.info("FSStore content auto-update disabled upon user request")
if kwargs.get('enable_destroy','no') == 'yes':
self.upnp_DestroyObject = self.hidden_upnp_DestroyObject
self.import_folder = kwargs.get('import_folder',None)
if self.import_folder != None:
self.import_folder = os.path.abspath(self.import_folder)
if not os.path.isdir(self.import_folder):
self.import_folder = None
self.ignore_file_pattern = re.compile('|'.join(['^\..*'] + list(ignore_patterns)))
parent = None
self.update_id = 0
if(len(self.content)>1 or
utils.means_true(kwargs.get('create_root',False)) or
self.import_folder != None):
UPnPClass = classChooser('root')
id = str(self.getnextID())
parent = self.store[id] = FSItem( id, parent, 'media', 'root', self.urlbase, UPnPClass, update=True,store=self)
if self.import_folder != None:
id = str(self.getnextID())
self.store[id] = FSItem( id, parent, self.import_folder, 'directory', self.urlbase, UPnPClass, update=True,store=self)
self.import_folder_id = id
for path in self.content:
if isinstance(path,(list,tuple)):
path = path[0]
if self.ignore_file_pattern.match(path):
continue
try:
path = path.encode('utf-8') # patch for #267
self.walk(path, parent, self.ignore_file_pattern)
except Exception,msg:
self.warning('on walk of %r: %r' % (path,msg))
import traceback
self.debug(traceback.format_exc())
self.wmc_mapping.update({'14': '0',
'15': '0',
'16': '0',
'17': '0'
})
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
def __repr__(self):
return str(self.__class__).split('.')[-1]
def release(self):
if self.inotify != None:
self.inotify.release()
def len(self):
return len(self.store)
def get_by_id(self,id):
#print "get_by_id", id, type(id)
# we have referenced ids here when we are in WMC mapping mode
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
#try:
# id = int(id)
#except ValueError:
# id = 1000
if id == '0':
id = '1000'
#print "get_by_id 2", id
try:
r = self.store[id]
except:
r = None
#print "get_by_id 3", r
return r
def get_id_by_name(self, parent='0', name=''):
self.info('get_id_by_name %r (%r) %r' % (parent, type(parent), name))
try:
parent = self.store[parent]
self.debug("%r %d" % (parent,len(parent.children)))
for child in parent.children:
#if not isinstance(name, unicode):
# name = name.decode("utf8")
self.debug("%r %r %r" % (child.get_name(),child.get_realpath(), name == child.get_realpath()))
if name == child.get_realpath():
return child.id
except:
import traceback
self.info(traceback.format_exc())
self.debug('get_id_by_name not found')
return None
def get_url_by_name(self,parent='0',name=''):
self.info('get_url_by_name %r %r' % (parent, name))
id = self.get_id_by_name(parent,name)
#print 'get_url_by_name', id
if id == None:
return ''
return self.store[id].url
def update_config(self,**kwargs):
print "update_config", kwargs
if 'content' in kwargs:
new_content = kwargs['content']
new_content = Set([os.path.abspath(x) for x in new_content.split(',')])
new_folders = new_content.difference(self.content)
obsolete_folders = self.content.difference(new_content)
print new_folders, obsolete_folders
for folder in obsolete_folders:
self.remove_content_folder(folder)
for folder in new_folders:
self.add_content_folder(folder)
self.content = new_content
def add_content_folder(self,path):
path = os.path.abspath(path)
if path not in self.content:
self.content.add(path)
self.walk(path, self.store['1000'], self.ignore_file_pattern)
def remove_content_folder(self,path):
path = os.path.abspath(path)
if path in self.content:
id = self.get_id_by_name('1000', path)
self.remove(id)
self.content.remove(path)
def walk(self, path, parent=None, ignore_file_pattern=''):
self.debug("walk %r" % path)
containers = []
parent = self.append(path,parent)
if parent != None:
containers.append(parent)
while len(containers)>0:
container = containers.pop()
try:
self.debug('adding %r' % container.location)
for child in container.location.children():
if ignore_file_pattern.match(child.basename()) != None:
continue
new_container = self.append(child.path,container)
if new_container != None:
containers.append(new_container)
except UnicodeDecodeError:
self.warning("UnicodeDecodeError - there is something wrong with a file located in %r", container.get_path())
def create(self, mimetype, path, parent):
self.debug("create ", mimetype, path, type(path), parent)
UPnPClass = classChooser(mimetype)
if UPnPClass == None:
return None
id = self.getnextID()
if mimetype in ('root','directory'):
id = str(id)
else:
_,ext = os.path.splitext(path)
id = str(id) + ext.lower()
update = False
if hasattr(self, 'update_id'):
update = True
self.store[id] = FSItem( id, parent, path, mimetype, self.urlbase, UPnPClass, update=True,store=self)
if hasattr(self, 'update_id'):
self.update_id += 1
#print self.update_id
if self.server:
if hasattr(self.server,'content_directory_server'):
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
if parent is not None:
value = (parent.get_id(),parent.get_update_id())
if self.server:
if hasattr(self.server,'content_directory_server'):
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
return id
def append(self,path,parent):
self.debug("append ", path, type(path), parent)
if os.path.exists(path) == False:
self.warning("path %r not available - ignored", path)
return None
if stat.S_ISFIFO(os.stat(path).st_mode):
self.warning("path %r is a FIFO - ignored", path)
return None
try:
mimetype,_ = mimetypes.guess_type(path, strict=False)
if mimetype == None:
if os.path.isdir(path):
mimetype = 'directory'
if mimetype == None:
return None
id = self.create(mimetype,path,parent)
if mimetype == 'directory':
if self.inotify is not None:
mask = IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_CHANGED
self.inotify.watch(path, mask=mask, auto_add=False, callbacks=(self.notify,id))
return self.store[id]
except OSError, msg:
""" seems we have some permissions issues along the content path """
self.warning("path %r isn't accessible, error %r", path, msg)
return None
def remove(self, id):
print 'FSSTore remove id', id
try:
item = self.store[id]
parent = item.get_parent()
item.remove()
del self.store[id]
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
#value = '%d,%d' % (parent.get_id(),parent_get_update_id())
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
except:
pass
def notify(self, iwp, filename, mask, parameter=None):
self.info("Event %s on %s %s - parameter %r" % (
', '.join(self.inotify.flag_to_human(mask)), iwp.path, filename, parameter))
path = iwp.path
if filename:
path = os.path.join(path, filename)
if mask & IN_CHANGED:
# FIXME react maybe on access right changes, loss of read rights?
#print '%s was changed, parent %d (%s)' % (path, parameter, iwp.path)
pass
if(mask & IN_DELETE or mask & IN_MOVED_FROM):
self.info('%s was deleted, parent %r (%s)' % (path, parameter, iwp.path))
id = self.get_id_by_name(parameter,os.path.join(iwp.path,filename))
if id != None:
self.remove(id)
if(mask & IN_CREATE or mask & IN_MOVED_TO):
if mask & IN_ISDIR:
self.info('directory %s was created, parent %r (%s)' % (path, parameter, iwp.path))
else:
self.info('file %s was created, parent %r (%s)' % (path, parameter, iwp.path))
if self.get_id_by_name(parameter,os.path.join(iwp.path,filename)) is None:
if os.path.isdir(path):
self.walk(path, self.get_by_id(parameter), self.ignore_file_pattern)
else:
if self.ignore_file_pattern.match(filename) == None:
self.append(path, self.get_by_id(parameter))
def getnextID(self):
ret = self.next_id
self.next_id += 1
return ret
def backend_import(self,item,data):
try:
f = open(item.get_path(), 'w+b')
if hasattr(data,'read'):
data = data.read()
f.write(data)
f.close()
item.rebuild(self.urlbase)
return 200
except IOError:
self.warning("import of file %s failed" % item.get_path())
except Exception,msg:
import traceback
self.warning(traceback.format_exc())
return 500
def upnp_init(self):
self.current_connection_id = None
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
[#'http-get:*:audio/mpeg:DLNA.ORG_PN=MP3;DLNA.ORG_OP=11;DLNA.ORG_FLAGS=01700000000000000000000000000000',
#'http-get:*:audio/x-ms-wma:DLNA.ORG_PN=WMABASE;DLNA.ORG_OP=11;DLNA.ORG_FLAGS=01700000000000000000000000000000',
#'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000',
#'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_SM;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000',
#'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_MED;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000',
#'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_LRG;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000',
#'http-get:*:video/mpeg:DLNA.ORG_PN=MPEG_PS_PAL;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=01700000000000000000000000000000',
#'http-get:*:video/x-ms-wmv:DLNA.ORG_PN=WMVMED_BASE;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=01700000000000000000000000000000',
'internal:%s:audio/mpeg:*' % self.server.coherence.hostname,
'http-get:*:audio/mpeg:*',
'internal:%s:video/mp4:*' % self.server.coherence.hostname,
'http-get:*:video/mp4:*',
'internal:%s:application/ogg:*' % self.server.coherence.hostname,
'http-get:*:application/ogg:*',
'internal:%s:video/x-msvideo:*' % self.server.coherence.hostname,
'http-get:*:video/x-msvideo:*',
'internal:%s:video/mpeg:*' % self.server.coherence.hostname,
'http-get:*:video/mpeg:*',
'internal:%s:video/avi:*' % self.server.coherence.hostname,
'http-get:*:video/avi:*',
'internal:%s:video/divx:*' % self.server.coherence.hostname,
'http-get:*:video/divx:*',
'internal:%s:video/quicktime:*' % self.server.coherence.hostname,
'http-get:*:video/quicktime:*',
'internal:%s:image/gif:*' % self.server.coherence.hostname,
'http-get:*:image/gif:*',
'internal:%s:image/jpeg:*' % self.server.coherence.hostname,
'http-get:*:image/jpeg:*'],
default=True)
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
#self.server.content_directory_server.set_variable(0, 'SortCapabilities', '*')
def upnp_ImportResource(self, *args, **kwargs):
SourceURI = kwargs['SourceURI']
DestinationURI = kwargs['DestinationURI']
if DestinationURI.endswith('?import'):
id = DestinationURI.split('/')[-1]
id = id[:-7] # remove the ?import
else:
return failure.Failure(errorCode(718))
item = self.get_by_id(id)
if item == None:
return failure.Failure(errorCode(718))
def gotPage(headers):
#print "gotPage", headers
content_type = headers.get('content-type',[])
if not isinstance(content_type, list):
content_type = list(content_type)
if len(content_type) > 0:
extension = mimetypes.guess_extension(content_type[0], strict=False)
item.set_path(None,extension)
shutil.move(tmp_path, item.get_path())
item.rebuild(self.urlbase)
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
if hasattr(self.server,'content_directory_server'):
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
if item.parent is not None:
value = (item.parent.get_id(),item.parent.get_update_id())
if self.server:
if hasattr(self.server,'content_directory_server'):
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
def gotError(error, url):
self.warning("error requesting", url)
self.info(error)
os.unlink(tmp_path)
return failure.Failure(errorCode(718))
tmp_fp, tmp_path = tempfile.mkstemp()
os.close(tmp_fp)
utils.downloadPage(SourceURI,
tmp_path).addCallbacks(gotPage, gotError, None, None, [SourceURI], None)
transfer_id = 0 #FIXME
return {'TransferID': transfer_id}
def upnp_CreateObject(self, *args, **kwargs):
#print "CreateObject", kwargs
if kwargs['ContainerID'] == 'DLNA.ORG_AnyContainer':
if self.import_folder != None:
ContainerID = self.import_folder_id
else:
return failure.Failure(errorCode(712))
else:
ContainerID = kwargs['ContainerID']
Elements = kwargs['Elements']
parent_item = self.get_by_id(ContainerID)
if parent_item == None:
return failure.Failure(errorCode(710))
if parent_item.item.restricted:
return failure.Failure(errorCode(713))
if len(Elements) == 0:
return failure.Failure(errorCode(712))
elt = DIDLElement.fromString(Elements)
if elt.numItems() != 1:
return failure.Failure(errorCode(712))
item = elt.getItems()[0]
if item.parentID == 'DLNA.ORG_AnyContainer':
item.parentID = ContainerID
if(item.id != '' or
item.parentID != ContainerID or
item.restricted == True or
item.title == ''):
return failure.Failure(errorCode(712))
if('..' in item.title or
'~' in item.title or
os.sep in item.title):
return failure.Failure(errorCode(712))
if item.upnp_class == 'object.container.storageFolder':
if len(item.res) != 0:
return failure.Failure(errorCode(712))
path = os.path.join(parent_item.get_path(),item.title)
id = self.create('directory',path,parent_item)
try:
os.mkdir(path)
except:
self.remove(id)
return failure.Failure(errorCode(712))
if self.inotify is not None:
mask = IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_CHANGED
self.inotify.watch(path, mask=mask, auto_add=False, callbacks=(self.notify,id))
new_item = self.get_by_id(id)
didl = DIDLElement()
didl.addItem(new_item.item)
return {'ObjectID': id, 'Result': didl.toString()}
if item.upnp_class.startswith('object.item'):
_,_,content_format,_ = item.res[0].protocolInfo.split(':')
extension = mimetypes.guess_extension(content_format, strict=False)
path = os.path.join(parent_item.get_realpath(),item.title+extension)
id = self.create('item',path,parent_item)
new_item = self.get_by_id(id)
for res in new_item.item.res:
res.importUri = new_item.url+'?import'
res.data = None
didl = DIDLElement()
didl.addItem(new_item.item)
return {'ObjectID': id, 'Result': didl.toString()}
return failure.Failure(errorCode(712))
def hidden_upnp_DestroyObject(self, *args, **kwargs):
ObjectID = kwargs['ObjectID']
item = self.get_by_id(ObjectID)
if item == None:
return failure.Failure(errorCode(701))
print "upnp_DestroyObject", item.location
try:
item.location.remove()
except Exception, msg:
print Exception, msg
return failure.Failure(errorCode(715))
return {}
if __name__ == '__main__':
from twisted.internet import reactor
p = 'tests/content'
f = FSStore(None,name='my media',content=p, urlbase='http://localhost/xyz')
print f.len()
print f.get_by_id(1000).child_count, f.get_by_id(1000).get_xml()
print f.get_by_id(1001).child_count, f.get_by_id(1001).get_xml()
print f.get_by_id(1002).child_count, f.get_by_id(1002).get_xml()
print f.get_by_id(1003).child_count, f.get_by_id(1003).get_xml()
print f.get_by_id(1004).child_count, f.get_by_id(1004).get_xml()
print f.get_by_id(1005).child_count, f.get_by_id(1005).get_xml()
print f.store[1000].get_children(0,0)
#print f.upnp_Search(ContainerID ='4',
# Filter ='dc:title,upnp:artist',
# RequestedCount = '1000',
# StartingIndex = '0',
# SearchCriteria = '(upnp:class = "object.container.album.musicAlbum")',
# SortCriteria = '+dc:title')
f.upnp_ImportResource(SourceURI='http://spiegel.de',DestinationURI='ttt')
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~dbus_service.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007,2008,2009 - Frank Scholz <[email protected]>
""" DBUS service class
"""
import time
import urllib, urlparse
#import gtk
import dbus
if dbus.__version__ < '0.82.2':
raise ImportError('dbus-python module too old, pls get a newer one from http://dbus.freedesktop.org/releases/dbus-python/')
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
import dbus.service
#import dbus.gobject_service
#import dbus.glib
from coherence import __version__
from coherence.upnp.core import DIDLLite
from coherence.dbus_constants import *
from coherence.upnp.core.utils import parse_xml
import coherence.extern.louie as louie
from coherence import log
from twisted.internet import reactor
from twisted.internet import defer, task
namespaces = {'{http://purl.org/dc/elements/1.1/}':'dc:',
'{urn:schemas-upnp-org:metadata-1-0/upnp/}': 'upnp:',
'{urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/}': 'DIDL-Lite:',
'{urn:schemas-dlna-org:metadata-1-0}': 'dlna:',
'{http://www.pv.com/pvns/}': 'pv:'}
def un_namespace(text):
for k,v in namespaces.items():
if text.startswith(k):
return text.replace(k,v)
return text
class DBusCDSService(dbus.service.Object,log.Loggable):
logCategory = 'dbus'
NOT_FOR_THE_TUBES = True
def __init__(self, service, dbus_device, bus):
self.service = service
self.dbus_device = dbus_device
self.type = self.service.service_type.split(':')[3] # get the service name
bus_name = dbus.service.BusName(CDS_SERVICE, bus)
device_id = dbus_device.id
self.path = OBJECT_PATH + '/devices/' + device_id + '/services/' + 'CDS'
dbus.service.Object.__init__(self, bus, bus_name=bus_name,
object_path=self.path)
self.debug("DBusService %r %r", service, self.type)
louie.connect(self.variable_changed, 'StateVariable.changed', sender=self.service)
self.subscribeStateVariables()
def shutdown(self):
self._release_thyself(suicide_mode=False)
def _release_thyself(self, suicide_mode=True):
louie.disconnect(self.variable_changed, 'StateVariable.changed', sender=self.service)
self.service = None
self.dbus_device = None
self.remove_from_connection()
self.path = None
if suicide_mode:
del self
def variable_changed(self,variable):
self.StateVariableChanged(self.dbus_device.device.get_id(),self.type,variable.name, variable.value)
@dbus.service.method(CDS_SERVICE,in_signature='',out_signature='s')
def get_id(self):
return self.service.id
@dbus.service.method(CDS_SERVICE,in_signature='',out_signature='s')
def get_scpd_xml(self):
return self.service.scpdXML
@dbus.service.signal(CDS_SERVICE,
signature='sssv')
def StateVariableChanged(self, udn, service, variable, value):
self.info("%s service %s signals StateVariable %s changed to %r" % (self.dbus_device.device.get_friendly_name(), self.type, variable, value))
@dbus.service.method(CDS_SERVICE,in_signature='',out_signature='as')
def getAvailableActions(self):
actions = self.service.get_actions()
r = []
for name in actions.keys():
r.append(name)
return r
@dbus.service.method(CDS_SERVICE,in_signature='',out_signature='ssv')
def subscribeStateVariables(self):
if not self.service:
return
notify = [v for v in self.service._variables[0].values() if v.send_events == True]
if len(notify) == 0:
return
data = {}
for n in notify:
if n.name == 'LastChange':
lc = {}
for instance, vdict in self.service._variables.items():
v = {}
for variable in vdict.values():
if( variable.name != 'LastChange' and
variable.name[0:11] != 'A_ARG_TYPE_' and
variable.never_evented == False):
if hasattr(variable, 'dbus_updated') == False:
variable.dbus_updated = None
if len(v) > 0:
lc[str(instance)] = v
if len(lc) > 0:
data[unicode(n.name)] = lc
else:
data[unicode(n.name)] = unicode(n.value)
return self.dbus_device.device.get_id(), self.type, dbus.Dictionary(data,signature='sv',variant_level=3)
@dbus.service.method(CDS_SERVICE,in_signature='',out_signature='s',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def GetSearchCapabilites(self,dbus_async_cb,dbus_async_err_cb):
r = self.callAction('GetSearchCapabilites',{})
if r == '':
return r
def convert_reply(data):
dbus_async_cb(unicode(data['SearchCaps']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='',out_signature='s',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def GetSortCapabilities(self,dbus_async_cb,dbus_async_err_cb):
r = self.callAction('GetSortCapabilities',{})
if r == '':
return r
def convert_reply(data):
dbus_async_cb(unicode(data['SortCaps']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='',out_signature='s',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def GetSortExtensionCapabilities(self,dbus_async_cb,dbus_async_err_cb):
r = self.callAction('GetSortExtensionCapabilities',{})
if r == '':
return r
def convert_reply(data):
dbus_async_cb(unicode(data['SortExtensionCaps']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='',out_signature='s',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def GetFeatureList(self,dbus_async_cb,dbus_async_err_cb):
r = self.callAction('GetFeatureList',{})
if r == '':
return r
def convert_reply(data):
dbus_async_cb(unicode(data['FeatureList']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='',out_signature='i',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def GetSystemUpdateID(self,dbus_async_cb,dbus_async_err_cb):
r = self.callAction('GetSystemUpdateID',{})
if r == '':
return r
def convert_reply(data):
dbus_async_cb(int(data['Id']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='sssiis',out_signature='aa{sv}iii', # was viii
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def Browse(self,ObjectID, BrowseFlag, Filter, StartingIndex, RequestedCount,SortCriteria,
dbus_async_cb,dbus_async_err_cb):
arguments = {'ObjectID':unicode(ObjectID),
'BrowseFlag':unicode(BrowseFlag),
'Filter':unicode(Filter),
'StartingIndex':int(StartingIndex),
'RequestedCount':int(RequestedCount),
'SortCriteria':unicode(SortCriteria)}
r = self.callAction('Browse',arguments)
if r == '':
return r
def convert_reply(data):
et = parse_xml(data['Result'], 'utf-8')
et = et.getroot()
items = dbus.Array([],signature='v')
def append(item):
i = dbus.Dictionary({},signature='sv')
for k,v in item.attrib.items():
i[un_namespace(k)] = v
res = dbus.Array([],signature='v')
for child in item:
if un_namespace(child.tag) == 'DIDL-Lite:res':
res_dict = dbus.Dictionary({},signature='sv')
res_dict['url'] = unicode(child.text)
for k,v in child.attrib.items():
res_dict[un_namespace(k)] = v
res.append(res_dict)
else:
i[un_namespace(child.tag)] = child.text
if len(res):
i['res'] = res
items.append(i)
for item in et:
append(item)
dbus_async_cb(items,int(data['NumberReturned']),int(data['TotalMatches']),int(data['UpdateID']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='sssiis',out_signature='aa{sv}iii',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def Search(self,ContainerID,SearchCriteria,Filter,StartingIndex,RequestedCount,SortCriteria,
dbus_async_cb,dbus_async_err_cb):
arguments = {'ContainerID':unicode(ContainerID),
'SearchCriteria':unicode(SearchCriteria),
'Filter':unicode(Filter),
'StartingIndex':int(StartingIndex),
'RequestedCount':int(RequestedCount),
'SortCriteria':unicode(SortCriteria)}
r = self.callAction('Search',arguments)
if r == '':
return r
def convert_reply(data):
et = parse_xml(data['Result'], 'utf-8')
et = et.getroot()
items = dbus.Array([],signature='v')
def append(item):
i = dbus.Dictionary({},signature='sv')
for k,v in item.attrib.items():
i[un_namespace(k)] = v
res = dbus.Array([],signature='v')
for child in item:
if un_namespace(child.tag) == 'DIDL-Lite:res':
res_dict = dbus.Dictionary({},signature='sv')
res_dict['url'] = unicode(child.text)
for k,v in child.attrib.items():
res_dict[un_namespace(k)] = v
res.append(res_dict)
else:
i[un_namespace(child.tag)] = child.text
if len(res):
i['res'] = res
items.append(i)
for item in et:
append(item)
dbus_async_cb(items,int(data['NumberReturned']),int(data['TotalMatches']),int(data['UpdateID']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='ss',out_signature='ss',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def CreateObject(self,ContainerID,Elements,
dbus_async_cb,dbus_async_err_cb):
arguments = {'ContainerID':unicode(ContainerID),
'Elements':unicode(Elements)}
r = self.callAction('CreateObject',arguments)
if r == '':
return r
def convert_reply(data):
dbus_async_cb(unicode(data['ObjectID']),unicode(data['Result']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='s',out_signature='',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def DestroyObject(self,ObjectID,
dbus_async_cb,dbus_async_err_cb):
arguments = {'ObjectID':unicode(ObjectID)}
r = self.callAction('DestroyObject',arguments)
if r == '':
return r
def convert_reply(data):
dbus_async_cb()
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='sss',out_signature='',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def UpdateObject(self,ObjectID,CurrentTagValue,NewTagValue,
dbus_async_cb,dbus_async_err_cb):
arguments = {'ObjectID':unicode(ObjectID),
'CurrentTagValue':unicode(CurrentTagValue),
'NewTagValue':NewTagValue}
r = self.callAction('UpdateObject',arguments)
if r == '':
return r
def convert_reply(data):
dbus_async_cb()
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='ss',out_signature='s',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def MoveObject(self,ObjectID,NewParentID,
dbus_async_cb,dbus_async_err_cb):
arguments = {'ObjectID':unicode(ObjectID),
'NewParentID':unicode(NewParentID)}
r = self.callAction('MoveObject',arguments)
if r == '':
return r
def convert_reply(data):
dbus_async_cb(unicode(data['NewObjectID']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='ss',out_signature='i',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def ImportResource(self,SourceURI,DestinationURI,
dbus_async_cb,dbus_async_err_cb):
arguments = {'SourceURI':unicode(SourceURI),
'DestinationURI':unicode(DestinationURI)}
r = self.callAction('ImportResource',arguments)
if r == '':
return r
def convert_reply(data):
dbus_async_cb(unicode(data['TransferID']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='ss',out_signature='i',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def ExportResource(self,SourceURI,DestinationURI,
dbus_async_cb,dbus_async_err_cb):
arguments = {'SourceURI':unicode(SourceURI),
'DestinationURI':unicode(DestinationURI)}
r = self.callAction('ExportResource',arguments)
if r == '':
return r
def convert_reply(data):
dbus_async_cb(unicode(data['TransferID']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='s',out_signature='',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def DeleteResource(self,ResourceURI,
dbus_async_cb,dbus_async_err_cb):
arguments = {'ResourceURI':unicode(ResourceURI)}
r = self.callAction('DeleteResource',arguments)
if r == '':
return r
def convert_reply(data):
dbus_async_cb()
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='i',out_signature='',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def StopTransferResource(self,TransferID,
dbus_async_cb,dbus_async_err_cb):
arguments = {'TransferID':unicode(TransferID)}
r = self.callAction('StopTransferResource',arguments)
if r == '':
return r
def convert_reply(data):
dbus_async_cb()
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='i',out_signature='sss',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def GetTransferProgress(self,TransferID,
dbus_async_cb,dbus_async_err_cb):
arguments = {'TransferID':unicode(TransferID)}
r = self.callAction('GetTransferProgress',arguments)
if r == '':
return r
def convert_reply(data):
dbus_async_cb(unicode(data['TransferStatus']),unicode(data['TransferLength']),unicode(data['TransferTotal']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
@dbus.service.method(CDS_SERVICE,in_signature='ss',out_signature='s',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def CreateReference(self,ContainerID,ObjectID,
dbus_async_cb,dbus_async_err_cb):
arguments = {'ContainerID':unicode(ContainerID),
'ObjectID':unicode(ObjectID)}
r = self.callAction('CreateReference',arguments)
if r == '':
return r
def convert_reply(data):
dbus_async_cb(unicode(data['NewID']))
r.addCallback(convert_reply)
r.addErrback(dbus_async_err_cb)
def callAction(self,name,arguments):
action = self.service.get_action(name)
if action != None:
d = action.call(**arguments)
return d
return ''
class DBusService(dbus.service.Object,log.Loggable):
logCategory = 'dbus'
SUPPORTS_MULTIPLE_CONNECTIONS = True
def __init__(self, service, dbus_device, bus):
self.service = service
self.dbus_device = dbus_device
if self.service is not None:
self.type = self.service.service_type.split(':')[3] # get the service name
self.type = self.type.replace('-','')
else:
self.type = "from_the_tubes"
try:
bus_name = dbus.service.BusName(SERVICE_IFACE, bus)
except:
bus_name = None
self.tube = bus
else:
self.tube = None
if self.dbus_device is not None:
self.device_id = self.dbus_device.id
else:
self.device_id = "dev_from_the_tubes"
self.path = OBJECT_PATH + '/devices/' + self.device_id + '/services/' + self.type
dbus.service.Object.__init__(self, bus, bus_name=bus_name,
object_path=self.path)
self.debug("DBusService %r %r", service, self.type)
louie.connect(self.variable_changed, 'Coherence.UPnP.StateVariable.changed', sender=self.service)
self.subscribe()
#interfaces = self._dbus_class_table[self.__class__.__module__ + '.' + self.__class__.__name__]
#for (name, funcs) in interfaces.iteritems():
# print name, funcs
# if funcs.has_key('destroy_object'):
# print """removing 'destroy_object'"""
# del funcs['destroy_object']
# for func in funcs.values():
# if getattr(func, '_dbus_is_method', False):
# print self.__class__._reflect_on_method(func)
#self._get_service_methods()
def shutdown(self):
self._release_thyself(suicide_mode=False)
def _release_thyself(self, suicide_mode=True):
louie.disconnect(self.variable_changed, 'Coherence.UPnP.StateVariable.changed', sender=self.service)
self.service = None
self.dbus_device = None
self.tube = None
self.remove_from_connection()
self.path = None
if suicide_mode:
del self
def _get_service_methods(self):
'''Returns a list of method descriptors for this object'''
methods = []
for func in dir(self):
func = getattr(self,func)
if callable(func) and hasattr(func, '_dbus_is_method'):
print func, func._dbus_interface, func._dbus_is_method
if hasattr(func, 'im_func'):
print func.im_func
def variable_changed(self,variable):
#print self.service, "got signal for change of", variable
#print variable.name, variable.value
#print type(variable.name), type(variable.value)
self.StateVariableChanged(self.device_id,self.type,variable.name, variable.value)
@dbus.service.signal(SERVICE_IFACE,
signature='sssv')
def StateVariableChanged(self, udn, service, variable, value):
self.info("%s service %s signals StateVariable %s changed to %r",
self.device_id, self.type, variable, value)
@dbus.service.method(SERVICE_IFACE,in_signature='',out_signature='s')
def get_scpd_xml(self):
return self.service.get_scpdXML()
@dbus.service.method(SERVICE_IFACE,in_signature='',out_signature='as')
def get_available_actions(self):
actions = self.service.get_actions()
r = []
for name in actions.keys():
r.append(name)
return r
@dbus.service.method(SERVICE_IFACE,in_signature='',out_signature='s')
def get_id(self):
return self.service.id
@dbus.service.method(SERVICE_IFACE,in_signature='sv',out_signature='v',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def action(self,name,arguments,dbus_async_cb,dbus_async_err_cb):
#print "action", name, arguments
def reply(data):
dbus_async_cb(dbus.Dictionary(data,signature='sv',variant_level=4))
if self.service.client is not None:
#print "action", name
func = getattr(self.service.client,name,None)
#print "action", func
if callable(func):
kwargs = {}
try:
for k,v in arguments.items():
kwargs[str(k)] = unicode(v)
except:
pass
d = func(**kwargs)
d.addCallback(reply)
d.addErrback(dbus_async_err_cb)
return ''
@dbus.service.method(SERVICE_IFACE,in_signature='sa{ss}',out_signature='v',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb',),
sender_keyword='sender',connection_keyword='connection')
def call_action(self,name,arguments,dbus_async_cb,dbus_async_err_cb,sender=None,connection=None):
print "call_action called by ", sender, connection, self.type, self.tube
def reply(data,name,connection):
if hasattr(connection,'_tube') == True:
if name == 'Browse':
didl = DIDLLite.DIDLElement.fromString(data['Result'])
changed = False
for item in didl.getItems():
new_res = DIDLLite.Resources()
for res in item.res:
remote_protocol,remote_network,remote_content_format,_ = res.protocolInfo.split(':')
if remote_protocol == 'http-get' and remote_network == '*':
quoted_url = 'mirabeau' + '/' + urllib.quote_plus(res.data)
print "modifying", res.data
host_port = ':'.join((self.service.device.client.coherence.mirabeau._external_address,
str(self.service.device.client.coherence.mirabeau._external_port)))
res.data = urlparse.urlunsplit(('http', host_port,quoted_url,"",""))
print "--->", res.data
new_res.append(res)
changed = True
item.res = new_res
if changed == True:
didl.rebuild()
### FIXME this is not the proper way to do it
data['Result'] = didl.toString().replace('<ns0:','<').replace('</ns0:','</')
dbus_async_cb(dbus.Dictionary(data,signature='sv',variant_level=4))
if self.service.client is not None:
action = self.service.get_action(name)
if action:
kwargs = {}
try:
for k,v in arguments.items():
kwargs[str(k)] = unicode(v)
except:
pass
d = action.call(**kwargs)
d.addCallback(reply,name,connection)
d.addErrback(dbus_async_err_cb)
return ''
@dbus.service.method(SERVICE_IFACE,in_signature='v',out_signature='v',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def destroy_object(self,arguments,dbus_async_cb,dbus_async_err_cb):
def reply(data):
dbus_async_cb(dbus.Dictionary(data,signature='sv',variant_level=4))
if self.service.client is not None:
kwargs = {}
for k,v in arguments.items():
kwargs[str(k)] = str(v)
d = self.service.client.destroy_object(**kwargs)
d.addCallback(reply)
d.addErrback(dbus_async_err_cb)
return ''
@dbus.service.method(SERVICE_IFACE,in_signature='',out_signature='ssv')
def subscribe(self):
notify = []
if self.service:
notify = [v for v in self.service._variables[0].values() if v.send_events == True]
if len(notify) == 0:
return
data = {}
for n in notify:
if n.name == 'LastChange':
lc = {}
for instance, vdict in self.service._variables.items():
v = {}
for variable in vdict.values():
if( variable.name != 'LastChange' and
variable.name[0:11] != 'A_ARG_TYPE_' and
variable.never_evented == False):
if hasattr(variable, 'dbus_updated') == False:
variable.dbus_updated = None
#if variable.dbus_updated != variable.last_touched:
# v[unicode(variable.name)] = unicode(variable.value)
# variable.dbus_updated = time.time()
# #FIXME: we are missing variable dependencies here
if len(v) > 0:
lc[str(instance)] = v
if len(lc) > 0:
data[unicode(n.name)] = lc
else:
data[unicode(n.name)] = unicode(n.value)
return self.dbus_device.device.get_id(), self.type, dbus.Dictionary(data,signature='sv',variant_level=3)
class DBusDevice(dbus.service.Object,log.Loggable):
logCategory = 'dbus'
SUPPORTS_MULTIPLE_CONNECTIONS = True
def __init__(self,device, bus):
if device is not None:
self.uuid = device.get_id()[5:]
self.id = self.uuid.replace('-','')
# we shouldn't need to do this, but ...
self.id = self.id.replace('+','')
else:
self.id = "from_the_tubes"
try:
bus_name = dbus.service.BusName(DEVICE_IFACE, bus)
except:
bus_name = None
self.tube = bus
else:
self.tube = None
dbus.service.Object.__init__(self, bus, bus_name=bus_name,
object_path=self.path())
self.services = []
self.device = device
self.debug("DBusDevice %r %r", device, self.id)
if device is not None:
for service in device.get_services():
self.services.append(DBusService(service,self,bus))
if service.service_type.split(':')[3] == 'ContentDirectory':
self.services.append(DBusCDSService(service,self,bus))
def shutdown(self):
self._release_thyself(suicide_mode=False)
def _release_thyself(self, suicide_mode=True):
for service in self.services:
service._release_thyself()
self.services = None
self.device = None
self.tube = None
self.remove_from_connection()
# FIXME: this is insane
if suicide_mode:
del self
def path(self):
return OBJECT_PATH + '/devices/' + self.id
@dbus.service.method(DEVICE_IFACE,in_signature='',out_signature='v')
def get_info(self):
services = [x.path for x in self.services
if getattr(x, "NOT_FOR_THE_TUBES", False) == False]
r = {'path': self.path(),
'device_type': self.device.get_device_type(),
'friendly_name': self.device.get_friendly_name(),
'udn': self.device.get_id(),
'uri': list(urlparse.urlsplit(self.device.get_location())),
'presentation_url': self.device.get_presentation_url(),
'parent_udn': self.device.get_parent_id(),
'services': services}
return dbus.Dictionary(r,signature='sv',variant_level=2)
@dbus.service.method(DEVICE_IFACE,in_signature='',out_signature='s')
def get_markup_name(self):
return self.device.get_markup_name()
@dbus.service.method(DEVICE_IFACE,in_signature='',out_signature='s')
def get_friendly_name(self):
return self.device.get_friendly_name()
@dbus.service.method(DEVICE_IFACE,in_signature='',out_signature='s')
def get_friendly_device_type(self):
return self.device.get_friendly_device_type()
@dbus.service.method(DEVICE_IFACE,in_signature='',out_signature='i')
def get_device_type_version(self):
return int(self.device.get_device_type_version())
@dbus.service.method(DEVICE_IFACE,in_signature='',out_signature='s')
def get_id(self):
return self.device.get_id()
@dbus.service.method(DEVICE_IFACE,in_signature='',out_signature='s')
def get_device_type(self):
return self.device.get_device_type()
@dbus.service.method(DEVICE_IFACE,in_signature='',out_signature='s')
def get_usn(self):
return self.device.get_usn()
@dbus.service.method(DEVICE_IFACE,in_signature='',out_signature='av')
def get_device_icons(self):
return dbus.Array(self.device.icons,signature='av',variant_level=2)
class DBusPontoon(dbus.service.Object,log.Loggable):
logCategory = 'dbus'
SUPPORTS_MULTIPLE_CONNECTIONS = True
def __init__(self,controlpoint, bus=None):
self.bus = bus or dbus.SessionBus()
try:
bus_name = dbus.service.BusName(BUS_NAME, self.bus)
except:
bus_name = None
self.tube = self.bus
else:
self.tube = None
self.bus_name = bus_name
dbus.service.Object.__init__(self, self.bus, bus_name=self.bus_name,
object_path=OBJECT_PATH)
self.debug("D-Bus pontoon %r %r %r" % (self, self.bus, self.bus_name))
self.devices = {}
self.controlpoint = controlpoint
self.pinboard = {}
# i am a stub service if i have no control point
if self.controlpoint is None:
return
for device in self.controlpoint.get_devices():
self.devices[device.get_id()] = DBusDevice(device,self.bus_name)
#louie.connect(self.cp_ms_detected, 'Coherence.UPnP.ControlPoint.MediaServer.detected', louie.Any)
#louie.connect(self.cp_ms_removed, 'Coherence.UPnP.ControlPoint.MediaServer.removed', louie.Any)
#louie.connect(self.cp_mr_detected, 'Coherence.UPnP.ControlPoint.MediaRenderer.detected', louie.Any)
#louie.connect(self.cp_mr_removed, 'Coherence.UPnP.ControlPoint.MediaRenderer.removed', louie.Any)
#louie.connect(self.remove_client, 'Coherence.UPnP.Device.remove_client', louie.Any)
louie.connect(self._device_detected, 'Coherence.UPnP.Device.detection_completed', louie.Any)
louie.connect(self._device_removed, 'Coherence.UPnP.Device.removed', louie.Any)
self.debug("D-Bus pontoon started")
def shutdown(self):
louie.disconnect(self._device_detected, 'Coherence.UPnP.Device.detection_completed', louie.Any)
louie.disconnect(self._device_removed, 'Coherence.UPnP.Device.removed', louie.Any)
for device_id, device in self.devices.iteritems():
device.shutdown()
self.devices = {}
self.remove_from_connection()
self.bus = None
@dbus.service.method(BUS_NAME,in_signature='sv',out_signature='')
def pin(self,key,value):
self.pinboard[key] = value
print self.pinboard
@dbus.service.method(BUS_NAME,in_signature='s',out_signature='v')
def get_pin(self,key):
return self.pinboard.get(key,'Coherence::Pin::None')
@dbus.service.method(BUS_NAME,in_signature='s',out_signature='')
def unpin(self,key):
del self.pinboard[key]
@dbus.service.method(BUS_NAME,in_signature='s',out_signature='s')
def create_oob(self,file):
print 'create_oob'
key = str(time.time())
self.pinboard[key] = file
print self.pinboard
return self.controlpoint.coherence.urlbase + 'oob?key=' + key
def remove_client(self, usn, client):
self.info("removed %s %s" % (client.device_type,client.device.get_friendly_name()))
try:
getattr(self,str('UPnP_ControlPoint_%s_removed' % client.device_type))(usn)
except:
pass
def remove(self,udn):
#print "DBusPontoon remove", udn
#print "before remove", self.devices
d = self.devices.pop(udn)
d._release_thyself()
del d
#print "after remove", self.devices
@dbus.service.method(BUS_NAME,in_signature='',out_signature='s')
def version(self):
return __version__
@dbus.service.method(BUS_NAME,in_signature='',out_signature='s')
def hostname(self):
return self.controlpoint.coherence.hostname
@dbus.service.method(BUS_NAME,in_signature='',out_signature='av')
def get_devices(self):
r = []
for device in self.devices.values():
#r.append(device.path())
r.append(device.get_info())
return dbus.Array(r,signature='v',variant_level=2)
@dbus.service.method(BUS_NAME,in_signature='i',out_signature='av',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def get_devices_async(self, for_mirabeau, dbus_async_cb,dbus_async_err_cb):
infos = []
allowed_device_types = ['urn:schemas-upnp-org:device:MediaServer:2',
'urn:schemas-upnp-org:device:MediaServer:1']
def iterate_devices(devices):
for device in devices:
if for_mirabeau and device.get_device_type() not in allowed_device_types:
continue
infos.append(device.get_info())
yield infos
def done(generator):
dbus_async_cb(dbus.Array(infos, signature='v', variant_level=2))
devices = self.devices.copy().values()
dfr = task.coiterate(iterate_devices(devices))
dfr.addCallbacks(done, lambda failure: dbus_async_err_cb(failure.value))
@dbus.service.method(BUS_NAME,in_signature='s',out_signature='v')
def get_device_with_id(self,id):
for device in self.devices.values():
if id == device.device.get_id():
return device.get_info()
@dbus.service.method(BUS_NAME,in_signature='sa{ss}',out_signature='s')
def add_plugin(self,backend,arguments):
kwargs = {}
for k,v in arguments.iteritems():
kwargs[str(k)] = str(v)
p = self.controlpoint.coherence.add_plugin(backend,**kwargs)
return str(p.uuid)
@dbus.service.method(BUS_NAME,in_signature='s',out_signature='s')
def remove_plugin(self,uuid):
return str(self.controlpoint.coherence.remove_plugin(uuid))
@dbus.service.method(BUS_NAME,in_signature='ssa{ss}',out_signature='s')
def call_plugin(self,uuid,method,arguments):
try:
plugin = self.controlpoint.coherence.active_backends[uuid]
except KeyError:
self.warning("no backend with the uuid %r found" % uuid)
return ""
function = getattr(plugin.backend, method, None)
if function == None:
return ""
kwargs = {}
for k,v in arguments.iteritems():
kwargs[str(k)] = unicode(v)
function(**kwargs)
return uuid
@dbus.service.method(BUS_NAME,in_signature='ssa{ss}',out_signature='v',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def create_object(self,device_id,container_id,arguments,dbus_async_cb,dbus_async_err_cb):
device = self.controlpoint.get_device_with_id(device_id)
if device != None:
client = device.get_client()
new_arguments = {}
for k,v in arguments.items():
new_arguments[str(k)] = unicode(v)
def reply(data):
dbus_async_cb(dbus.Dictionary(data,signature='sv',variant_level=4))
d = client.content_directory.create_object(str(container_id), new_arguments)
d.addCallback(reply)
d.addErrback(dbus_async_err_cb)
@dbus.service.method(BUS_NAME,in_signature='sss',out_signature='v',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def import_resource(self,device_id,source_uri, destination_uri,dbus_async_cb,dbus_async_err_cb):
device = self.controlpoint.get_device_with_id(device_id)
if device != None:
client = device.get_client()
def reply(data):
dbus_async_cb(dbus.Dictionary(data,signature='sv',variant_level=4))
d = client.content_directory.import_resource(str(source_uri), str(destination_uri))
d.addCallback(reply)
d.addErrback(dbus_async_err_cb)
@dbus.service.method(BUS_NAME,in_signature='ss',out_signature='v',
async_callbacks=('dbus_async_cb', 'dbus_async_err_cb'))
def put_resource(self,destination_uri,filepath,dbus_async_cb,dbus_async_err_cb):
def reply(data):
dbus_async_cb(200)
d = self.controlpoint.put_resource(str(destination_uri),unicode(filepath))
d.addCallback(reply)
d.addErrback(dbus_async_err_cb)
def _device_detected(self,device):
id = device.get_id()
#print "new_device_detected",device.get_usn(),device.friendly_device_type,id
if id not in self.devices:
new_device = DBusDevice(device,self.bus)
self.devices[id] = new_device
#print self.devices, id
info = new_device.get_info()
self.device_detected(info,id)
if device.get_friendly_device_type() == 'MediaServer':
self.UPnP_ControlPoint_MediaServer_detected(info,id)
elif device.get_friendly_device_type() == 'MediaRenderer':
self.UPnP_ControlPoint_MediaRenderer_detected(info,id)
def _device_removed(self,usn=''):
#print "_device_removed", usn
id = usn.split('::')[0]
device = self.devices[id]
self.device_removed(id)
#print device.get_friendly_device_type()
if device.get_friendly_device_type() == 'MediaServer':
self.UPnP_ControlPoint_MediaServer_removed(id)
if device.get_friendly_device_type() == 'MediaRenderer':
self.UPnP_ControlPoint_MediaServer_removed(id)
reactor.callLater(1, self.remove, id)
def cp_ms_detected(self,client,udn=''):
#print "cp_ms_detected", udn
if client.device.get_id() not in self.devices:
new_device = DBusDevice(client.device,self.bus)
self.devices[client.device.get_id()] = new_device
self.UPnP_ControlPoint_MediaServer_detected(new_device.get_info(),udn)
def cp_mr_detected(self,client,udn=''):
if client.device.get_id() not in self.devices:
new_device = DBusDevice(client.device,self.bus)
self.devices[client.device.get_id()] = new_device
self.UPnP_ControlPoint_MediaRenderer_detected(new_device.get_info(),udn)
def cp_ms_removed(self,udn):
#print "cp_ms_removed", udn
self.UPnP_ControlPoint_MediaServer_removed(udn)
# schedule removal of device from our cache after signal has
# been called. Let's assume one second is long enough...
reactor.callLater(1, self.remove, udn)
def cp_mr_removed(self,udn):
#print "cp_mr_removed", udn
self.UPnP_ControlPoint_MediaRenderer_removed(udn)
# schedule removal of device from our cache after signal has
# been called. Let's assume one second is long enough...
reactor.callLater(1, self.remove, udn)
@dbus.service.signal(BUS_NAME,
signature='vs')
def UPnP_ControlPoint_MediaServer_detected(self,device,udn):
self.info("emitting signal UPnP_ControlPoint_MediaServer_detected")
@dbus.service.signal(BUS_NAME,
signature='s')
def UPnP_ControlPoint_MediaServer_removed(self,udn):
self.info("emitting signal UPnP_ControlPoint_MediaServer_removed")
@dbus.service.signal(BUS_NAME,
signature='vs')
def UPnP_ControlPoint_MediaRenderer_detected(self,device,udn):
self.info("emitting signal UPnP_ControlPoint_MediaRenderer_detected")
@dbus.service.signal(BUS_NAME,
signature='s')
def UPnP_ControlPoint_MediaRenderer_removed(self,udn):
self.info("emitting signal UPnP_ControlPoint_MediaRenderer_removed")
@dbus.service.signal(BUS_NAME,
signature='vs')
def device_detected(self,device,udn):
self.info("emitting signal device_detected")
@dbus.service.signal(BUS_NAME,
signature='s')
def device_removed(self,udn):
self.info("emitting signal device_removed")
""" org.DLNA related methods and signals
"""
@dbus.service.method(DLNA_BUS_NAME+'.DMC',in_signature='',out_signature='av')
def getDMSList(self):
return dbus.Array(self._get_devices_of_type('MediaServer'),
signature='v', variant_level=2)
def _get_devices_of_type(self, typ):
return [ device.get_info() for device in self.devices.itervalues()
if device.get_friendly_device_type() == typ ]
@dbus.service.method(DLNA_BUS_NAME + '.DMC', in_signature='',
out_signature='av')
def getDMRList(self):
return dbus.Array(self._get_devices_of_type('MediaRenderer'),
signature='v', variant_level=2)
@dbus.service.signal(BUS_NAME,
signature='vs')
def DMS_added(self,device,udn):
self.info("emitting signal DMS_added")
@dbus.service.signal(BUS_NAME,
signature='s')
def DMS_removed(self,udn):
self.info("emitting signal DMS_removed")
@dbus.service.signal(BUS_NAME,
signature='vs')
def DMR_added(self,device,udn):
self.info("emitting signal DMR_added")
@dbus.service.signal(BUS_NAME,
signature='s')
def DMR_removed(self,udn):
self.info("emitting signal DMR_detected")
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~swr3_storage.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008,2009 Frank Scholz <[email protected]>
from datetime import datetime
from email.Utils import parsedate_tz
from coherence.backend import BackendStore,BackendRssMixin
from coherence.backend import BackendItem
from coherence.upnp.core import DIDLLite
from twisted.python.util import OrderedDict
from coherence.upnp.core.utils import getPage
from coherence.extern.et import parse_xml
ROOT_CONTAINER_ID = 0
class Item(BackendItem):
def __init__(self, parent, id, title, url):
self.parent = parent
self.id = id
self.location = url
self.name = title
self.duration = None
self.size = None
self.mimetype = 'audio/mpeg'
self.description = None
self.date = None
self.item = None
def get_item(self):
if self.item == None:
self.item = DIDLLite.AudioItem(self.id, self.parent.id, self.name)
self.item.description = self.description
self.item.date = self.date
if hasattr(self.parent, 'cover'):
self.item.albumArtURI = self.parent.cover
res = DIDLLite.Resource(self.location, 'http-get:*:%s:*' % self.mimetype)
res.duration = self.duration
res.size = self.size
self.item.res.append(res)
return self.item
class Container(BackendItem):
def __init__(self, id, store, parent_id, title):
self.url = store.urlbase+str(id)
self.parent_id = parent_id
self.id = id
self.name = title
self.mimetype = 'directory'
self.update_id = 0
self.children = []
self.item = DIDLLite.Container(self.id, self.parent_id, self.name)
self.item.childCount = 0
self.sorted = False
def add_child(self, child):
id = child.id
if isinstance(child.id, basestring):
_,id = child.id.split('.')
self.children.append(child)
self.item.childCount += 1
self.sorted = False
def get_children(self, start=0, end=0):
if self.sorted == False:
def childs_sort(x,y):
r = cmp(x.name,y.name)
return r
self.children.sort(cmp=childs_sort)
self.sorted = True
if end != 0:
return self.children[start:end]
return self.children[start:]
def get_child_count(self):
return len(self.children)
def get_path(self):
return self.url
def get_item(self):
return self.item
def get_name(self):
return self.name
def get_id(self):
return self.id
class SWR3Store(BackendStore,BackendRssMixin):
implements = ['MediaServer']
def __init__(self, server, *args, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.name = kwargs.get('name', 'SWR3')
self.opml = kwargs.get('opml', 'http://www.swr3.de/rdf-feed/podcast/')
self.encoding = kwargs.get('encoding', "ISO-8859-1")
self.refresh = int(kwargs.get('refresh', 1)) * (60 *60)
self.next_id = 1000
self.update_id = 0
self.last_updated = None
self.store = {}
self.store[ROOT_CONTAINER_ID] = \
Container(ROOT_CONTAINER_ID,self,-1, self.name)
self.parse_opml()
self.init_completed()
def parse_opml(self):
def fail(f):
self.info("fail %r", f)
return f
def create_containers(data):
feeds = []
for feed in data.findall('body/outline'):
#print feed.attrib['type'],feed.attrib['url']
if(feed.attrib['type'] == 'link' and
feed.attrib['url'] not in feeds):
feeds.append(feed.attrib['url'])
self.update_data(feed.attrib['url'],self.get_next_id(),encoding=self.encoding)
dfr = getPage(self.opml)
dfr.addCallback(parse_xml,encoding=self.encoding)
dfr.addErrback(fail)
dfr.addCallback(create_containers)
dfr.addErrback(fail)
def get_next_id(self):
self.next_id += 1
return self.next_id
def get_by_id(self,id):
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
try:
return self.store[int(id)]
except (ValueError,KeyError):
pass
return None
def upnp_init(self):
if self.server:
self.server.connection_manager_server.set_variable( \
0, 'SourceProtocolInfo', ['http-get:*:audio/mpeg:*'])
def parse_data(self,xml_data,container):
root = xml_data.getroot()
title = root.find("./channel/title").text
title = title.encode(self.encoding).decode('utf-8')
self.store[container] = \
Container(container,self,ROOT_CONTAINER_ID, title)
description = root.find("./channel/description").text
description = description.encode(self.encoding).decode('utf-8')
self.store[container].description = description
self.store[container].cover = root.find("./channel/image/url").text
self.store[ROOT_CONTAINER_ID].add_child(self.store[container])
for podcast in root.findall("./channel/item"):
enclosure = podcast.find("./enclosure")
title = podcast.find("./title").text
title = title.encode(self.encoding).decode('utf-8')
item = Item(self.store[container], self.get_next_id(), title, enclosure.attrib['url'])
item.size = int(enclosure.attrib['length'])
item.mimetype = enclosure.attrib['type']
self.store[container].add_child(item)
description = podcast.find("./description")
if description != None:
description = description.text
item.description = description.encode(self.encoding).decode('utf-8')
#item.date = datetime(*parsedate_tz(podcast.find("./pubDate").text)[0:6])
#item.date = podcast.find("./pubDate")
self.update_id += 1
#if self.server:
# self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
# value = (ROOT_CONTAINER_ID,self.container.update_id)
# self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~services~servers~media_receiver_registrar_server.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006, Frank Scholz <[email protected]>
# Content Directory service
from twisted.web import resource
from coherence.upnp.core.soap_service import UPnPPublisher
from coherence.upnp.core import service
class FakeMediaReceiverRegistrarBackend:
def upnp_IsAuthorized(self, *args, **kwargs):
r = { 'Result': 1}
return r
def upnp_IsValidated(self, *args, **kwargs):
r = { 'Result': 1}
return r
def upnp_RegisterDevice(self, *args, **kwargs):
""" in parameter RegistrationReqMsg """
RegistrationReqMsg = kwargs['RegistrationReqMsg']
""" FIXME: check with WMC and WMP """
r = { 'RegistrationRespMsg': 'WTF should be in here?'}
return r
class MediaReceiverRegistrarControl(service.ServiceControl,UPnPPublisher):
def __init__(self, server):
self.service = server
self.variables = server.get_variables()
self.actions = server.get_actions()
class MediaReceiverRegistrarServer(service.ServiceServer, resource.Resource):
implementation = 'optional'
def __init__(self, device, backend=None):
self.device = device
if backend == None:
backend = self.device.backend
resource.Resource.__init__(self)
self.version = 1
self.namespace = 'microsoft.com'
self.id_namespace = 'microsoft.com'
service.ServiceServer.__init__(self, 'X_MS_MediaReceiverRegistrar', self.version, backend)
self.device_description_tmpl = 'xbox-description-1.xml'
self.control = MediaReceiverRegistrarControl(self)
self.putChild('scpd.xml', service.scpdXML(self, self.control))
self.putChild('control', self.control)
def listchilds(self, uri):
cl = ''
for c in self.children:
cl += '<li><a href=%s/%s>%s</a></li>' % (uri,c,c)
return cl
def render(self,request):
return '<html><p>root of the MediaReceiverRegistrar</p><p><ul>%s</ul></p></html>'% self.listchilds(request.uri)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~json.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
import simplejson as json
from twisted.web import resource,static
from twisted.internet import defer
from coherence import log
class JsonInterface(resource.Resource,log.Loggable):
logCategory = 'json'
#isLeaf = False
def __init__(self, controlpoint):
self.controlpoint = controlpoint
self.controlpoint.coherence.add_web_resource('json',
self)
self.children = {}
def render_GET(self,request):
d = defer.maybeDeferred(self.do_the_render,request)
return d
def render_POST(self,request):
d = defer.maybeDeferred(self.do_the_render,request)
return d
def getChildWithDefault(self,path,request):
self.info('getChildWithDefault, %s, %s, %s %s %r' % (request.method, path, request.uri, request.client,request.args))
#return self.do_the_render(request)
d = defer.maybeDeferred(self.do_the_render,request)
return d
def do_the_render(self,request):
self.warning('do_the_render, %s, %s, %s %r %s' % (request.method, request.path,request.uri, request.args, request.client))
msg = "Houston, we've got a problem"
path = request.path.split('/')
path = path[2:]
self.warning('path %r' % path)
if request.method in ('GET','POST'):
request.postpath = None
if request.method == 'GET':
if path[0] == 'devices':
return self.list_devices(request)
else:
device = self.controlpoint.get_device_with_id(path[0])
if device != None:
service = device.get_service_by_type(path[1])
if service != None:
action = service.get_action(path[2])
if action != None:
return self.call_action(action,request)
else:
msg = "action %r on service type %r for device %r not found" % (path[2],path[1],path[0])
else:
msg = "service type %r for device %r not found" % (path[1],path[0])
else:
msg = "device with id %r not found" % path[0]
request.setResponseCode(404,message=msg)
return static.Data("<html><p>%s</p></html>" % msg,'text/html')
def list_devices(self,request):
devices = []
for device in self.controlpoint.get_devices():
devices.append(device.as_dict())
return static.Data(json.dumps(devices),'application/json')
def call_action(self,action,request):
kwargs = {}
for entry,value_list in request.args.items():
kwargs[entry] = unicode(value_list[0])
def to_json(result):
self.warning("to_json")
return static.Data(json.dumps(result),'application/json')
def fail(f):
request.setResponseCode(404)
return static.Data("<html><p>Houston, we've got a problem</p></html>",'text/html')
d = action.call(**kwargs)
d.addCallback(to_json)
d.addErrback(fail)
return d | [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~services~servers~scheduled_recording_server.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2009, Frank Scholz <[email protected]>
# ScheduledRecording service
from twisted.web import resource
from coherence.upnp.core.soap_service import UPnPPublisher
from coherence.upnp.core import service
class ScheduledRecordingControl(service.ServiceControl,UPnPPublisher):
def __init__(self, server):
self.service = server
self.variables = server.get_variables()
self.actions = server.get_actions()
class ScheduledRecordingServer(service.ServiceServer, resource.Resource):
implementation = 'optional'
def __init__(self, device, backend=None):
self.device = device
if backend == None:
backend = self.device.backend
resource.Resource.__init__(self)
self.version = 1
service.ServiceServer.__init__(self, 'ScheduledRecording', self.version, backend)
self.control = ScheduledRecordingControl(self)
self.putChild(self.scpd_url, service.scpdXML(self, self.control))
self.putChild(self.control_url, self.control)
def listchilds(self, uri):
cl = ''
for c in self.children:
cl += '<li><a href=%s/%s>%s</a></li>' % (uri,c,c)
return cl
def render(self,request):
return '<html><p>root of the ScheduledRecording</p><p><ul>%s</ul></p></html>'% self.listchilds(request.uri)
| [] |
2024-01-10 | opendreambox/python-coherence | setup.py | # -*- coding: utf-8 -*-
import sys
import os
try:
from coherence import __version__
except ImportError:
raise SystemExit(1)
try:
import setuptools
from setuptools import setup, find_packages
packages = find_packages()
setuptools = True
except:
setuptools = None
from distutils.core import setup
packages = ['coherence',]
def find_packages(path):
for f in os.listdir(path):
if f[0] == '.':
continue
if os.path.isdir(os.path.join(path,f)) == True:
next_path = os.path.join(path,f)
if '__init__.py' in os.listdir(next_path):
packages.append(next_path.replace(os.sep,'.'))
find_packages(next_path)
find_packages('coherence')
from distutils.core import Command
from distutils import log
class build_docs(Command):
description = "build documentation from rst-files"
user_options=[]
def initialize_options (self): pass
def finalize_options (self):
self.docpages = DOCPAGES
def run(self):
substitutions = ('.. |VERSION| replace:: '
+ self.distribution.get_version())
for writer, rstfilename, outfilename in self.docpages:
distutils.dir_util.mkpath(os.path.dirname(outfilename))
log.info("creating %s page %s", writer, outfilename)
if not self.dry_run:
try:
rsttext = open(rstfilename).read()
except IOError, e:
raise SystemExit(e)
rsttext = '\n'.join((substitutions, rsttext))
# docutils.core does not offer easy reading from a
# string into a file, so we need to do it ourself :-(
doc = docutils.core.publish_string(source=rsttext,
source_path=rstfilename,
writer_name=writer)
try:
rsttext = open(outfilename, 'w').write(doc)
except IOError, e:
raise SystemExit(e)
cmdclass = {}
try:
import docutils.core
import docutils.io
import docutils.writers.manpage
import distutils.command.build
distutils.command.build.build.sub_commands.append(('build_docs', None))
cmdclass['build_docs'] = build_docs
except ImportError:
log.warn("docutils not installed, can not build man pages. "
"Using pre-build ones.")
DOCPAGES = (
('manpage', 'docs/man/coherence.rst', 'docs/man/coherence.1'),
)
setup_args = {
'name':"Coherence",
'version':__version__,
'description':"""Coherence - DLNA/UPnP framework for the digital living""",
'long_description':"""
Coherence is a framework written in Python, providing a variety of
UPnP MediaServer and UPnP MediaRenderer implementations for instant
use.
It includes an UPnP ControlPoint, which is accessible via D-Bus too.
Furthermore it enables your application to participate in
digital living networks, at the moment primarily the DLNA/UPnP universe.
Its objective and demand is to relieve your application from all the
membership/the UPnP related tasks as much as possible.
New in this %s - the Red-Nosed Reindeer - release
* new MediaServer backends that allow access to
* Banshee - exports audio and video files from Banshees media db
(http://banshee-project.org/)
* FeedStore - a MediaServer serving generic RSS feeds
* Playlist - exposes the list of video/audio streams from a m3u
playlist (e.g. web TV listings published by french ISPs such as
Free, SFR...)
* YAMJ - serves the movie/TV series data files and metadata from a
given YAMJ (Yet Another Movie Jukebox) library
(http://code.google.com/p/moviejukebox/)
* updates on Mirabeau - our "UPnP over XMPP" bridge
* simplifications in the D-Bus API
* a first implementation of an JSON/REST API
* advancements of the GStreamer MediaRenderer, supporting now GStreamers
playbin2
* upgrade of the DVB-Daemon MediaServer
* refinements in the transcoding section, having now the choice to use
GStreamer pipelines or external processes like mencoder
* more 'compatibility' improvements for different devices (e.g.
Samsung TVs or Apache Felix)
* and - as every time - the usual bugfixes and enhancements
Kudos go to:
* Benjamin (lightyear) Kampmann,
* Charlie (porthose) Smotherman
* Dominik (schrei5) Ruf,
* Frank (dev) Scholz,
* Friedrich (frinring) Kossebau,
* Jean-Michel (jmsizun) Sizun,
* Philippe (philn) Normand,
* Sebastian (sebp) Poelsterl,
* Zaheer (zaheerm) Merali
""" % __version__,
'author':"Frank Scholz",
'author_email':'[email protected]',
'license' : "MIT",
'packages':packages,
'scripts' : ['bin/coherence','misc/Desktop-Applet/applet-coherence'],
'url' : "http://coherence-project.org",
'download_url' : 'http://coherence-project.org/download/Coherence-%s.tar.gz' % __version__,
'keywords':['UPnP', 'DLNA', 'multimedia', 'gstreamer'],
'classifiers' : ['Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Environment :: Web Environment',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
'package_data' : {
'coherence': ['upnp/core/xml-service-descriptions/*.xml',
'ui/icons/*.png',
'web/static/*.css','web/static/*.js'],
'misc': ['Desktop-Applet/*.png',
'device-icons/*.png'],
},
}
if setuptools:
setup_args['install_requires'] = [
'ConfigObj >= 4.3',
'zope.interface',
]
if sys.platform in ('win32','sunos5'):
setup_args['install_requires'].append('Netifaces >= 0.4')
setup_args['entry_points'] = """
[coherence.plugins.backend.media_server]
FSStore = coherence.backends.fs_storage:FSStore
MediaStore = coherence.backends.mediadb_storage:MediaStore
ElisaMediaStore = coherence.backends.elisa_storage:ElisaMediaStore
FlickrStore = coherence.backends.flickr_storage:FlickrStore
AxisCamStore = coherence.backends.axiscam_storage:AxisCamStore
BuzztardStore = coherence.backends.buzztard_control:BuzztardStore
IRadioStore = coherence.backends.iradio_storage:IRadioStore
LastFMStore = coherence.backends.lastfm_storage:LastFMStore
AmpacheStore = coherence.backends.ampache_storage:AmpacheStore
TrackerStore = coherence.backends.tracker_storage:TrackerStore
DVBDStore = coherence.backends.dvbd_storage:DVBDStore
AppleTrailersStore = coherence.backends.appletrailers_storage:AppleTrailersStore
LolcatsStore = coherence.backends.lolcats_storage:LolcatsStore
TEDStore = coherence.backends.ted_storage:TEDStore
BBCStore = coherence.backends.bbc_storage:BBCStore
SWR3Store = coherence.backends.swr3_storage:SWR3Store
Gallery2Store = coherence.backends.gallery2_storage:Gallery2Store
YouTubeStore = coherence.backends.youtube_storage:YouTubeStore
MiroGuideStore = coherence.backends.miroguide_storage:MiroGuideStore
ITVStore = coherence.backends.itv_storage:ITVStore
PicasaStore = coherence.backends.picasa_storage:PicasaStore
TestStore = coherence.backends.test_storage:TestStore
PlaylistStore = coherence.backends.playlist_storage:PlaylistStore
YamjStore = coherence.backends.yamj_storage:YamjStore
BansheeStore = coherence.backends.banshee_storage:BansheeStore
FeedStore = coherence.backends.feed_storage:FeedStore
RadiotimeStore = coherence.backends.radiotime_storage:RadiotimeStore
AudioCDStore = coherence.backends.audiocd_storage:AudioCDStore
[coherence.plugins.backend.media_renderer]
ElisaPlayer = coherence.backends.elisa_renderer:ElisaPlayer
GStreamerPlayer = coherence.backends.gstreamer_renderer:GStreamerPlayer
BuzztardPlayer = coherence.backends.buzztard_control:BuzztardPlayer
[coherence.plugins.backend.binary_light]
SimpleLight = coherence.backends.light:SimpleLight
[coherence.plugins.backend.dimmable_light]
BetterLight = coherence.backends.light:BetterLight
"""
setup(cmdclass=cmdclass, **setup_args)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~banshee_storage.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2009, Philippe Normand <[email protected]>
"""
TODO:
- podcasts
"""
from twisted.internet import reactor, defer, task
from coherence.extern import db_row
from coherence.upnp.core import DIDLLite
from coherence.backend import BackendItem, BackendStore
from coherence.log import Loggable
import coherence.extern.louie as louie
from sqlite3 import dbapi2
# fallback on pysqlite2.dbapi2
import re
import os
import time
from urlparse import urlsplit
import urllib2
import mimetypes
mimetypes.init()
mimetypes.add_type('audio/x-m4a', '.m4a')
mimetypes.add_type('video/mp4', '.mp4')
mimetypes.add_type('video/mpegts', '.ts')
mimetypes.add_type('video/divx', '.divx')
mimetypes.add_type('video/divx', '.avi')
mimetypes.add_type('video/x-matroska', '.mkv')
mimetypes.add_type('audio/x-musepack', '.mpc')
mimetypes.add_type('audio/x-wavpack', '.flac')
mimetypes.add_type('audio/x-wavpack', '.wv')
mimetypes.add_type('audio/mp4', '.m4a')
ROOT_CONTAINER_ID = 0
AUDIO_CONTAINER = 200
VIDEO_CONTAINER = 300
AUDIO_ALL_CONTAINER_ID = 201
AUDIO_ARTIST_CONTAINER_ID = 202
AUDIO_ALBUM_CONTAINER_ID = 203
AUDIO_PLAYLIST_CONTAINER_ID = 204
VIDEO_ALL_CONTAINER_ID = 301
VIDEO_PLAYLIST_CONTAINER_ID = 302
def get_cover_path(artist_name, album_title):
def _escape_part(part):
escaped = ""
if part:
if part.find("(") > -1:
part = part[:part.find("(")]
escaped = re.sub("[^A-Za-z0-9]*", "", part).lower()
return escaped
base_dir = os.path.expanduser("~/.cache/album-art")
return os.path.join(base_dir, "%s-%s.jpg" % (_escape_part(artist_name),
_escape_part(album_title)))
class SQLiteDB(Loggable):
"""
Python DB API 2.0 backend support.
"""
logCategory = "sqlite"
def __init__(self, database):
""" Connect to a db backend hosting the given database.
"""
Loggable.__init__(self)
self._params = {'database': database, 'check_same_thread': True}
self.connect()
def disconnect(self):
self._db.close()
def connect(self):
"""
Connect to the database, set L{_db} instance variable.
"""
self._db = dbapi2.connect(**self._params)
def reconnect(self):
"""
Disconnect and reconnect to the database.
"""
self.disconnect()
self.connect()
def sql_execute(self, request, *params, **kw):
""" Execute a SQL query in the db backend
"""
t0 = time.time()
debug_msg = request
if params:
debug_msg = u"%s params=%r" % (request, params)
debug_msg = u''.join(debug_msg.splitlines())
if debug_msg:
self.debug('QUERY: %s', debug_msg)
cursor = self._db.cursor()
result = []
cursor.execute(request, params)
if cursor.description:
all_rows = cursor.fetchall()
result = db_row.getdict(all_rows, cursor.description)
cursor.close()
delta = time.time() - t0
self.log("SQL request took %s seconds" % delta)
return result
class Container(BackendItem):
get_path = None
def __init__(self, id, parent_id, name, children_callback=None, store=None,
play_container=False):
self.id = id
self.parent_id = parent_id
self.name = name
self.mimetype = 'directory'
self.store = store
self.play_container = play_container
self.update_id = 0
if children_callback != None:
self.children = children_callback
else:
self.children = []
def add_child(self, child):
self.children.append(child)
def get_children(self,start=0,request_count=0):
def got_children(children):
if request_count == 0:
return children[start:]
else:
return children[start:request_count]
if callable(self.children):
dfr = defer.maybeDeferred(self.children)
else:
dfr = defer.succeed(self.children)
dfr.addCallback(got_children)
return dfr
def get_child_count(self):
count = 0
if callable(self.children):
count = defer.maybeDeferred(self.children)
count.addCallback(lambda children: len(children))
else:
count = len(self.children)
return count
def get_item(self):
item = DIDLLite.Container(self.id, self.parent_id,self.name)
def got_count(count):
item.childCount = count
if self.store and self.play_container == True:
if item.childCount > 0:
dfr = self.get_children(request_count=1)
dfr.addCallback(got_child, item)
return dfr
return item
def got_child(children, item):
res = DIDLLite.PlayContainerResource(self.store.server.uuid,
cid=self.get_id(),
fid=children[0].get_id())
item.res.append(res)
return item
dfr = defer.maybeDeferred(self.get_child_count)
dfr.addCallback(got_count)
return dfr
def get_name(self):
return self.name
def get_id(self):
return self.id
class Artist(BackendItem):
def __init__(self, *args, **kwargs):
BackendItem.__init__(self, *args, **kwargs)
self._row = args[0]
self._db = args[1]
self._local_music_library_id = args[2]
self.musicbrainz_id = self._row.MusicBrainzID
self.itemID = self._row.ArtistID
self.name = self._row.Name or ''
if self.name:
self.name = self.name.encode("utf-8")
def get_children(self,start=0, end=0):
albums = []
def query_db():
q = "select * from CoreAlbums where ArtistID=? and AlbumID in "\
"(select distinct(AlbumID) from CoreTracks where "\
"PrimarySourceID=?) order by Title"
rows = self._db.sql_execute(q, self.itemID,
self._local_music_library_id)
for row in rows:
album = Album(row, self._db, self)
albums.append(album)
yield album
dfr = task.coiterate(query_db())
dfr.addCallback(lambda gen: albums)
return dfr
def get_child_count(self):
q = "select count(AlbumID) as c from CoreAlbums where ArtistID=? and "\
"AlbumID in (select distinct(AlbumID) from CoreTracks where "\
"PrimarySourceID=?) "
return self._db.sql_execute(q, self.itemID,
self._local_music_library_id)[0].c
def get_item(self):
item = DIDLLite.MusicArtist(self.get_id(),
AUDIO_ARTIST_CONTAINER_ID, self.name)
item.childCount = self.get_child_count()
return item
def get_id(self):
return "artist.%d" % self.itemID
def __repr__(self):
return '<Artist %d name="%s" musicbrainz="%s">' % (self.itemID,
self.name,
self.musicbrainz_id)
class Album(BackendItem):
""" definition for an album """
mimetype = 'directory'
get_path = None
def __init__(self, *args, **kwargs):
BackendItem.__init__(self, *args, **kwargs)
self._row = args[0]
self._db = args[1]
self.artist = args[2]
self.itemID = self._row.AlbumID
self.title = self._row.Title
self.cover = get_cover_path(self.artist.name, self.title)
if self.title:
self.title = self.title.encode("utf-8")
self.musicbrainz_id = self._row.MusicBrainzID
self.cd_count = 1
def get_children(self,start=0,request_count=0):
tracks = []
def query_db():
q = "select * from CoreTracks where AlbumID=? order by TrackNumber"
if request_count:
q += " limit %d" % request_count
rows = self._db.sql_execute(q, self.itemID)
for row in rows:
track = Track(row, self._db, self)
tracks.append(track)
yield track
dfr = task.coiterate(query_db())
dfr.addCallback(lambda gen: tracks)
return dfr
def get_child_count(self):
q = "select count(TrackID) as c from CoreTracks where AlbumID=?"
count = self._db.sql_execute(q, self.itemID)[0].c
return count
def get_item(self):
item = DIDLLite.MusicAlbum(self.get_id(), AUDIO_ALBUM_CONTAINER_ID, self.title)
item.artist = self.artist.name
item.childCount = self.get_child_count()
if self.cover:
_,ext = os.path.splitext(self.cover)
item.albumArtURI = ''.join((self._db.urlbase,
self.get_id(), '?cover', ext))
def got_tracks(tracks):
res = DIDLLite.PlayContainerResource(self._db.server.uuid,
cid=self.get_id(),
fid=tracks[0].get_id())
item.res.append(res)
return item
if item.childCount > 0:
dfr = self.get_children(request_count=1)
dfr.addCallback(got_tracks)
else:
dfr = defer.succeed(item)
return dfr
def get_id(self):
return "album.%d" % self.itemID
def get_name(self):
return self.title
def get_cover(self):
return self.cover
def __repr__(self):
return '<Album %d title="%s" artist="%s" #cds %d cover="%s" musicbrainz="%s">' \
% (self.itemID, self.title,
self.artist.name,
self.cd_count,
self.cover,
self.musicbrainz_id)
class BasePlaylist(BackendItem):
""" definition for a playlist """
mimetype = 'directory'
get_path = None
def __init__(self, *args, **kwargs):
BackendItem.__init__(self, *args, **kwargs)
self._row = args[0]
self._store = args[1]
self._db = self._store.db
self.title = self._row.Name
if self.title:
self.title = self.title.encode("utf-8")
def get_tracks(self, request_count):
return []
def db_to_didl(self, row):
album = self._store.get_album_with_id(row.AlbumID)
track = Track(row, self._db, album)
return track
def get_id(self):
return "%s.%d" % (self.id_type, self.db_id)
def __repr__(self):
return '<%s %d title="%s">' % (self.__class___.__name__,
self.db_id, self.title)
def get_children(self, start=0, request_count=0):
tracks = []
def query_db():
rows = self.get_tracks(request_count)
for row in rows:
track = self.db_to_didl(row)
tracks.append(track)
yield track
dfr = task.coiterate(query_db())
dfr.addCallback(lambda gen: tracks)
return dfr
def get_child_count(self):
return self._row.CachedCount
def get_item(self):
item = DIDLLite.PlaylistContainer(self.get_id(),
AUDIO_PLAYLIST_CONTAINER_ID,
self.title)
item.childCount = self.get_child_count()
def got_tracks(tracks):
res = DIDLLite.PlayContainerResource(self._db.server.uuid,
cid=self.get_id(),
fid=tracks[0].get_id())
item.res.append(res)
return item
if item.childCount > 0:
dfr = self.get_children(request_count=1)
dfr.addCallback(got_tracks)
else:
dfr = defer.succeed(item)
return dfr
def get_name(self):
return self.title
class MusicPlaylist(BasePlaylist):
id_type = "musicplaylist"
@property
def db_id(self):
return self._row.PlaylistID
def get_tracks(self, request_count):
q = "select * from CoreTracks where TrackID in (select TrackID "\
"from CorePlaylistEntries where PlaylistID=?)"
if request_count:
q += " limit %d" % request_count
return self._db.sql_execute(q, self.db_id)
class MusicSmartPlaylist(BasePlaylist):
id_type = "musicsmartplaylist"
@property
def db_id(self):
return self._row.SmartPlaylistID
def get_tracks(self, request_count):
q = "select * from CoreTracks where TrackID in (select TrackID "\
"from CoreSmartPlaylistEntries where SmartPlaylistID=?)"
if request_count:
q += " limit %d" % request_count
return self._db.sql_execute(q, self.db_id)
class VideoPlaylist(MusicPlaylist):
id_type = "videoplaylist"
def db_to_didl(self, row):
return Video(row, self._db)
class VideoSmartPlaylist(MusicSmartPlaylist):
id_type = "videosmartplaylist"
def db_to_didl(self, row):
return Video(row, self._db)
class BaseTrack(BackendItem):
""" definition for a track """
def __init__(self, *args, **kwargs):
BackendItem.__init__(self, *args, **kwargs)
self._row = args[0]
self._db = args[1]
self.itemID = self._row.TrackID
self.title = self._row.Title
self.track_nr = self._row.TrackNumber
self.location = self._row.Uri
self.playlist = kwargs.get("playlist")
def get_children(self,start=0,request_count=0):
return []
def get_child_count(self):
return 0
def get_resources(self):
resources = []
_,host_port,_,_,_ = urlsplit(self._db.urlbase)
if host_port.find(':') != -1:
host,port = tuple(host_port.split(':'))
else:
host = host_port
_,ext = os.path.splitext(self.location)
ext = ext.lower()
# FIXME: drop this hack when we switch to tagbin
mimetype, dummy = mimetypes.guess_type("dummy%s" % ext)
if not mimetype:
mimetype = 'audio/mpeg'
ext = "mp3"
statinfo = os.stat(self.get_path())
res = DIDLLite.Resource(self.location, 'internal:%s:%s:*' % (host,
mimetype))
try:
res.size = statinfo.st_size
except:
res.size = 0
resources.append(res)
url = "%s%s%s" % (self._db.urlbase, self.get_id(), ext)
res = DIDLLite.Resource(url, 'http-get:*:%s:*' % mimetype)
try:
res.size = statinfo.st_size
except:
res.size = 0
resources.append(res)
return statinfo, resources
def get_path(self):
return urllib2.unquote(self.location[7:].encode('utf-8'))
def get_id(self):
return "track.%d" % self.itemID
def get_name(self):
return self.title
def get_url(self):
return self._db.urlbase + str(self.itemID).encode('utf-8')
def get_cover(self):
return self.album.cover
def __repr__(self):
return '<Track %d title="%s" nr="%d" album="%s" artist="%s" path="%s">' \
% (self.itemID, self.title, self.track_nr, self.album.title,
self.album.artist.name, self.location)
class Track(BaseTrack):
def __init__(self, *args, **kwargs):
BaseTrack.__init__(self, *args, **kwargs)
self.album = args[2]
def get_item(self):
item = DIDLLite.MusicTrack(self.get_id(), self.album.itemID,self.title)
item.artist = self.album.artist.name
item.album = self.album.title
item.playlist = self.playlist
if self.album.cover != '':
_,ext = os.path.splitext(self.album.cover)
""" add the cover image extension to help clients not reacting on
the mimetype """
item.albumArtURI = ''.join((self._db.urlbase, self.get_id(),
'?cover',ext))
item.originalTrackNumber = self.track_nr
item.server_uuid = str(self._db.server.uuid)[5:]
statinfo, resources = self.get_resources()
item.res.extend(resources)
try:
# FIXME: getmtime is deprecated in Twisted 2.6
item.date = datetime.fromtimestamp(statinfo.st_mtime)
except:
item.date = None
return item
class Video(BaseTrack):
def get_item(self):
item = DIDLLite.VideoItem(self.get_id(), VIDEO_ALL_CONTAINER_ID,
self.title)
item.server_uuid = str(self._db.server.uuid)[5:]
statinfo, resources = self.get_resources()
item.res.extend(resources)
try:
# FIXME: getmtime is deprecated in Twisted 2.6
item.date = datetime.fromtimestamp(statinfo.st_mtime)
except:
item.date = None
return item
class BansheeDB(Loggable):
logCategory = "banshee_db"
def __init__(self, path=None):
Loggable.__init__(self)
self._local_music_library_id = None
self._local_video_library_id = None
default_db_path = os.path.expanduser("~/.config/banshee-1/banshee.db")
self._db_path = path or default_db_path
def open_db(self):
self.db = SQLiteDB(self._db_path)
def close(self):
self.db.disconnect()
def get_local_music_library_id(self):
if self._local_music_library_id is None:
q = "select PrimarySourceID from CorePrimarySources where StringID=?"
row = self.db.sql_execute(q, 'MusicLibrarySource-Library')[0]
self._local_music_library_id = row.PrimarySourceID
return self._local_music_library_id
def get_local_video_library_id(self):
if self._local_video_library_id is None:
q = "select PrimarySourceID from CorePrimarySources where StringID=?"
row = self.db.sql_execute(q, 'VideoLibrarySource-VideoLibrary')[0]
self._local_video_library_id = row.PrimarySourceID
return self._local_video_library_id
def get_artists(self):
artists = []
def query_db():
source_id = self.get_local_music_library_id()
q = "select * from CoreArtists where ArtistID in "\
"(select distinct(ArtistID) from CoreTracks where "\
"PrimarySourceID=?) order by Name"
for row in self.db.sql_execute(q, source_id):
artist = Artist(row, self.db, source_id)
artists.append(artist)
yield artist
dfr = task.coiterate(query_db())
dfr.addCallback(lambda gen: artists)
return dfr
def get_albums(self):
albums = []
artists = {}
def query_db():
q = "select * from CoreAlbums where AlbumID in "\
"(select distinct(AlbumID) from CoreTracks where "\
"PrimarySourceID=?) order by Title"
for row in self.db.sql_execute(q, self.get_local_music_library_id()):
try:
artist = artists[row.ArtistID]
except KeyError:
artist = self.get_artist_with_id(row.ArtistID)
artists[row.ArtistID] = artist
album = Album(row, self.db, artist)
albums.append(album)
yield album
dfr = task.coiterate(query_db())
dfr.addCallback(lambda gen: albums)
return dfr
def get_music_playlists(self):
return self.get_playlists(self.get_local_music_library_id(),
MusicPlaylist, MusicSmartPlaylist)
def get_playlists(self, source_id, PlaylistClass, SmartPlaylistClass):
playlists = []
def query_db():
q = "select * from CorePlaylists where PrimarySourceID=? order by Name"
for row in self.db.sql_execute(q, source_id):
playlist = PlaylistClass(row, self)
playlists.append(playlist)
yield playlist
q = "select * from CoreSmartPlaylists where PrimarySourceID=? order by Name"
for row in self.db.sql_execute(q, source_id):
playlist = SmartPlaylistClass(row, self)
playlists.append(playlist)
yield playlist
dfr = task.coiterate(query_db())
dfr.addCallback(lambda gen: playlists)
return dfr
def get_artist_with_id(self, artist_id):
q = "select * from CoreArtists where ArtistID=? limit 1"
row = self.db.sql_execute(q, artist_id)[0]
return Artist(row, self.db, self.get_local_music_library_id())
def get_album_with_id(self, album_id):
q = "select * from CoreAlbums where AlbumID=? limit 1"
row = self.db.sql_execute(q, album_id)[0]
artist = self.get_artist_with_id(row.ArtistID)
return Album(row, self.db, artist)
def get_playlist_with_id(self, playlist_id, PlaylistClass):
q = "select * from CorePlaylists where PlaylistID=? limit 1"
row = self.db.sql_execute(q, playlist_id)[0]
return PlaylistClass(row, self)
def get_smart_playlist_with_id(self, playlist_id, PlaylistClass):
q = "select * from CoreSmartPlaylists where SmartPlaylistID=? limit 1"
row = self.db.sql_execute(q, playlist_id)[0]
return PlaylistClass(row, self)
def get_music_playlist_with_id(self, playlist_id):
return self.get_playlist_with_id(playlist_id, MusicPlaylist)
def get_music_smart_playlist_with_id(self, playlist_id):
return self.get_smart_playlist_with_id(playlist_id, MusicSmartPlaylist)
def get_video_playlist_with_id(self, playlist_id):
return self.get_playlist_with_id(playlist_id, VideoPlaylist)
def get_video_smart_playlist_with_id(self, playlist_id):
return self.get_smart_playlist_with_id(playlist_id, VideoSmartPlaylist)
def get_track_with_id(self, track_id):
q = "select * from CoreTracks where TrackID=? limit 1"
row = self.db.sql_execute(q, track_id)[0]
album = self.get_album_with_id(row.AlbumID)
return Track(row, self.db, album)
def get_track_for_uri(self, track_uri):
q = "select * from CoreTracks where Uri=? limit 1"
try:
row = self.db.sql_execute(q, track_uri)[0]
except IndexError:
# not found
track = None
else:
album = self.get_album_with_id(row.AlbumID)
track = Track(row, self, album)
return track
def get_tracks(self):
tracks = []
albums = {}
def query_db():
q = "select * from CoreTracks where TrackID in "\
"(select distinct(TrackID) from CoreTracks where "\
"PrimarySourceID=?) order by AlbumID,TrackNumber"
for row in self.db.sql_execute(q, self.get_local_music_library_id()):
if row.AlbumID not in albums:
album = self.get_album_with_id(row.AlbumID)
albums[row.AlbumID] = album
else:
album = albums[row.AlbumID]
track = Track(row, self.db,album)
tracks.append(track)
yield track
dfr = task.coiterate(query_db())
dfr.addCallback(lambda gen: tracks)
return dfr
def get_video_with_id(self, video_id):
q = "select * from CoreTracks where TrackID=? limit 1"
row = self.db.sql_execute(q, video_id)[0]
return Video(row, self.db)
def get_videos(self):
videos = []
def query_db():
source_id = self.get_local_video_library_id()
q = "select * from CoreTracks where TrackID in "\
"(select distinct(TrackID) from CoreTracks where "\
"PrimarySourceID=?)"
for row in self.db.sql_execute(q, source_id):
video = Video(row, self.db, source_id)
videos.append(video)
yield video
dfr = task.coiterate(query_db())
dfr.addCallback(lambda gen: videos)
return dfr
def get_video_playlists(self):
return self.get_playlists(self.get_local_video_library_id(),
VideoPlaylist, VideoSmartPlaylist)
class BansheeStore(BackendStore, BansheeDB):
logCategory = 'banshee_store'
implements = ['MediaServer']
def __init__(self, server, **kwargs):
BackendStore.__init__(self,server,**kwargs)
BansheeDB.__init__(self, kwargs.get("db_path"))
self.update_id = 0
self.name = kwargs.get('name', 'Banshee')
self.containers = {}
self.containers[ROOT_CONTAINER_ID] = Container(ROOT_CONTAINER_ID,
-1, self.name, store=self)
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
def upnp_init(self):
self.open_db()
music = Container(AUDIO_CONTAINER, ROOT_CONTAINER_ID,
'Music', store=self)
self.containers[ROOT_CONTAINER_ID].add_child(music)
self.containers[AUDIO_CONTAINER] = music
artists = Container(AUDIO_ARTIST_CONTAINER_ID, AUDIO_CONTAINER,
'Artists', children_callback=self.get_artists,
store=self)
self.containers[AUDIO_ARTIST_CONTAINER_ID] = artists
self.containers[AUDIO_CONTAINER].add_child(artists)
albums = Container(AUDIO_ALBUM_CONTAINER_ID, AUDIO_CONTAINER,
'Albums', children_callback=self.get_albums,
store=self)
self.containers[AUDIO_ALBUM_CONTAINER_ID] = albums
self.containers[AUDIO_CONTAINER].add_child(albums)
tracks = Container(AUDIO_ALL_CONTAINER_ID, AUDIO_CONTAINER,
'All tracks', children_callback=self.get_tracks,
play_container=True, store=self)
self.containers[AUDIO_ALL_CONTAINER_ID] = tracks
self.containers[AUDIO_CONTAINER].add_child(tracks)
playlists = Container(AUDIO_PLAYLIST_CONTAINER_ID, AUDIO_CONTAINER,
'Playlists', store=self,
children_callback=self.get_music_playlists)
self.containers[AUDIO_PLAYLIST_CONTAINER_ID] = playlists
self.containers[AUDIO_CONTAINER].add_child(playlists)
videos = Container(VIDEO_CONTAINER, ROOT_CONTAINER_ID,
'Videos', store=self)
self.containers[ROOT_CONTAINER_ID].add_child(videos)
self.containers[VIDEO_CONTAINER] = videos
all_videos = Container(VIDEO_ALL_CONTAINER_ID, VIDEO_CONTAINER,
'All Videos', children_callback=self.get_videos,
store=self)
self.containers[VIDEO_ALL_CONTAINER_ID] = all_videos
self.containers[VIDEO_CONTAINER].add_child(all_videos)
playlists = Container(VIDEO_PLAYLIST_CONTAINER_ID, VIDEO_CONTAINER,
'Playlists', store=self,
children_callback=self.get_video_playlists)
self.containers[VIDEO_PLAYLIST_CONTAINER_ID] = playlists
self.containers[VIDEO_CONTAINER].add_child(playlists)
self.db.server = self.server
self.db.urlbase = self.urlbase
self.db.containers = self.containers
self.current_connection_id = None
if self.server:
hostname = self.server.coherence.hostname
source_protocol_info = ['internal:%s:audio/mpeg:*' % hostname,
'http-get:*:audio/mpeg:*',
'internal:%s:application/ogg:*' % hostname,
'http-get:*:application/ogg:*']
self.server.connection_manager_server.set_variable(0,
'SourceProtocolInfo',
source_protocol_info,
default=True)
def release(self):
self.db.disconnect()
def get_by_id(self,item_id):
self.info("get_by_id %s" % item_id)
if isinstance(item_id, basestring) and item_id.find('.') > 0:
item_id = item_id.split('@',1)
item_type, item_id = item_id[0].split('.')[:2]
item_id = int(item_id)
dfr = self._lookup(item_type, item_id)
else:
item_id = int(item_id)
item = self.containers[item_id]
dfr = defer.succeed(item)
return dfr
def _lookup(self, item_type, item_id):
lookup_mapping = dict(artist=self.get_artist_with_id,
album=self.get_album_with_id,
musicplaylist=self.get_music_playlist_with_id,
musicsmartplaylist=self.get_music_smart_playlist_with_id,
videoplaylist=self.get_video_playlist_with_id,
videosmartplaylist=self.get_video_smart_playlist_with_id,
track=self.get_track_with_id,
video=self.get_video_with_id)
item = None
func = lookup_mapping.get(item_type)
if func:
item = func(item_id)
return defer.succeed(item)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~ampache_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
import time
import mimetypes
mimetypes.init()
try:
import hashlib
def md5(s):
m =hashlib.md5()
m.update(s)
return m.hexdigest()
def sha256(s):
m =hashlib.sha256()
m.update(s)
return m.hexdigest()
except ImportError:
import md5 as oldmd5
def md5(s):
m=oldmd5.new()
m.update(s)
return m.hexdigest()
from twisted.internet import reactor,defer
from twisted.python import failure
from coherence.upnp.core import DIDLLite
from coherence.upnp.core.soap_service import errorCode
from coherence.upnp.core import utils
import coherence.extern.louie as louie
from coherence.backend import BackendItem, BackendStore
ROOT_CONTAINER_ID = 0
AUDIO_CONTAINER = 100
AUDIO_ALL_CONTAINER_ID = 101
AUDIO_ARTIST_CONTAINER_ID = 102
AUDIO_ALBUM_CONTAINER_ID = 103
AUDIO_PLAYLIST_CONTAINER_ID = 104
AUDIO_GENRE_CONTAINER_ID = 105
AUDIO_TAG_CONTAINER_ID = 106
VIDEO_CONTAINER_ID = 200
from urlparse import urlsplit
class ProxySong(utils.ReverseProxyResource):
def __init__(self, uri):
self.uri = uri
_,host_port,path,query,_ = urlsplit(uri)
if host_port.find(':') != -1:
host,port = tuple(host_port.split(':'))
port = int(port)
else:
host = host_port
port = 80
utils.ReverseProxyResource.__init__(self, host, port, '?'.join((path,query)))
class Container(BackendItem):
logCategory = 'ampache_store'
get_path = None
def __init__(self, id, parent_id, name, store=None, children_callback=None, container_class=DIDLLite.Container,play_container=False):
self.id = id
self.parent_id = parent_id
self.name = name
self.mimetype = 'directory'
self.container_class = container_class
self.update_id = 0
if children_callback != None:
self.children = children_callback
else:
self.children = []
self.childCount = None
self.store = store
self.play_container = play_container
if self.store!=None:
self.get_url = lambda: self.store.urlbase + str(self.id)
def add_child(self, child):
self.children.append(child)
if self.childCount == None:
self.childCount = 0
self.childCount += 1
def get_children(self,start=0,end=0):
self.info("container.get_children %r %r", start, end)
if(end - start > 250 or
end - start == 0):
end = start+250
if callable(self.children):
return self.children(start,end-start)
else:
children = self.children
if end == 0:
return children[start:]
else:
return children[start:end]
def get_child_count(self):
if self.childCount == None:
if callable(self.children):
self.childCount = len(self.children())
else:
self.childCount = len(self.children)
return self.childCount
def get_item(self):
item = self.container_class(self.id, self.parent_id,self.name)
item.childCount = self.get_child_count()
#if self.store and self.play_container == True:
# if item.childCount > 0:
# d = defer.maybeDeferred(self.get_children, 0, 1)
# def process_result(r,item):
# res = DIDLLite.PlayContainerResource(self.store.server.uuid,cid=self.get_id(),fid=r[0].get_id())
# item.res.append(res)
# return item
# def got_error(f,item):
# return item
# d.addCallback(process_result,item)
# d.addErrback(got_error,item)
# return d
return item
def get_name(self):
return self.name
def get_id(self):
return self.id
class Playlist(BackendItem):
logCategory = 'ampache_store'
get_path = None
def __init__(self, store, element):
self.store = store
self.ampache_id = element.get('id')
self.id = 'playlist.%d' % int(element.get('id'))
self.title = element.find('name').text
self.creator = element.find('owner').text
self.tracks = int(element.find('items').text)
try:
self.cover = element.find('art').text
except:
self.cover = None
def get_children(self,start=0,end=0):
return self.store.ampache_query('playlist_songs', start, end-start, filter=self.ampache_id)
def get_child_count(self):
return self.tracks
def get_item(self, parent_id = AUDIO_PLAYLIST_CONTAINER_ID):
item = DIDLLite.PlaylistItem(self.id, parent_id, self.title)
item.childCount = self.get_child_count()
#item.artist = self.artist
item.albumArtURI = self.cover
return item
def get_id(self):
return self.id
def get_name(self):
return self.title
def get_cover(self):
return self.cover
class Album(BackendItem):
logCategory = 'ampache_store'
get_path = None
def __init__(self, store, element):
self.store = store
self.ampache_id = element.get('id')
self.id = 'album.%d' % int(element.get('id'))
self.title = element.find('name').text
self.artist = element.find('artist').text
self.tracks = int(element.find('tracks').text)
try:
self.cover = element.find('art').text
except:
self.cover = None
def get_children(self,start=0,end=0):
return self.store.ampache_query('album_songs', start, end-start, filter=self.ampache_id)
def get_child_count(self):
return self.tracks
def get_item(self, parent_id = AUDIO_ALBUM_CONTAINER_ID):
item = DIDLLite.MusicAlbum(self.id, parent_id, self.title)
item.childCount = self.get_child_count()
item.artist = self.artist
item.albumArtURI = self.cover
#if item.childCount > 0:
# d = defer.maybeDeferred(self.get_children, 0, 1)
# def process_result(r,item):
# res = DIDLLite.PlayContainerResource(self.store.server.uuid,cid=self.get_id(),fid=r[0].get_id())
# item.res.append(res)
# return item
# def got_error(f,item):
# return item
# d.addCallback(process_result,item)
# d.addErrback(got_error,item)
# return d
return item
def get_id(self):
return self.id
def get_name(self):
return self.title
def get_cover(self):
return self.cover
class Artist(BackendItem):
logCategory = 'ampache_store'
get_path = None
def __init__(self, store, element):
self.store = store
self.ampache_id = element.get('id')
self.id = 'artist.%d' % int(element.get('id'))
try:
self.count_albums = int(element.find('albums').text)
except:
self.count_albums = None
try:
self.count_songs = int(element.find('songs').text)
except:
self.count_songs = None
self.name = element.find('name').text
def get_children(self,start=0,end=0):
return self.store.ampache_query('artist_albums', start, end-start, filter=self.ampache_id)
def get_child_count(self):
if self.count_albums != None:
return self.count_albums
def got_childs(result):
self.count_albums = len(result)
return self.count_albums
d = self.get_children()
d.addCallback(got_childs)
return d
def get_item(self, parent_id = AUDIO_ARTIST_CONTAINER_ID):
item = DIDLLite.MusicArtist(self.id, parent_id, self.name)
return item
def get_id(self):
return self.id
def get_name(self):
return self.name
class Genre(BackendItem):
logCategory = 'ampache_store'
get_path = None
def __init__(self, store, element):
self.store = store
self.ampache_id = element.get('id')
self.id = 'genre.%d' % int(element.get('id'))
try:
self.count_albums = int(element.find('albums').text)
except:
self.count_albums = None
try:
self.count_artists = int(element.find('artists').text)
except:
self.count_artists = None
try:
self.count_songs = int(element.find('songs').text)
except:
self.count_songs = None
self.name = element.find('name').text
def get_children(self,start=0,end=0):
return self.store.ampache_query('genre_songs', start, end-start, filter=self.ampache_id)
def get_child_count(self):
if self.count_songs != None:
return self.count_songs
def got_childs(result):
self.count_songs = len(result)
return self.count_songs
d = self.get_children()
d.addCallback(got_childs)
return d
def get_item(self, parent_id = AUDIO_GENRE_CONTAINER_ID):
item = DIDLLite.Genre(self.id, parent_id, self.name)
return item
def get_id(self):
return self.id
def get_name(self):
return self.name
class Tag(BackendItem):
logCategory = 'ampache_store'
get_path = None
def __init__(self, store, element):
self.store = store
self.ampache_id = element.get('id')
self.id = 'tag.%d' % int(element.get('id'))
try:
self.count_albums = int(element.find('albums').text)
except:
self.count_albums = None
try:
self.count_artists = int(element.find('artists').text)
except:
self.count_artists = None
try:
self.count_songs = int(element.find('songs').text)
except:
self.count_songs = None
self.name = element.find('name').text
def get_children(self,start=0,end=0):
return self.store.ampache_query('tag_songs', start, end-start, filter=self.ampache_id)
def get_child_count(self):
if self.count_songs != None:
return self.count_songs
def got_childs(result):
self.count_songs = len(result)
return self.count_songs
d = self.get_children()
d.addCallback(got_childs)
return d
def get_item(self, parent_id = AUDIO_TAG_CONTAINER_ID):
item = DIDLLite.Genre(self.id, parent_id, self.name)
return item
def get_id(self):
return self.id
def get_name(self):
return self.name
class Track(BackendItem):
logCategory = 'ampache_store'
def __init__(self,store,element):
self.store = store
self.id = 'song.%d' % int(element.get('id'))
self.parent_id = 'album.%d' % int(element.find('album').get('id'))
self.url = element.find('url').text
seconds = int(element.find('time').text)
hours = seconds / 3600
seconds = seconds - hours * 3600
minutes = seconds / 60
seconds = seconds - minutes * 60
self.duration = ("%d:%02d:%02d") % (hours, minutes, seconds)
self.bitrate = 0
self.title = element.find('title').text
self.artist = element.find('artist').text
self.album = element.find('album').text
self.genre = element.find('genre').text
self.track_nr = element.find('track').text
try:
self.cover = element.find('art').text
except:
self.cover = None
self.mimetype = None
try:
self.mimetype = element.find('mime').text
except:
self.mimetype,_ = mimetypes.guess_type(self.url, strict=False)
if self.mimetype == None:
self.mimetype = "audio/mpeg"
try:
self.size = int(element.find('size').text)
except:
self.size = 0
if self.store.proxy == True:
self.location = ProxySong(self.url)
def get_children(self, start=0, request_count=0):
return []
def get_child_count(self):
return 0
def get_item(self, parent_id=None):
self.debug("Track get_item %r @ %r" %(self.id,self.parent_id))
# create item
item = DIDLLite.MusicTrack(self.id,self.parent_id)
item.album = self.album
item.artist = self.artist
#item.date =
item.genre = self.genre
item.originalTrackNumber = self.track_nr
item.title = self.title
item.albumArtURI = self.cover
# add http resource
res = DIDLLite.Resource(self.get_url(), 'http-get:*:%s:*' % self.mimetype)
if self.size > 0:
res.size = self.size
if self.duration > 0:
res.duration = str(self.duration)
if self.bitrate > 0:
res.bitrate = str(bitrate)
item.res.append(res)
return item
def get_id(self):
return self.id
def get_name(self):
return self.title
def get_url(self):
if self.store.proxy == True:
return self.store.urlbase + str(self.id)
else:
return self.url
def get_path(self):
return None
class Video(BackendItem):
logCategory = 'ampache_store'
def __init__(self,store,element):
self.store = store
self.id = 'video.%d' % int(element.get('id'))
self.url = element.find('url').text
try:
seconds = int(element.find('time').text)
hours = seconds / 3600
seconds = seconds - hours * 3600
minutes = seconds / 60
seconds = seconds - minutes * 60
self.duration = ("%d:%02d:%02d") % (hours, minutes, seconds)
except:
self.duration = 0
self.cover = None
self.title = element.find('title').text
self.mimetype = None
try:
self.mimetype = element.find('mime').text
except:
self.mimetype,_ = mimetypes.guess_type(self.url, strict=False)
if self.mimetype == None:
self.mimetype = "video/avi"
try:
self.size = int(element.find('size').text)
except:
self.size = 0
if self.store.proxy == True:
self.location = ProxySong(self.url)
def get_children(self, start=0, request_count=0):
return []
def get_child_count(self):
return 0
def get_item(self, parent_id=VIDEO_CONTAINER_ID):
self.debug("video get_item %r @ %r" %(self.id,parent_id))
# create item
item = DIDLLite.VideoItem(self.id,parent_id)
item.title = self.title
item.albumArtURI = self.cover
# add http resource
res = DIDLLite.Resource(self.get_url(), 'http-get:*:%s:*' % self.mimetype)
if self.size > 0:
res.size = self.size
if self.duration > 0:
res.duration = str(self.duration)
item.res.append(res)
return item
def get_id(self):
return self.id
def get_name(self):
return self.title
def get_url(self):
if self.store.proxy == True:
return self.store.urlbase + str(self.id)
else:
return self.url
def get_path(self):
return None
class AmpacheStore(BackendStore):
""" this is a backend to the Ampache Media DB
"""
implements = ['MediaServer']
logCategory = 'ampache_store'
def __init__(self, server, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.config = kwargs
self.name = kwargs.get('name','Ampache')
self.key = kwargs.get('password',kwargs.get('key',''))
self.user = kwargs.get('user',None)
self.url = kwargs.get('url','http://localhost/ampache/server/xml.server.php')
if kwargs.get('proxy','no') in [1,'Yes','yes','True','true']:
self.proxy = True
else:
self.proxy = False
self.update_id = 0
self.token = None
self.songs = 0
self.albums = 0
self.artists = 0
self.api_version=int(kwargs.get('api_version',350001))
#self.api_version=int(kwargs.get('api_version',340001))
self.get_token()
def __repr__(self):
return "Ampache storage"
def get_by_id(self,id):
self.info("looking for id %r", id)
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
if isinstance(id, basestring) and id.startswith('artist_all_tracks_'):
try:
return self.containers[id]
except:
return None
item = None
try:
id = int(id)
item = self.containers[id]
except ValueError:
try:
type,id = id.split('.')
if type in ['song','artist','album','playlist','genre','tag','video']:
item = self.ampache_query(type, filter=str(id))
except ValueError:
return None
return item
def got_auth_response( self,response,renegotiate=False):
self.info( "got_auth_response %r", response)
try:
response = utils.parse_xml(response, encoding='utf-8')
except SyntaxError, msg:
self.warning('error parsing ampache answer %r', msg)
raise SyntaxError('error parsing ampache answer %r' % msg)
try:
error = response.find('error').text
self.warning('error on token request %r', error)
raise ValueError(error)
except AttributeError:
try:
self.token = response.find('auth').text
self.songs = int(response.find('songs').text)
self.albums = int(response.find('albums').text)
self.artists = int(response.find('artists').text)
try:
self.playlists = int(response.find('playlists').text)
except:
self.playlists = 0
try:
self.genres = int(response.find('genres').text)
except:
self.genres = 0
try:
self.tags = int(response.find('tags').text)
except:
self.tags = 0
try:
self.videos = int(response.find('videos').text)
except:
self.videos = 0
self.info('ampache returned auth token %r', self.token)
self.info('Songs: %d, Artists: %d, Albums: %d, Playlists %d, Genres %d, Tags %d, Videos %d' %
(self.songs, self.artists,self.albums,self.playlists,self.genres,self.tags,self.videos))
if renegotiate == False:
self.containers = {}
self.containers[ROOT_CONTAINER_ID] = \
Container( ROOT_CONTAINER_ID,-1, self.name, store=self)
self.wmc_mapping.update({'4': lambda : self.get_by_id(AUDIO_ALL_CONTAINER_ID), # all tracks
'5': lambda : self.get_by_id(AUDIO_GENRE_CONTAINER_ID), # all genres
'6': lambda : self.get_by_id(AUDIO_ARTIST_CONTAINER_ID), # all artists
'7': lambda : self.get_by_id(AUDIO_ALBUM_CONTAINER_ID), # all albums
'13': lambda : self.get_by_id(AUDIO_PLAYLIST_CONTAINER_ID), # all playlists
'8': lambda : self.get_by_id(VIDEO_CONTAINER_ID), # all videos
})
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
except AttributeError:
raise ValueError('no authorization token returned')
def got_auth_error(self,e,renegotiate=False):
self.warning('error calling ampache %r', e)
if renegotiate == False:
louie.send('Coherence.UPnP.Backend.init_failed', None, backend=self, msg=e)
def get_token(self,renegotiate=False):
""" ask Ampache for the authorization token """
timestamp = int(time.time())
if self.api_version < 350001:
passphrase = md5('%d%s' % (timestamp, self.key))
else:
passphrase = sha256('%d%s' % (timestamp, sha256(self.key)))
request = ''.join((self.url, '?action=handshake&auth=%s×tamp=%d' % (passphrase, timestamp)))
if self.user != None:
request = ''.join((request, '&user=%s' % self.user))
if self.api_version != None:
request = ''.join((request, '&version=%s' % str(self.api_version)))
self.info("auth_request %r", request)
d = utils.getPage(request)
d.addCallback(self.got_auth_response,renegotiate)
d.addErrback(self.got_auth_error,renegotiate)
return d
def got_error(self, e):
self.warning('error calling ampache %r', e)
return e
def got_response(self, response, query_item, request):
self.info("got a response for %r", query_item)
self.debug(response)
response = utils.parse_xml(response, encoding='utf-8')
items = []
try:
error = response.find('error')
self.warning('error on token request %r %r' % (error.attrib['code'], error.text))
if error.attrib['code'] == '401': # session error, we need to renegotiate our session
d = self.get_token(renegotiate=True)
def resend_request(result, old_request):
# exchange the auth token in the resending request
new_request = old_request.split('&')
for part in new_request:
if part.startswith('auth='):
new_request[new_request.index(part)] = 'auth=%s' % self.token
break
new_request = '&'.join(new_request)
self.info("ampache_query %r", new_request)
return utils.getPage(new_request)
d.addCallback(resend_request, request)
d.addErrBack(self.got_error)
return d
raise ValueError(error.text)
except AttributeError:
if query_item in ('song','artist','album','playlist','genre','tag','video'):
q = response.find(query_item)
if q == None:
return None
else:
if q.tag in ['song']:
return Track(self,q)
if q.tag == 'artist':
return Artist(self,q)
if q.tag in ['album']:
return Album(self,q)
if q.tag in ['playlist']:
return Playlist(self,q)
if q.tag in ['genre']:
return Genre(self,q)
if q.tag in ['tag']:
return Tag(self,q)
if q.tag in ['video']:
return Video(self,q)
else:
if query_item in ('songs','artists','albums','playlists','genres','tags','videos'):
query_item = query_item[:-1]
if query_item in ('playlist_songs','album_songs','genre_songs','tag_songs'):
query_item = 'song'
if query_item in ('artist_albums',):
query_item = 'album'
for q in response.findall(query_item):
if query_item in ('song',):
items.append(Track(self,q))
if query_item in ('artist',):
items.append(Artist(self,q))
if query_item in ('album',):
items.append(Album(self,q))
if query_item in ('playlist',):
items.append(Playlist(self,q))
if query_item in ('genre',):
items.append(Genre(self,q))
if query_item in ('tag',):
items.append(Tag(self,q))
if query_item in ('video',):
items.append(Video(self,q))
return items
def ampache_query(self, item, start=0, request_count=0, filter=None):
request = ''.join((self.url, '?action=%s&auth=%s&offset=%d' % (item,self.token, start)))
if request_count > 0:
request = ''.join((request, '&limit=%d' % request_count))
if filter != None:
request = ''.join((request, '&filter=%s' % filter))
self.info("ampache_query %r", request)
d = utils.getPage(request)
d.addCallback(self.got_response, item, request)
d.addErrback(self.got_error)
return d
def ampache_query_songs(self, start=0, request_count=0):
return self.ampache_query('songs', start, request_count)
def ampache_query_albums(self, start=0, request_count=0):
return self.ampache_query('albums', start, request_count)
def ampache_query_artists(self, start=0, request_count=0):
return self.ampache_query('artists', start, request_count)
def ampache_query_playlists(self, start=0, request_count=0):
return self.ampache_query('playlists', start, request_count)
def ampache_query_genres(self, start=0, request_count=0):
return self.ampache_query('genres', start, request_count)
def ampache_query_tags(self, start=0, request_count=0):
return self.ampache_query('tags', start, request_count)
def ampache_query_videos(self, start=0, request_count=0):
return self.ampache_query('videos', start, request_count)
def upnp_init(self):
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
['http-get:*:audio/mpeg:*',
'http-get:*:application/ogg:*',
'http-get:*:video/mp4:*',
'http-get:*:video/x-msvideo:*',
'http-get:*:video/avi:*',
'http-get:*:video/quicktime:*',])
self.containers[AUDIO_ALL_CONTAINER_ID] = \
Container(AUDIO_ALL_CONTAINER_ID,ROOT_CONTAINER_ID, 'All tracks',
store=self,
children_callback=self.ampache_query_songs,
play_container=True)
self.containers[AUDIO_ALL_CONTAINER_ID].childCount = self.songs
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_ALL_CONTAINER_ID])
self.containers[AUDIO_ALBUM_CONTAINER_ID] = \
Container(AUDIO_ALBUM_CONTAINER_ID,ROOT_CONTAINER_ID, 'Albums',
store=self,
children_callback=self.ampache_query_albums)
self.containers[AUDIO_ALBUM_CONTAINER_ID].childCount = self.albums
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_ALBUM_CONTAINER_ID])
self.containers[AUDIO_ARTIST_CONTAINER_ID] = \
Container( AUDIO_ARTIST_CONTAINER_ID,ROOT_CONTAINER_ID, 'Artists',
store=self,
children_callback=self.ampache_query_artists)
self.containers[AUDIO_ARTIST_CONTAINER_ID].childCount = self.artists
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_ARTIST_CONTAINER_ID])
self.containers[AUDIO_PLAYLIST_CONTAINER_ID] = \
Container(AUDIO_PLAYLIST_CONTAINER_ID,ROOT_CONTAINER_ID, 'Playlists',
store=self,
children_callback=self.ampache_query_playlists,
container_class=DIDLLite.PlaylistContainer)
self.containers[AUDIO_PLAYLIST_CONTAINER_ID].childCount = self.playlists
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_PLAYLIST_CONTAINER_ID])
self.containers[AUDIO_GENRE_CONTAINER_ID] = \
Container(AUDIO_GENRE_CONTAINER_ID,ROOT_CONTAINER_ID, 'Genres',
store=self,
children_callback=self.ampache_query_genres)
self.containers[AUDIO_GENRE_CONTAINER_ID].childCount = self.genres
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_GENRE_CONTAINER_ID])
self.containers[AUDIO_TAG_CONTAINER_ID] = \
Container(AUDIO_TAG_CONTAINER_ID,ROOT_CONTAINER_ID, 'Tags',
store=self,
children_callback=self.ampache_query_tags)
self.containers[AUDIO_TAG_CONTAINER_ID].childCount = self.tags
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_TAG_CONTAINER_ID])
self.containers[VIDEO_CONTAINER_ID] = \
Container(VIDEO_CONTAINER_ID,ROOT_CONTAINER_ID, 'Videos',
store=self,
children_callback=self.ampache_query_videos)
self.containers[VIDEO_CONTAINER_ID].childCount = self.videos
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[VIDEO_CONTAINER_ID])
def upnp_XBrowse(self, *args, **kwargs):
try:
ObjectID = kwargs['ObjectID']
except:
self.debug("hmm, a Browse action and no ObjectID argument? An XBox maybe?")
try:
ObjectID = kwargs['ContainerID']
except:
ObjectID = 0
BrowseFlag = kwargs['BrowseFlag']
Filter = kwargs['Filter']
StartingIndex = int(kwargs['StartingIndex'])
RequestedCount = int(kwargs['RequestedCount'])
SortCriteria = kwargs['SortCriteria']
parent_container = None
requested_id = None
if BrowseFlag == 'BrowseDirectChildren':
parent_container = str(ObjectID)
else:
requested_id = str(ObjectID)
self.info("upnp_Browse request %r %r %r %r", ObjectID, BrowseFlag, StartingIndex, RequestedCount)
didl = DIDLLite.DIDLElement(upnp_client=kwargs.get('X_UPnPClient', ''),
requested_id=requested_id,
parent_container=parent_container)
def build_response(tm):
num_ret = didl.numItems()
#if int(kwargs['RequestedCount']) != 0 and num_ret != int(kwargs['RequestedCount']):
# num_ret = 0
#if RequestedCount == 0 and tm-StartingIndex != num_ret:
# num_ret = 0
r = {'Result': didl.toString(), 'TotalMatches': tm,
'NumberReturned': num_ret}
self.info("upnp_Browse response %r %r", num_ret, tm)
if hasattr(item, 'update_id'):
r['UpdateID'] = item.update_id
elif hasattr(self, 'update_id'):
r['UpdateID'] = self.update_id # FIXME
else:
r['UpdateID'] = 0
return r
total = 0
items = []
wmc_mapping = getattr(self, "wmc_mapping", None)
if(kwargs.get('X_UPnPClient', '') == 'XBox' and
wmc_mapping != None and
wmc_mapping.has_key(ObjectID)):
""" fake a Windows Media Connect Server
"""
root_id = wmc_mapping[ObjectID]
if callable(root_id):
item = root_id()
if item is not None:
if isinstance(item, list):
total = len(item)
if int(RequestedCount) == 0:
items = item[StartingIndex:]
else:
items = item[StartingIndex:StartingIndex+RequestedCount]
else:
d = defer.maybeDeferred( item.get_children, StartingIndex, StartingIndex + RequestedCount)
d.addCallback( process_result)
d.addErrback(got_error)
return d
for i in items:
didl.addItem(i.get_item())
return build_response(total)
root_id = ObjectID
item = self.get_by_id(root_id)
if item == None:
return failure.Failure(errorCode(701))
def got_error(r):
return r
def process_result(result, found_item):
if result == None:
result = []
if BrowseFlag == 'BrowseDirectChildren':
l = []
def process_items(result, tm):
if result == None:
result = []
for i in result:
if i[0] == True:
didl.addItem(i[1])
return build_response(tm)
for i in result:
d = defer.maybeDeferred(i.get_item)
l.append(d)
def got_child_count(count):
dl = defer.DeferredList(l)
dl.addCallback(process_items, count)
return dl
d = defer.maybeDeferred(found_item.get_child_count)
d.addCallback(got_child_count)
return d
else:
didl.addItem(result)
total = 1
return build_response(total)
def proceed(result):
if BrowseFlag == 'BrowseDirectChildren':
d = defer.maybeDeferred( result.get_children, StartingIndex, StartingIndex + RequestedCount)
else:
d = defer.maybeDeferred( result.get_item)
d.addCallback( process_result, result)
d.addErrback(got_error)
return d
if isinstance(item,defer.Deferred):
item.addCallback(proceed)
return item
else:
return proceed(item)
if __name__ == '__main__':
from coherence.base import Coherence
def main():
def got_result(result):
print "got_result"
def call_browse(ObjectID=0,StartingIndex=0,RequestedCount=0):
r = f.backend.upnp_Browse(BrowseFlag='BrowseDirectChildren',
RequestedCount=RequestedCount,
StartingIndex=StartingIndex,
ObjectID=ObjectID,
SortCriteria='*',
Filter='')
r.addCallback(got_result)
r.addErrback(got_result)
def call_test(start,count):
r = f.backend.ampache_query_artists(start,count)
r.addCallback(got_result)
r.addErrback(got_result)
config = {}
config['logmode'] = 'warning'
c = Coherence(config)
f = c.add_plugin('AmpacheStore',
url='http://localhost/ampache/server/xml.server.php',
key='password',
user=None)
reactor.callLater(3, call_browse, 0, 0, 0)
#reactor.callLater(3, call_browse, AUDIO_ALL_CONTAINER_ID, 0, 0)
#reactor.callLater(3, call_browse, AUDIO_ARTIST_CONTAINER_ID, 0, 10)
#reactor.callLater(3, call_browse, AUDIO_ALBUM_CONTAINER_ID, 0, 10)
#reactor.callLater(3, call_test, 0, 10)
reactor.callWhenRunning(main)
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | misc~Rhythmbox-Plugin~upnp_coherence~__init__.py | # -*- Mode: python; coding: utf-8; tab-width: 8; indent-tabs-mode: t; -*-
#
# Copyright 2011, Caleb Callaway <[email protected]>
# Copyright 2008-2010, Frank Scholz <[email protected]>
# Copyright 2008, James Livingston <[email protected]>
#
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
import rhythmdb, rb
import gobject
gobject.threads_init()
import gconf
import coherence.extern.louie as louie
from coherence import log
from CoherenceDBEntryType import CoherenceDBEntryType
# for the icon
import os.path, urllib, gio, gtk.gdk
# the gconf configuration
gconf_keys = {
'port': "/apps/rhythmbox/plugins/coherence/port",
'interface': "/apps/rhythmbox/plugins/coherence/interface",
# DMS
'dms_uuid': "/apps/rhythmbox/plugins/coherence/dms/uuid",
'dms_active': "/apps/rhythmbox/plugins/coherence/dms/active",
'dms_version': "/apps/rhythmbox/plugins/coherence/dms/version",
'dms_name': "/apps/rhythmbox/plugins/coherence/dms/name",
# DMR
'dmr_uuid': "/apps/rhythmbox/plugins/coherence/dmr/uuid",
'dmr_active': "/apps/rhythmbox/plugins/coherence/dmr/active",
'dmr_version': "/apps/rhythmbox/plugins/coherence/dmr/version",
'dmr_name': "/apps/rhythmbox/plugins/coherence/dmr/name",
# DMC
'dmc_active': "/apps/rhythmbox/plugins/coherence/dmc/active",
}
class CoherencePlugin(rb.Plugin, log.Loggable):
logCategory = 'rb_coherence_plugin'
def __init__(self):
rb.Plugin.__init__(self)
self.coherence = None
self.config = gconf.client_get_default()
if self.config.get(gconf_keys['dmc_active']) is None:
# key not yet found represented by "None"
self._set_defaults()
def _set_defaults(self):
for a in ('r', 's'):
self.config.set_bool(gconf_keys['dm%s_active' % a], True)
self.config.set_int(gconf_keys['dm%s_version' % a], 2)
self.config.set_string(gconf_keys['dmr_name'], "Rhythmbox UPnP MediaRenderer on {host}")
self.config.set_string(gconf_keys['dms_name'], "Rhythmbox UPnP MediaServer on {host}")
self.config.set_bool(gconf_keys['dmc_active'], True)
def activate(self, shell):
from twisted.internet import gtk2reactor
try:
gtk2reactor.install()
except AssertionError, e:
# sometimes it's already installed
self.warning("gtk2reactor already installed %r" % e)
self.coherence = self.get_coherence()
if self.coherence is None:
self.warning("Coherence is not installed or too old, aborting")
return
self.warning("Coherence UPnP plugin activated")
self.shell = shell
self.sources = {}
# Set up our icon
the_icon = None
face_path = os.path.join(os.path.expanduser('~'), ".face")
if os.path.exists(face_path):
file = gio.File(path=face_path);
url = file.get_uri();
info = file.query_info("standard::fast-content-type");
mimetype = info.get_attribute_as_string("standard::fast-content-type");
pixbuf = gtk.gdk.pixbuf_new_from_file(face_path)
width = "%s" % pixbuf.get_width()
height = "%s" % pixbuf.get_height()
depth = '24'
the_icon = {
'url': url,
'mimetype': mimetype,
'width': width,
'height': height,
'depth': depth
}
if self.config.get_bool(gconf_keys['dms_active']):
# create our own media server
from coherence.upnp.devices.media_server import MediaServer
from MediaStore import MediaStore
kwargs = {
'version': self.config.get_int(gconf_keys['dms_version']),
'no_thread_needed': True,
'db': self.shell.props.db,
'plugin': self}
if the_icon:
kwargs['icon'] = the_icon
dms_uuid = self.config.get_string(gconf_keys['dms_uuid'])
if dms_uuid:
kwargs['uuid'] = dms_uuid
name = self.config.get_string(gconf_keys['dms_name'])
if name:
name = name.replace('{host}',self.coherence.hostname)
kwargs['name'] = name
self.server = MediaServer(self.coherence, MediaStore, **kwargs)
if dms_uuid is None:
self.config.set_string(gconf_keys['dms_uuid'], str(self.server.uuid))
self.warning("Media Store available with UUID %s" % str(self.server.uuid))
if self.config.get_bool(gconf_keys['dmr_active']):
# create our own media renderer
# but only if we have a matching Coherence package installed
if self.coherence_version < (0, 5, 2):
print "activation failed. Coherence is older than version 0.5.2"
else:
from coherence.upnp.devices.media_renderer import MediaRenderer
from MediaPlayer import RhythmboxPlayer
kwargs = {
"version": self.config.get_int(gconf_keys['dmr_version']),
"no_thread_needed": True,
"shell": self.shell,
'dmr_uuid': gconf_keys['dmr_uuid']
}
if the_icon:
kwargs['icon'] = the_icon
dmr_uuid = self.config.get_string(gconf_keys['dmr_uuid'])
if dmr_uuid:
kwargs['uuid'] = dmr_uuid
name = self.config.get_string(gconf_keys['dmr_name'])
if name:
name = name.replace('{host}',self.coherence.hostname)
kwargs['name'] = name
self.renderer = MediaRenderer(self.coherence,
RhythmboxPlayer, **kwargs)
if dmr_uuid is None:
self.config.set_string(gconf_keys['dmr_uuid'], str(self.renderer.uuid))
self.warning("Media Renderer available with UUID %s" % str(self.renderer.uuid))
if self.config.get_bool(gconf_keys['dmc_active']):
self.warning("start looking for media servers")
# watch for media servers
louie.connect(self.detected_media_server,
'Coherence.UPnP.ControlPoint.MediaServer.detected',
louie.Any)
louie.connect(self.removed_media_server,
'Coherence.UPnP.ControlPoint.MediaServer.removed',
louie.Any)
def deactivate(self, shell):
self.info("Coherence UPnP plugin deactivated")
if self.coherence is None:
return
self.coherence.shutdown()
try:
louie.disconnect(self.detected_media_server,
'Coherence.UPnP.ControlPoint.MediaServer.detected',
louie.Any)
except louie.error.DispatcherKeyError:
pass
try:
louie.disconnect(self.removed_media_server,
'Coherence.UPnP.ControlPoint.MediaServer.removed',
louie.Any)
except louie.error.DispatcherKeyError:
pass
del self.shell
del self.coherence
for usn, source in self.sources.iteritems():
source.delete_thyself()
del self.sources
# uninstall twisted reactor? probably not, since other things may have used it
def get_coherence (self):
coherence_instance = None
required_version = (0, 5, 7)
try:
from coherence.base import Coherence
from coherence import __version_info__
except ImportError, e:
print "Coherence not found"
return None
if __version_info__ < required_version:
required = '.'.join([str(i) for i in required_version])
found = '.'.join([str(i) for i in __version_info__])
print "Coherence %s required. %s found. Please upgrade" % (required, found)
return None
self.coherence_version = __version_info__
coherence_config = {
#'logmode': 'info',
'controlpoint': 'yes',
'plugins': {},
}
serverport = self.config.get_int(gconf_keys['port'])
if serverport:
coherence_config['serverport'] = serverport
interface = self.config.get_string(gconf_keys['interface'])
if interface:
coherence_config['interface'] = interface
coherence_instance = Coherence(coherence_config)
return coherence_instance
def removed_media_server(self, udn):
self.info("upnp server went away %s" % udn)
if self.sources.has_key(udn):
self.sources[udn].delete_thyself()
del self.sources[udn]
def detected_media_server(self, client, udn):
self.info("found upnp server %s (%s)" % (client.device.get_friendly_name(), udn))
""" don't react on our own MediaServer"""
if hasattr(self, 'server') and client.device.get_id() == str(self.server.uuid):
return
db = self.shell.props.db
group = rb.rb_display_page_group_get_by_id ("shared")
entry_type = CoherenceDBEntryType(client.device.get_id()[5:])
db.register_entry_type(entry_type)
from UpnpSource import UpnpSource
source = gobject.new (UpnpSource,
shell=self.shell,
entry_type=entry_type,
plugin=self,
client=client,
udn=udn)
self.sources[udn] = source
self.shell.append_display_page (source, group)
def create_configure_dialog(self, dialog=None):
if dialog is None:
def store_config(dialog,port_spinner,interface_entry,
dms_check,dms_name_entry,dms_version_entry,dms_uuid_entry,
dmr_check,dmr_name_entry,dmr_version_entry,dmr_uuid_entry,
dmc_check):
port = port_spinner.get_value_as_int()
self.config.set_int(gconf_keys['port'],port)
interface = interface_entry.get_text()
if len(interface) != 0:
self.config.set_string(gconf_keys['interface'],interface)
self.config.set_bool(gconf_keys['dms_active'],dms_check.get_active())
self.config.set_string(gconf_keys['dms_name'],dms_name_entry.get_text())
self.config.set_int(gconf_keys['dms_version'],int(dms_version_entry.get_active_text()))
self.config.set_string(gconf_keys['dms_uuid'],dms_uuid_entry.get_text())
self.config.set_bool(gconf_keys['dmr_active'],dmr_check.get_active())
self.config.set_string(gconf_keys['dmr_name'],dmr_name_entry.get_text())
self.config.set_int(gconf_keys['dmr_version'],int(dmr_version_entry.get_active_text()))
self.config.set_string(gconf_keys['dmr_uuid'],dmr_uuid_entry.get_text())
self.config.set_bool(gconf_keys['dmc_active'],dmc_check.get_active())
dialog.hide()
dialog = gtk.Dialog(title='DLNA/UPnP Configuration',
parent=None,flags=0,buttons=None)
dialog.set_default_size(500,350)
table = gtk.Table(rows=2, columns=2, homogeneous=False)
dialog.vbox.pack_start(table, False, False, 0)
label = gtk.Label("Network Interface:")
label.set_alignment(0,0.5)
table.attach(label, 0, 1, 0, 1)
interface_entry = gtk.Entry()
interface_entry.set_max_length(16)
if self.config.get_string(gconf_keys['interface']) != None:
interface_entry.set_text(self.config.get_string(gconf_keys['interface']))
else:
interface_entry.set_text('')
table.attach(interface_entry, 1, 2, 0, 1,
xoptions=gtk.FILL|gtk.EXPAND,yoptions=gtk.FILL|gtk.EXPAND,xpadding=5,ypadding=5)
label = gtk.Label("Port:")
label.set_alignment(0,0.5)
table.attach(label, 0, 1, 1, 2)
value = 0
if self.config.get_int(gconf_keys['port']) != None:
value = self.config.get_int(gconf_keys['port'])
adj = gtk.Adjustment(value, 0, 65535, 1, 100, 0)
port_spinner = gtk.SpinButton(adj, 0, 0)
port_spinner.set_wrap(True)
port_spinner.set_numeric(True)
table.attach(port_spinner, 1, 2, 1, 2,
xoptions=gtk.FILL|gtk.EXPAND,yoptions=gtk.FILL|gtk.EXPAND,xpadding=5,ypadding=5)
frame = gtk.Frame('MediaServer')
dialog.vbox.add(frame)
vbox = gtk.VBox(False, 0)
vbox.set_border_width(5)
frame.add(vbox)
table = gtk.Table(rows=4, columns=2, homogeneous=True)
vbox.pack_start(table, False, False, 0)
label = gtk.Label("enabled:")
label.set_alignment(0,0.5)
table.attach(label, 0, 1, 0, 1)
dms_check = gtk.CheckButton()
dms_check.set_active(self.config.get_bool(gconf_keys['dms_active']))
table.attach(dms_check, 1, 2, 0, 1)
label = gtk.Label("Name:")
label.set_alignment(0,0.5)
table.attach(label, 0, 1, 1, 2)
dms_name_entry = gtk.Entry()
if self.config.get_string(gconf_keys['dms_name']) != None:
dms_name_entry.set_text(self.config.get_string(gconf_keys['dms_name']))
else:
dms_name_entry.set_text('')
table.attach(dms_name_entry, 1, 2, 1, 2)
label = gtk.Label("UPnP version:")
label.set_alignment(0,0.5)
table.attach(label, 0, 1, 3, 4)
dms_version_entry = gtk.combo_box_new_text()
dms_version_entry.insert_text(0,'2')
dms_version_entry.insert_text(1,'1')
dms_version_entry.set_active(0)
if self.config.get_int(gconf_keys['dms_version']) != None:
if self.config.get_int(gconf_keys['dms_version']) == 1:
dms_version_entry.set_active(1)
table.attach(dms_version_entry, 1, 2, 3, 4)
label = gtk.Label("UUID:")
label.set_alignment(0,0.5)
table.attach(label, 0, 1, 2, 3)
dms_uuid_entry = gtk.Entry()
if self.config.get_string(gconf_keys['dms_uuid']) != None:
dms_uuid_entry.set_text(self.config.get_string(gconf_keys['dms_uuid']))
else:
dms_uuid_entry.set_text('')
table.attach(dms_uuid_entry, 1, 2, 2, 3)
frame = gtk.Frame('MediaRenderer')
dialog.vbox.add(frame)
vbox = gtk.VBox(False, 0)
vbox.set_border_width(5)
frame.add(vbox)
table = gtk.Table(rows=4, columns=2, homogeneous=True)
vbox.pack_start(table, False, False, 0)
label = gtk.Label("enabled:")
label.set_alignment(0,0.5)
table.attach(label, 0, 1, 0, 1)
dmr_check = gtk.CheckButton()
dmr_check.set_active(self.config.get_bool(gconf_keys['dmr_active']))
table.attach(dmr_check, 1, 2, 0, 1)
label = gtk.Label("Name:")
label.set_alignment(0,0.5)
table.attach(label, 0, 1, 1, 2)
dmr_name_entry = gtk.Entry()
if self.config.get_string(gconf_keys['dmr_name']) != None:
dmr_name_entry.set_text(self.config.get_string(gconf_keys['dmr_name']))
else:
dmr_name_entry.set_text('')
table.attach(dmr_name_entry, 1, 2, 1, 2)
label = gtk.Label("UPnP version:")
label.set_alignment(0,0.5)
table.attach(label, 0, 1, 3, 4)
dmr_version_entry = gtk.combo_box_new_text()
dmr_version_entry.insert_text(0,'2')
dmr_version_entry.insert_text(1,'1')
dmr_version_entry.set_active(0)
if self.config.get_int(gconf_keys['dmr_version']) != None:
if self.config.get_int(gconf_keys['dmr_version']) == 1:
dmr_version_entry.set_active(1)
table.attach(dmr_version_entry, 1, 2, 3, 4)
label = gtk.Label("UUID:")
label.set_alignment(0,0.5)
table.attach(label, 0, 1, 2, 3)
dmr_uuid_entry = gtk.Entry()
if self.config.get_string(gconf_keys['dmr_uuid']) != None:
dmr_uuid_entry.set_text(self.config.get_string(gconf_keys['dmr_uuid']))
else:
dmr_uuid_entry.set_text('')
table.attach(dmr_uuid_entry, 1, 2, 2, 3)
frame = gtk.Frame('MediaClient')
dialog.vbox.add(frame)
vbox = gtk.VBox(False, 0)
vbox.set_border_width(5)
frame.add(vbox)
table = gtk.Table(rows=1, columns=2, homogeneous=True)
vbox.pack_start(table, False, False, 0)
label = gtk.Label("enabled:")
label.set_alignment(0,0.5)
table.attach(label, 0, 1, 0, 1)
dmc_check = gtk.CheckButton()
dmc_check.set_active(self.config.get_bool(gconf_keys['dmc_active']))
table.attach(dmc_check, 1, 2, 0, 1)
button = gtk.Button(stock=gtk.STOCK_CANCEL)
dialog.action_area.pack_start(button, True, True, 5)
button.connect("clicked", lambda w: dialog.hide())
button = gtk.Button(stock=gtk.STOCK_OK)
button.connect("clicked", lambda w: store_config(dialog,port_spinner,interface_entry,
dms_check,dms_name_entry,dms_version_entry,dms_uuid_entry,
dmr_check,dmr_name_entry,dmr_version_entry,dmr_uuid_entry,
dmc_check))
dialog.action_area.pack_start(button, True, True, 5)
dialog.show_all()
dialog.present()
return dialog
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~base.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006,2007,2008 Frank Scholz <[email protected]>
import string
import socket
import os, sys
import traceback
import copy
from twisted.python import filepath, util
from twisted.internet.tcp import CannotListenError
from twisted.internet import task, address, defer
from twisted.internet import reactor
from twisted.web import resource,static
import coherence.extern.louie as louie
from coherence import __version__
from coherence import log
from coherence.upnp.core.ssdp import SSDPServer
from coherence.upnp.core.msearch import MSearch
from coherence.upnp.core.device import Device, RootDevice
from coherence.upnp.core.utils import parse_xml, get_ip_address, get_host_address
from coherence.upnp.core.utils import Site
from coherence.upnp.devices.control_point import ControlPoint
from coherence.upnp.devices.media_server import MediaServer
from coherence.upnp.devices.media_renderer import MediaRenderer
from coherence.upnp.devices.binary_light import BinaryLight
from coherence.upnp.devices.dimmable_light import DimmableLight
try:
import pkg_resources
except ImportError:
pkg_resources = None
class SimpleRoot(resource.Resource, log.Loggable):
addSlash = True
logCategory = 'coherence'
def __init__(self, coherence):
resource.Resource.__init__(self)
self.coherence = coherence
self.http_hostname = '%s:%d' % (self.coherence.hostname, self.coherence.web_server_port)
def getChild(self, name, request):
self.debug('SimpleRoot getChild %s, %s' % (name, request))
if name == 'oob':
""" we have an out-of-band request """
return static.File(self.coherence.dbus.pinboard[request.args['key'][0]])
if name == '':
return self
# at this stage, name should be a device UUID
try:
return self.coherence.children[name]
except:
self.warning("Cannot find device for requested name:", name)
request.setResponseCode(404)
return static.Data('<html><p>No device for requested UUID: %s</p></html>' % name,'text/html')
def listchilds(self, uri):
self.info('listchilds %s' % uri)
if uri[-1] != '/':
uri += '/'
cl = []
for child in self.coherence.children:
device = self.coherence.get_device_with_id(child)
if device is not None:
cl.append('<li><a href=%s%s>%s:%s %s</a></li>' % (
uri, child, device.get_friendly_device_type(),
device.get_device_type_version(),
device.get_friendly_name()))
for child in self.children:
cl.append('<li><a href=%s%s>%s</a></li>' % (uri, child, child))
return "".join(cl)
def render(self,request):
result = """<html><head><title>Coherence</title></head><body>
<a href="http://coherence.beebits.net">Coherence</a> - a Python DLNA/UPnP framework for the Digital Living<p>Hosting:<ul>%s</ul></p></body></html>""" % self.listchilds(request.uri)
return result.encode('utf-8')
class WebServer(log.Loggable):
logCategory = 'webserver'
def __init__(self, ui, port, coherence):
try:
if ui != 'yes':
""" use this to jump out here if we do not want
the web ui """
raise ImportError
self.warning("Web UI not supported atm, will return with version 0.7.0")
raise ImportError
from nevow import __version_info__, __version__
if __version_info__ <(0,9,17):
self.warning( "Nevow version %s too old, disabling WebUI" % __version__)
raise ImportError
from nevow import appserver, inevow
from coherence.web.ui import Web, IWeb, WebUI
from twisted.python.components import registerAdapter
def ResourceFactory( original):
return WebUI( IWeb, original)
registerAdapter(ResourceFactory, Web, inevow.IResource)
self.web_root_resource = Web(coherence)
self.site = appserver.NevowSite( self.web_root_resource)
except ImportError:
self.site = Site(SimpleRoot(coherence))
self.port = reactor.listenTCP( port, self.site, interface="::")
coherence.web_server_port = self.port._realPortNumber
# XXX: is this the right way to do it?
self.warning( "WebServer on port %d ready" % coherence.web_server_port)
class Plugins(log.Loggable):
logCategory = 'plugins'
_instance_ = None # Singleton
_valids = ("coherence.plugins.backend.media_server",
"coherence.plugins.backend.media_renderer",
"coherence.plugins.backend.binary_light",
"coherence.plugins.backend.dimmable_light")
_plugins = {}
def __new__(cls, *args, **kwargs):
obj = getattr(cls, '_instance_', None)
if obj is not None:
return obj
else:
obj = super(Plugins, cls).__new__(cls, *args, **kwargs)
cls._instance_ = obj
obj._collect(*args, **kwargs)
return obj
def __repr__(self):
return str(self._plugins)
def __init__(self, *args, **kwargs):
pass
def __getitem__(self, key):
plugin = self._plugins.__getitem__(key)
if pkg_resources and isinstance(plugin, pkg_resources.EntryPoint):
try:
plugin = plugin.load(require=False)
except (ImportError, AttributeError, pkg_resources.ResolutionError), msg:
self.warning("Can't load plugin %s (%s), maybe missing dependencies..." % (plugin.name,msg))
self.info(traceback.format_exc())
del self._plugins[key]
raise KeyError
else:
self._plugins[key] = plugin
return plugin
def get(self, key,default=None):
try:
return self.__getitem__(key)
except KeyError:
return default
def __setitem__(self, key, value):
self._plugins.__setitem__(key,value)
def set(self, key,value):
return self.__setitem__(key,value)
def keys(self):
return self._plugins.keys()
def _collect(self, ids=_valids):
if not isinstance(ids, (list,tuple)):
ids = (ids,)
if pkg_resources:
for group in ids:
for entrypoint in pkg_resources.iter_entry_points(group):
# set a placeholder for lazy loading
self._plugins[entrypoint.name] = entrypoint
else:
self.info("no pkg_resources, fallback to simple plugin handling")
if len(self._plugins) == 0:
self._collect_from_module()
def _collect_from_module(self):
from coherence.extern.simple_plugin import Reception
reception = Reception(os.path.join(os.path.dirname(__file__),'backends'), log=self.warning)
self.info(reception.guestlist())
for cls in reception.guestlist():
self._plugins[cls.__name__.split('.')[-1]] = cls
class Coherence(log.Loggable):
logCategory = 'coherence'
_instance_ = None # Singleton
def __new__(cls, *args, **kwargs):
obj = getattr(cls, '_instance_', None)
if obj is not None:
cls._incarnations_ += 1
return obj
else:
obj = super(Coherence, cls).__new__(cls)
cls._instance_ = obj
cls._incarnations_ = 1
obj.setup(*args, **kwargs)
obj.cls = cls
return obj
def __init__(self, *args, **kwargs):
pass
def clear(self):
""" we do need this to survive multiple calls
to Coherence during trial tests
"""
self.cls._instance_ = None
def setup(self, config={}):
self.mirabeau = None
self.devices = []
self.children = {}
self._callbacks = {}
self.active_backends = {}
self.dbus = None
self.config = config
self.ctrl = None
network_if = config.get('interface')
self.web_server_port = int(config.get('serverport', 0))
""" initializes logsystem
a COHERENCE_DEBUG environment variable overwrites
all level settings here
"""
try:
logmode = config.get('logging').get('level','warning')
except (KeyError,AttributeError):
logmode = config.get('logmode', 'warning')
_debug = []
try:
subsystems = config.get('logging')['subsystem']
if isinstance(subsystems,dict):
subsystems = [subsystems]
for subsystem in subsystems:
try:
if subsystem['active'] == 'no':
continue
except (KeyError,TypeError):
pass
self.info( "setting log-level for subsystem %s to %s" % (subsystem['name'],subsystem['level']))
_debug.append('%s:%d' % (subsystem['name'].lower(), log.human2level(subsystem['level'])))
except (KeyError,TypeError):
subsystem_log = config.get('subsystem_log',{})
for subsystem,level in subsystem_log.items():
#self.info( "setting log-level for subsystem %s to %s" % (subsystem,level))
_debug.append('%s:%d' % (subsystem.lower(), log.human2level(level)))
if len(_debug) > 0:
_debug = ','.join(_debug)
else:
_debug = '*:%d' % log.human2level(logmode)
try:
logfile = config.get('logging').get('logfile',None)
if logfile != None:
logfile = unicode(logfile)
except (KeyError,AttributeError,TypeError):
logfile = config.get('logfile', None)
log.init(logfile, _debug)
self.warning("Coherence UPnP framework version %s starting..." % __version__)
if network_if:
self.hostname = get_ip_address('%s' % network_if)
else:
try:
self.hostname = socket.gethostbyname(socket.gethostname())
except socket.gaierror:
self.warning("hostname can't be resolved, maybe a system misconfiguration?")
self.hostname = '127.0.0.1'
if self.hostname.startswith('127.'):
""" use interface detection via routing table as last resort """
def catch_result(hostname):
self.hostname = hostname
self.setup_part2()
d = defer.maybeDeferred(get_host_address)
d.addCallback(catch_result)
else:
self.setup_part2()
def setup_part2(self):
self.info('running on host: %s' % self.hostname)
if self.hostname.startswith('127.'):
self.warning('detection of own ip failed, using %s as own address, functionality will be limited', self.hostname)
unittest = self.config.get('unittest', 'no')
if unittest == 'no':
unittest = False
else:
unittest = True
self.ssdp_server = SSDPServer(test=unittest,interface=self.hostname)
louie.connect( self.create_device, 'Coherence.UPnP.SSDP.new_device', louie.Any)
louie.connect( self.remove_device, 'Coherence.UPnP.SSDP.removed_device', louie.Any)
louie.connect( self.add_device, 'Coherence.UPnP.RootDevice.detection_completed', louie.Any)
#louie.connect( self.receiver, 'Coherence.UPnP.Service.detection_completed', louie.Any)
self.ssdp_server.subscribe("new_device", self.add_device)
self.ssdp_server.subscribe("removed_device", self.remove_device)
self.msearch = MSearch(self.ssdp_server,test=unittest)
self.msearch6 = MSearch(self.ssdp_server,ipv6=True,test=unittest)
reactor.addSystemEventTrigger( 'before', 'shutdown', self.shutdown, force=True)
try:
self.web_server = WebServer( self.config.get('web-ui',None), self.web_server_port, self)
except CannotListenError:
self.warning('port %r already in use, aborting!' % self.web_server_port)
reactor.stop()
return
self.urlbase = 'http://%s:%d/' % (self.hostname, self.web_server_port)
#self.renew_service_subscription_loop = task.LoopingCall(self.check_devices)
#self.renew_service_subscription_loop.start(20.0, now=False)
self.available_plugins = None
try:
plugins = self.config['plugin']
if isinstance(plugins,dict):
plugins=[plugins]
except:
plugins = None
if plugins is None:
plugins = self.config.get('plugins',None)
if plugins is None:
self.info("No plugin defined!")
else:
if isinstance(plugins,dict):
for plugin,arguments in plugins.items():
try:
if not isinstance(arguments, dict):
arguments = {}
self.add_plugin(plugin, **arguments)
except Exception, msg:
self.warning("Can't enable plugin, %s: %s!" % (plugin, msg))
self.info(traceback.format_exc())
else:
for plugin in plugins:
try:
if plugin['active'] == 'no':
continue
except (KeyError,TypeError):
pass
try:
backend = plugin['backend']
arguments = copy.copy(plugin)
del arguments['backend']
backend = self.add_plugin(backend, **arguments)
if self.writeable_config() == True:
if 'uuid' not in plugin:
plugin['uuid'] = str(backend.uuid)[5:]
self.config.save()
except Exception, msg:
self.warning("Can't enable plugin, %s: %s!" % (plugin, msg))
self.info(traceback.format_exc())
self.external_address = ':'.join((self.hostname,str(self.web_server_port)))
if(self.config.get('controlpoint', 'no') == 'yes' or
self.config.get('json','no') == 'yes'):
self.ctrl = ControlPoint(self)
if self.config.get('json','no') == 'yes':
from coherence.json import JsonInterface
self.json = JsonInterface(self.ctrl)
if self.config.get('transcoding', 'no') == 'yes':
from coherence.transcoder import TranscoderManager
self.transcoder_manager = TranscoderManager(self)
self.dbus = None
if self.config.get('use_dbus', 'no') == 'yes':
try:
from coherence import dbus_service
if self.ctrl == None:
self.ctrl = ControlPoint(self)
self.ctrl.auto_client_append('InternetGatewayDevice')
self.dbus = dbus_service.DBusPontoon(self.ctrl)
except Exception, msg:
self.warning("Unable to activate dbus sub-system: %r" % msg)
self.debug(traceback.format_exc())
else:
if self.config.get('enable_mirabeau', 'no') == 'yes':
from coherence import mirabeau
from coherence.tube_service import MirabeauProxy
mirabeau_cfg = self.config.get('mirabeau', {})
self.mirabeau = mirabeau.Mirabeau(mirabeau_cfg, self)
self.add_web_resource('mirabeau', MirabeauProxy())
self.mirabeau.start()
def add_plugin(self, plugin, **kwargs):
self.info("adding plugin %r", plugin)
self.available_plugins = Plugins()
try:
plugin_class = self.available_plugins.get(plugin,None)
if plugin_class == None:
raise KeyError
for device in plugin_class.implements:
try:
device_class=globals().get(device,None)
if device_class == None:
raise KeyError
self.info("Activating %s plugin as %s..." % (plugin, device))
new_backend = device_class(self, plugin_class, **kwargs)
self.active_backends[str(new_backend.uuid)] = new_backend
return new_backend
except KeyError:
self.warning("Can't enable %s plugin, sub-system %s not found!" % (plugin, device))
except Exception, msg:
self.warning("Can't enable %s plugin for sub-system %s, %s!" % (plugin, device, msg))
self.debug(traceback.format_exc())
except KeyError, error:
self.warning("Can't enable %s plugin, not found!" % plugin)
except Exception, msg:
self.warning("Can't enable %s plugin, %s!" % (plugin, msg))
self.debug(traceback.format_exc())
def remove_plugin(self, plugin):
""" removes a backend from Coherence """
""" plugin is the object return by add_plugin """
""" or an UUID string """
if isinstance(plugin,basestring):
try:
plugin = self.active_backends[plugin]
except KeyError:
self.warning("no backend with the uuid %r found" % plugin)
return ""
try:
del self.active_backends[str(plugin.uuid)]
self.info("removing plugin %r", plugin)
plugin.unregister()
return plugin.uuid
except KeyError:
self.warning("no backend with the uuid %r found" % plugin.uuid)
return ""
def writeable_config(self):
""" do we have a new-style config file """
from coherence.extern.simple_config import ConfigItem
if isinstance(self.config,ConfigItem):
return True
return False
def store_plugin_config(self,uuid,items):
""" find the backend with uuid
and store in its the config
the key and value pair(s)
"""
plugins = self.config.get('plugin')
if plugins is None:
self.warning("storing a plugin config option is only possible with the new config file format")
return
if isinstance(plugins,dict):
plugins = [plugins]
uuid = str(uuid)
if uuid.startswith('uuid:'):
uuid = uuid[5:]
if isinstance(items,tuple):
new = {}
new[items[0]] = items[1]
for plugin in plugins:
try:
if plugin['uuid'] == uuid:
for k,v in items.items():
plugin[k] = v
self.config.save()
except:
pass
else:
self.info("storing plugin config option for %s failed, plugin not found" % uuid)
def receiver( self, signal, *args, **kwargs):
#print "Coherence receiver called with", signal
#print kwargs
pass
def shutdown( self,force=False):
if force == True:
self._incarnations_ = 1
if self._incarnations_ > 1:
self._incarnations_ -= 1
return
def _shutdown():
self.mirabeau = None
if self.dbus:
self.dbus.shutdown()
self.dbus = None
for backend in self.active_backends.itervalues():
backend.unregister()
self.active_backends = {}
""" send service unsubscribe messages """
def _shutdownMSearch(msearch):
if hasattr(msearch, 'double_discover_loop'):
msearch.double_discover_loop.stop()
if hasattr(msearch, 'port'):
msearch.port.stopListening()
try:
if self.web_server.port != None:
self.web_server.port.stopListening()
self.web_server.port = None
if hasattr(self.ssdp_server, 'resend_notify_loop'):
self.ssdp_server.resend_notify_loop.stop()
if hasattr(self.ssdp_server, 'port'):
self.ssdp_server.port.stopListening()
_shutdownMSearch(self.msearch)
_shutdownMSearch(self.msearch6)
#self.renew_service_subscription_loop.stop()
except:
pass
l = []
for root_device in self.get_devices():
for device in root_device.get_devices():
d = device.unsubscribe_service_subscriptions()
d.addCallback(device.remove)
l.append(d)
d = root_device.unsubscribe_service_subscriptions()
d.addCallback(root_device.remove)
l.append(d)
def homecleanup(result):
"""anything left over"""
louie.disconnect( self.create_device, 'Coherence.UPnP.SSDP.new_device', louie.Any)
louie.disconnect( self.remove_device, 'Coherence.UPnP.SSDP.removed_device', louie.Any)
louie.disconnect( self.add_device, 'Coherence.UPnP.RootDevice.detection_completed', louie.Any)
self.ssdp_server.shutdown()
if self.ctrl:
self.ctrl.shutdown()
self.warning('Coherence UPnP framework shutdown')
return result
dl = defer.DeferredList(l)
dl.addCallback(homecleanup)
return dl
if self.mirabeau is not None:
d = defer.maybeDeferred(self.mirabeau.stop)
d.addBoth(lambda x: _shutdown())
return d
else:
return _shutdown()
def check_devices(self):
""" iterate over devices and their embedded ones and renew subscriptions """
for root_device in self.get_devices():
root_device.renew_service_subscriptions()
for device in root_device.get_devices():
device.renew_service_subscriptions()
def subscribe(self, name, callback):
self._callbacks.setdefault(name,[]).append(callback)
def unsubscribe(self, name, callback):
callbacks = self._callbacks.get(name,[])
if callback in callbacks:
callbacks.remove(callback)
self._callbacks[name] = callbacks
def callback(self, name, *args):
for callback in self._callbacks.get(name,[]):
callback(*args)
def get_device_by_host(self, host):
found = []
for device in self.devices:
if device.get_host() == host:
found.append(device)
return found
def get_device_with_usn(self, usn):
found = None
for device in self.devices:
if device.get_usn() == usn:
found = device
break
return found
def get_device_with_id(self, device_id):
found = None
for device in self.devices:
id = device.get_id()
if device_id[:5] != 'uuid:':
id = id[5:]
if id == device_id:
found = device
break
return found
def get_devices(self):
return self.devices
def get_local_devices(self):
return [d for d in self.devices if d.manifestation == 'local']
def get_nonlocal_devices(self):
return [d for d in self.devices if d.manifestation == 'remote']
def create_device(self, device_type, infos):
self.info("creating ", infos['ST'],infos['USN'])
if infos['ST'] == 'upnp:rootdevice':
self.info("creating upnp:rootdevice ", infos['USN'])
root = RootDevice(infos)
else:
self.info("creating device/service ",infos['USN'])
root_id = infos['USN'][:-len(infos['ST'])-2]
root = self.get_device_with_id(root_id)
device = Device(parent=root)
# fire this only after the device detection is fully completed
# and we are on the device level already, so we can work with them instead with the SSDP announce
#if infos['ST'] == 'upnp:rootdevice':
# self.callback("new_device", infos['ST'], infos)
def add_device(self, device):
self.info("adding device",device.get_id(),device.get_usn(),device.friendly_device_type)
self.devices.append(device)
def remove_device(self, device_type, infos):
self.info("removed device",infos['ST'],infos['USN'])
device = self.get_device_with_usn(infos['USN'])
if device:
louie.send('Coherence.UPnP.Device.removed', None, usn=infos['USN'])
self.devices.remove(device)
device.remove()
if infos['ST'] == 'upnp:rootdevice':
louie.send('Coherence.UPnP.RootDevice.removed', None, usn=infos['USN'])
self.callback("removed_device", infos['ST'], infos['USN'])
def add_web_resource(self, name, sub):
self.children[name] = sub
def remove_web_resource(self, name):
try:
del self.children[name]
except KeyError:
""" probably the backend init failed """
pass
def connect(self,receiver,signal=louie.signal.All,sender=louie.sender.Any, weak=True):
""" wrapper method around louie.connect
"""
louie.connect(receiver,signal=signal,sender=sender,weak=weak)
def disconnect(self,receiver,signal=louie.signal.All,sender=louie.sender.Any, weak=True):
""" wrapper method around louie.disconnect
"""
louie.disconnect(receiver,signal=signal,sender=sender,weak=weak)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~services~servers~dimming_server.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
# Dimming service
from twisted.web import resource
from coherence.upnp.core.soap_service import UPnPPublisher
from coherence.upnp.core import service
from coherence import log
class DimmingControl(service.ServiceControl,UPnPPublisher):
def __init__(self, server):
self.service = server
self.variables = server.get_variables()
self.actions = server.get_actions()
class DimmingServer(service.ServiceServer, resource.Resource,
log.Loggable):
logCategory = 'dimming_server'
def __init__(self, device, backend=None):
self.device = device
if backend == None:
backend = self.device.backend
resource.Resource.__init__(self)
service.ServiceServer.__init__(self, 'Dimming', self.device.version, backend)
self.control = DimmingControl(self)
self.putChild(self.scpd_url, service.scpdXML(self, self.control))
self.putChild(self.control_url, self.control) | [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~core~variable.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006, Frank Scholz <[email protected]>
import time
from sets import Set
from coherence.upnp.core import utils
try:
#FIXME:
# there is some circular import, service imports variable, variable imports service
# how is this done properly?
#
from coherence.upnp.core import service
except ImportError:
import service
from coherence import log
import coherence.extern.louie as louie
class StateVariable(log.Loggable):
logCategory = 'variable'
def __init__(self, upnp_service, name, implementation, instance, send_events,
data_type, allowed_values):
self.service = upnp_service
self.name = name
self.implementation = implementation
self.instance = instance
self.send_events = utils.means_true(send_events)
self.never_evented = False
self.data_type = data_type
self.allowed_values = allowed_values
if self.allowed_values == None:
self.allowed_values = []
self.has_vendor_values = False
self.allowed_value_range = None
self.dependant_variable = None
self.default_value = ''
self.old_value = ''
self.value = ''
self.last_time_touched = None
self._callbacks = []
if isinstance( self.service, service.ServiceServer):
self.moderated = self.service.is_variable_moderated(name)
self.updated = False
def as_tuples(self):
r = []
r.append(('Name',self.name))
if self.send_events:
r.append(('Evented','yes'))
else:
r.append(('Evented','no'))
r.append(('Data Type',self.data_type))
r.append(('Default Value',self.default_value))
r.append(('Current Value',unicode(self.value)))
if(self.allowed_values != None and len(self.allowed_values) > 0):
r.append(('Allowed Values',','.join(self.allowed_values)))
return r
def set_default_value(self, value):
self.update(value)
self.default_value = self.value
def set_allowed_values(self, values):
if not isinstance(values,(list,tuple)):
values = [values]
self.allowed_values = values
def set_allowed_value_range(self, **kwargs):
self.allowed_value_range = kwargs
def get_allowed_values(self):
return self.allowed_values
def set_never_evented(self, value):
self.never_evented = utils.means_true(value)
def update(self, value):
self.info("variable check for update", self.name, value, self.service)
if not isinstance( self.service, service.Service):
if self.name == 'ContainerUpdateIDs':
old_value = self.value
if self.updated == True:
if isinstance( value, tuple):
v = old_value.split(',')
i = 0
while i < len(v):
if v[i] == str(value[0]):
del v[i:i+2]
old_value = ','.join(v)
break;
i += 2
if len(old_value):
new_value = old_value + ',' + str(value[0]) + ',' + str(value[1])
else:
new_value = str(value[0]) + ',' + str(value[1])
else:
if len(old_value):
new_value = str(old_value) + ',' + str(value)
else:
new_value = str(value)
else:
if isinstance( value, tuple):
new_value = str(value[0]) + ',' + str(value[1])
else:
new_value = value
else:
if self.data_type == 'string':
if isinstance(value,basestring):
value = value.split(',')
if(isinstance(value,tuple) or
isinstance(value,Set)):
value = list(value)
if not isinstance(value,list):
value = [value]
new_value = []
for v in value:
if type(v) == unicode:
v = v.encode('utf-8')
else:
v = str(v)
if len(self.allowed_values):
if self.has_vendor_values == True:
new_value.append(v)
elif v.upper() in [x.upper() for x in self.allowed_values]:
new_value.append(v)
else:
self.warning("Variable %s update, %r value %s doesn't fit in %r" % (self.name, self.has_vendor_values, v, self.allowed_values))
new_value = 'Coherence_Value_Error'
else:
new_value.append(v)
new_value = ','.join(new_value)
elif self.data_type == 'boolean':
new_value = utils.generalise_boolean(value)
elif self.data_type == 'bin.base64':
new_value = value
else:
new_value = int(value)
else:
if self.data_type == 'string':
if type(value) == unicode:
value = value.encode('utf-8')
else:
value = str(value)
if len(self.allowed_values):
if self.has_vendor_values == True:
new_value = value
elif value.upper() in [v.upper() for v in self.allowed_values]:
new_value = value
else:
self.warning("Variable %s NOT updated, value %s doesn't fit" % (self.name, value))
new_value = 'Coherence_Value_Error'
else:
new_value = value
elif self.data_type == 'boolean':
new_value = utils.generalise_boolean(value)
elif self.data_type == 'bin.base64':
new_value = value
else:
try:
new_value = int(value)
except ValueError:
new_value = 'Coherence_Value_Error'
if new_value == 'Coherence_Value_Error':
return
if new_value == self.value:
self.info("variable NOT updated, no value change", self.name, self.value)
return
self.old_value = self.value
self.value = new_value
self.last_time_touched = time.time()
#print "UPDATED %s %r %r %r %r %r" % (self.name,self.service,isinstance( self.service, service.Service),self.instance,self.value,self._callbacks)
self.notify()
if isinstance( self.service, service.Service):
#self.notify()
pass
else:
self.updated = True
if self.service.last_change != None:
self.service.last_change.updated = True
self.info("variable updated", self.name, self.value)
def subscribe(self, callback):
self._callbacks.append(callback)
callback( self)
def notify(self):
if self.name.startswith('A_ARG_TYPE_'):
return
self.info("Variable %s sends notify about new value >%r<" %(self.name, self.value))
#if self.old_value == '':
# return
louie.send(signal='Coherence.UPnP.StateVariable.%s.changed' % self.name, sender=self.service, variable=self)
louie.send(signal='Coherence.UPnP.StateVariable.changed',sender=self.service, variable=self)
#print "CALLBACKS %s %r %r" % (self.name,self.instance,self._callbacks)
for callback in self._callbacks:
callback(self)
def __repr__(self):
return "Variable: %s, %s, %d, %s, %s, %s, %s, %s, %s, %s" % \
(self.name,
str(self.service),
self.instance,
self.implementation,
self.data_type,
str(self.allowed_values),
str(self.default_value),
str(self.old_value),
str(self.value),
str(self.send_events))
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~mediadb_storage.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007,2008, Frank Scholz <[email protected]>
"""
MediaStore
A MediaServer with a database backend,
exposes its content in All, Albums and Artists containers.
Serves cover art with the Album object, and keeps references to
the MusicBrainz DB - http://musicbrainz.org/
Should not scan for files, but gets feeded
with proper tagged ones via some import tool
or/and allow imports via the web-UI.
depends on:
for the sqlite db handling:
Axiom - http://divmod.org/trac/wiki/DivmodAxiom
Epsilon - http://divmod.org/trac/wiki/DivmodEpsilon
for id3 tag extraction:
libmtag - http://code.google.com/p/libmtag/
taglib - http://developer.kde.org/~wheeler/taglib.html
or
pyid3lib - http://pyid3lib.sourceforge.net/doc.html
or
tagpy - http://news.tiker.net/software/tagpy
taglib - http://developer.kde.org/~wheeler/taglib.html
CoversByAmazon - https://coherence.beebits.net/browser/trunk/coherence/extern/covers_by_amazon.py
"""
import os, shutil
import string
import urllib
from urlparse import urlsplit
from axiom import store, item, attributes
from epsilon.extime import Time
import coherence.extern.louie as louie
from twisted.internet import reactor, defer
from twisted.python.filepath import FilePath
from coherence.upnp.core import DIDLLite
from coherence.extern.covers_by_amazon import CoverGetter
from coherence.backend import BackendItem, BackendStore
KNOWN_AUDIO_TYPES = {'.mp3':'audio/mpeg',
'.ogg':'application/ogg',
'.mpc':'audio/x-musepack',
'.flac':'audio/x-wavpack',
'.wv':'audio/x-wavpack',
'.m4a':'audio/mp4',}
def _dict_from_tags(tag):
tags = {}
tags['artist'] = tag.artist.strip()
tags['album'] = tag.album.strip()
tags['title'] = tag.title.strip()
if type(tag.track) == int:
tags['track'] = tag.track
elif type(tag.track) in (str, unicode):
tags['track'] = int(tag.track.strip())
else:
tags['track'] = tag.track[0]
for key in ('artist', 'album', 'title'):
value = tags.get(key, u'')
if isinstance(value, unicode):
tags[key] = value.encode('utf-8')
return tags
try:
import libmtag
def get_tags(filename):
audio_file = libmtag.File(filename)
tags = {}
tags['artist'] = audio_file.tag().get('artist').strip()
tags['album'] = audio_file.tag().get('album').strip()
tags['title'] = audio_file.tag().get('title').strip()
tags['track'] = audio_file.tag().get('track').strip()
return tags
except ImportError:
try:
import pyid3lib
def get_tags(filename):
audio_file = pyid3lib.tag(filename)
return _dict_from_tags(audio_file)
except ImportError:
try:
import tagpy
def get_tags(filename):
audio_file = tagpy.FileRef(filename)
return _dict_from_tags(audio_file.tag())
except ImportError:
get_tags = None
if not get_tags:
raise ImportError("we need some installed id3 tag library for this backend: python-tagpy, pyid3lib or libmtag")
MEDIA_DB = 'tests/media.db'
ROOT_CONTAINER_ID = 0
AUDIO_CONTAINER = 100
AUDIO_ALL_CONTAINER_ID = 101
AUDIO_ARTIST_CONTAINER_ID = 102
AUDIO_ALBUM_CONTAINER_ID = 103
def sanitize(filename):
badchars = ''.join(set(string.punctuation) - set('-_+.~'))
f = unicode(filename.lower())
for old, new in ((u'ä','ae'),(u'ö','oe'),(u'ü','ue'),(u'ß','ss')):
f = f.replace(unicode(old),unicode(new))
f = f.replace(badchars, '_')
return f
class Container(BackendItem):
get_path = None
def __init__(self, id, parent_id, name, children_callback=None,store=None,play_container=False):
self.id = id
self.parent_id = parent_id
self.name = name
self.mimetype = 'directory'
self.store = store
self.play_container = play_container
self.update_id = 0
if children_callback != None:
self.children = children_callback
else:
self.children = []
def add_child(self, child):
self.children.append(child)
def get_children(self,start=0,request_count=0):
if callable(self.children):
children = self.children()
else:
children = self.children
if request_count == 0:
return children[start:]
else:
return children[start:request_count]
def get_child_count(self):
if callable(self.children):
return len(self.children())
else:
return len(self.children)
def get_item(self):
item = DIDLLite.Container(self.id, self.parent_id,self.name)
item.childCount = self.get_child_count()
if self.store and self.play_container == True:
if item.childCount > 0:
res = DIDLLite.PlayContainerResource(self.store.server.uuid,cid=self.get_id(),fid=self.get_children()[0].get_id())
item.res.append(res)
return item
def get_name(self):
return self.name
def get_id(self):
return self.id
class Artist(item.Item,BackendItem):
""" definition for an artist """
schemaVersion = 1
typeName = 'artist'
mimetype = 'directory'
name = attributes.text(allowNone=False, indexed=True)
musicbrainz_id = attributes.text()
get_path = None
def get_artist_all_tracks(self,start=0,request_count=0):
children = [x[1] for x in list(self.store.query((Album,Track),
attributes.AND(Album.artist == self,
Track.album == Album.storeID),
sort=(Album.title.ascending,Track.track_nr.ascending)
))]
if request_count == 0:
return children[start:]
else:
return children[start:request_count]
def get_children(self,start=0,request_count=0):
all_id = 'artist_all_tracks_%d' % (self.storeID+1000)
self.store.containers[all_id] = \
Container( all_id, self.storeID+1000, 'All tracks of %s' % self.name,
children_callback=self.get_artist_all_tracks,
store=self.store,play_container=True)
children = [self.store.containers[all_id]] + list(self.store.query(Album, Album.artist == self,sort=Album.title.ascending))
if request_count == 0:
return children[start:]
else:
return children[start:request_count]
def get_child_count(self):
return len(list(self.store.query(Album, Album.artist == self))) + 1
def get_item(self):
item = DIDLLite.MusicArtist(self.storeID+1000, AUDIO_ARTIST_CONTAINER_ID, self.name)
item.childCount = self.get_child_count()
return item
def get_id(self):
return self.storeID + 1000
def get_name(self):
return self.name
def __repr__(self):
return '<Artist %d name="%s" musicbrainz="%s">' \
% (self.storeID, self.name.encode('ascii', 'ignore'), self.musicbrainz_id)
class Album(item.Item,BackendItem):
""" definition for an album """
schemaVersion = 1
typeName = 'album'
mimetype = 'directory'
title = attributes.text(allowNone=False, indexed=True)
musicbrainz_id = attributes.text()
artist = attributes.reference(allowNone=False, indexed=True)
cd_count = attributes.integer(default=1)
cover = attributes.text(default=u'')
get_path = None
def get_children(self,start=0,request_count=0):
children = list(self.store.query(Track, Track.album == self,sort=Track.track_nr.ascending))
if request_count == 0:
return children[start:]
else:
return children[start:request_count]
def get_child_count(self):
return len(list(self.store.query(Track, Track.album == self)))
def get_item(self):
item = DIDLLite.MusicAlbum(self.storeID+1000, AUDIO_ALBUM_CONTAINER_ID, self.title)
item.artist = self.artist.name
item.childCount = self.get_child_count()
if len(self.cover)>0:
_,ext = os.path.splitext(self.cover)
item.albumArtURI = ''.join((self.store.urlbase,str(self.get_id()),'?cover',ext))
if self.get_child_count() > 0:
res = DIDLLite.PlayContainerResource(self.store.server.uuid,cid=self.get_id(),fid=self.get_children()[0].get_id())
item.res.append(res)
return item
def get_id(self):
return self.storeID + 1000
def get_name(self):
return self.title
def get_cover(self):
return self.cover
def __repr__(self):
return '<Album %d title="%s" artist="%s" #cds %d cover="%s" musicbrainz="%s">' \
% (self.storeID, self.title.encode('ascii', 'ignore'),
self.artist.name.encode('ascii', 'ignore'),
self.cd_count,
self.cover.encode('ascii', 'ignore'),
self.musicbrainz_id)
class Track(item.Item,BackendItem):
""" definition for a track """
schemaVersion = 1
typeName = 'track'
title = attributes.text(allowNone=False, indexed=True)
track_nr = attributes.integer(default=1,allowNone=False)
cd_nr = attributes.integer(default=1,allowNone=False)
album = attributes.reference(allowNone=False, indexed=True)
location = attributes.text(allowNone=False)
rating=attributes.integer(default=0,allowNone=False)
last_played=attributes.timestamp()
added=attributes.timestamp(default=Time(),allowNone=False)
def get_children(self,start=0,request_count=0):
return []
def get_child_count(self):
return 0
def get_item(self):
item = DIDLLite.MusicTrack(self.storeID+1000, self.album.storeID+1000,self.title)
item.artist = self.album.artist.name
item.album = self.album.title
if self.album.cover != '':
_,ext = os.path.splitext(self.album.cover)
""" add the cover image extension to help clients not reacting on
the mimetype """
item.albumArtURI = ''.join((self.store.urlbase,str(self.storeID+1000),'?cover',ext))
item.originalTrackNumber = self.track_nr
item.server_uuid = str(self.store.server.uuid)[5:]
_,host_port,_,_,_ = urlsplit(self.store.urlbase)
if host_port.find(':') != -1:
host,port = tuple(host_port.split(':'))
else:
host = host_port
_,ext = os.path.splitext(self.location)
ext = ext.lower()
try:
mimetype = KNOWN_AUDIO_TYPES[ext]
except KeyError:
mimetype = 'audio/mpeg'
statinfo = os.stat(self.location)
res = DIDLLite.Resource('file://'+self.location, 'internal:%s:%s:*' % (host,mimetype))
try:
res.size = statinfo.st_size
except:
res.size = 0
item.res.append(res)
url = self.store.urlbase + str(self.storeID+1000) + ext
res = DIDLLite.Resource(url, 'http-get:*:%s:*' % mimetype)
try:
res.size = statinfo.st_size
except:
res.size = 0
item.res.append(res)
#if self.store.server.coherence.config.get('transcoding', 'no') == 'yes':
# if mimetype in ('audio/mpeg',
# 'application/ogg','audio/ogg',
# 'audio/x-m4a',
# 'application/x-flac'):
# dlna_pn = 'DLNA.ORG_PN=LPCM'
# dlna_tags = DIDLLite.simple_dlna_tags[:]
# dlna_tags[1] = 'DLNA.ORG_CI=1'
# #dlna_tags[2] = 'DLNA.ORG_OP=00'
# new_res = DIDLLite.Resource(url+'?transcoded=lpcm',
# 'http-get:*:%s:%s' % ('audio/L16;rate=44100;channels=2', ';'.join([dlna_pn]+dlna_tags)))
# new_res.size = None
# item.res.append(new_res)
#
# if mimetype != 'audio/mpeg':
# new_res = DIDLLite.Resource(url+'?transcoded=mp3',
# 'http-get:*:%s:*' % 'audio/mpeg')
# new_res.size = None
# item.res.append(new_res)
try:
# FIXME: getmtime is deprecated in Twisted 2.6
item.date = datetime.fromtimestamp(statinfo.st_mtime)
except:
item.date = None
return item
def get_path(self):
return self.location.encode('utf-8')
def get_id(self):
return self.storeID + 1000
def get_name(self):
return self.title
def get_url(self):
return self.store.urlbase + str(self.storeID+1000).encode('utf-8')
def get_cover(self):
return self.album.cover
def __repr__(self):
return '<Track %d title="%s" nr="%d" album="%s" artist="%s" path="%s">' \
% (self.storeID, self.title.encode('ascii', 'ignore'),
self.track_nr,
self.album.title.encode('ascii', 'ignore'),
self.album.artist.name.encode('ascii', 'ignore'),
self.location.encode('ascii', 'ignore'))
class Playlist(item.Item,BackendItem):
""" definition for a playlist
- has a name
- and references to tracks
- that reference list must keep its ordering
and items can be inserted at any place,
moved up or down or deleted
"""
schemaVersion = 1
typeName = ''
name = attributes.text(allowNone=False, indexed=True)
# references to tracks
get_path = None
class MediaStore(BackendStore):
logCategory = 'media_store'
implements = ['MediaServer']
def __init__(self, server, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.info("MediaStore __init__")
self.update_id = 0
self.medialocation = kwargs.get('medialocation','tests/content/audio')
self.coverlocation = kwargs.get('coverlocation',None)
if self.coverlocation is not None and self.coverlocation[-1] != '/':
self.coverlocation = self.coverlocation + '/'
self.mediadb = kwargs.get('mediadb',MEDIA_DB)
self.name = kwargs.get('name','MediaStore')
self.containers = {}
self.containers[ROOT_CONTAINER_ID] = \
Container( ROOT_CONTAINER_ID,-1, self.name)
self.wmc_mapping.update({'4': lambda : self.get_by_id(AUDIO_ALL_CONTAINER_ID), # all tracks
'7': lambda : self.get_by_id(AUDIO_ALBUM_CONTAINER_ID), # all albums
'6': lambda : self.get_by_id(AUDIO_ARTIST_CONTAINER_ID), # all artists
})
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
def walk(self, path):
#print "walk", path
if os.path.exists(path):
for filename in os.listdir(path):
if os.path.isdir(os.path.join(path,filename)):
self.walk(os.path.join(path,filename))
else:
_,ext = os.path.splitext(filename)
if ext.lower() in KNOWN_AUDIO_TYPES:
self.filelist.append(os.path.join(path,filename))
def get_music_files(self, musiclocation):
if not isinstance(musiclocation, list):
musiclocation = [musiclocation]
self.filelist = []
for path in musiclocation:
self.walk(path)
def check_for_cover_art(path):
#print "check_for_cover_art", path
""" let's try to find in the current directory some jpg file,
or png if the jpg search fails, and take the first one
that comes around
"""
jpgs = [i for i in os.listdir(path) if os.path.splitext(i)[1] in ('.jpg', '.JPG')]
try:
return unicode(jpgs[0])
except IndexError:
pngs = [i for i in os.listdir(path) if os.path.splitext(i)[1] in ('.png', '.PNG')]
try:
return unicode(pngs[0])
except IndexError:
return u''
def got_tags(tags, file):
#print "got_tags", tags
album=tags.get('album', '')
artist=tags.get('artist', '')
title=tags.get('title', '')
track=tags.get('track', 0)
if len(artist) == 0:
return;
artist = u'UNKNOWN_ARTIST'
if len(album) == 0:
return;
album = u'UNKNOWN_ALBUM'
if len(title) == 0:
return;
title = u'UNKNOWN_TITLE'
#print "Tags:", file, album, artist, title, track
artist_ds = self.db.findOrCreate(Artist, name=unicode(artist,'utf8'))
album_ds = self.db.findOrCreate(Album,
title=unicode(album,'utf8'),
artist=artist_ds)
if len(album_ds.cover) == 0:
dirname = unicode(os.path.dirname(file),'utf-8')
album_ds.cover = check_for_cover_art(dirname)
if len(album_ds.cover) > 0:
filename = u"%s - %s" % ( album_ds.artist.name, album_ds.title)
filename = sanitize(filename + os.path.splitext(album_ds.cover)[1])
filename = os.path.join(dirname,filename)
shutil.move(os.path.join(dirname,album_ds.cover),filename)
album_ds.cover = filename
#print album_ds.cover
track_ds = self.db.findOrCreate(Track,
title=unicode(title,'utf8'),
track_nr=int(track),
album=album_ds,
location=unicode(file,'utf8'))
for file in self.filelist:
d = defer.maybeDeferred(get_tags,file)
d.addBoth(got_tags, file)
def show_db(self):
for album in list(self.db.query(Album,sort=Album.title.ascending)):
print album
for track in list(self.db.query(Track, Track.album == album,sort=Track.track_nr.ascending)):
print track
def show_albums(self):
for album in list(self.db.query(Album,sort=Album.title.ascending)):
print album
def show_artists(self):
for artist in list(self.db.query(Artist,sort=Artist.name.ascending)):
print artist
def show_tracks_by_artist(self, artist_name):
"""
artist = self.db.query(Artist,Artist.name == artist_name)
artist = list(artist)[0]
for album in list(self.db.query(Album, Album.artist == artist)):
for track in list(self.db.query(Track, Track.album == album,sort=Track.title.ascending)):
print track
"""
for track in [x[2] for x in list(self.db.query((Artist,Album,Track),
attributes.AND(Artist.name == artist_name,
Album.artist == Artist.storeID,
Track.album == Album.storeID),
sort=(Track.title.ascending)
))]:
print track
def show_tracks_by_title(self, title_or_part):
for track in list(self.db.query(Track, Track.title.like(u'%',title_or_part,u'%'),sort=Track.title.ascending)):
print track
def show_tracks_to_filename(self, title_or_part):
for track in list(self.db.query(Track, Track.title.like(u'%',title_or_part,u'%'),sort=Track.title.ascending)):
print track.title, track.album.artist.name, track.track_nr
_,ext = os.path.splitext(track.path)
f = "%02d - %s - %s%s" % ( track.track_nr, track.album.artist.name,
track.title, ext)
f = sanitize(f)
print f
def get_album_covers(self):
for album in list(self.db.query(Album, Album.cover == u'')):
print "missing cover for:", album.artist.name, album.title
filename = "%s - %s" % ( album.artist.name, album.title)
filename = sanitize(filename)
if self.coverlocation is not None:
cover_path = os.path.join(self.coverlocation,filename +'.jpg')
if os.path.exists(cover_path) is True:
print "cover found:", cover_path
album.cover = cover_path
else:
def got_it(f,a):
print "cover saved:",f, a.title
a.cover = f
aws_key = '1XHSE4FQJ0RK0X3S9WR2'
CoverGetter(cover_path,aws_key,
callback=(got_it,(album)),
artist=album.artist.name,
title=album.title)
def get_by_id(self,id):
self.info("get_by_id %s" % id)
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0].split('.')[0]
if isinstance(id, basestring) and id.startswith('artist_all_tracks_'):
try:
return self.containers[id]
except:
return None
try:
id = int(id)
except ValueError:
id = 1000
try:
item = self.containers[id]
except:
try:
item = self.db.getItemByID(id-1000)
except:
item = None
self.info("get_by_id found", item)
return item
def upnp_init(self):
#print "MediaStore upnp_init"
db_is_new = False
if os.path.exists(self.mediadb) is False:
db_is_new = True
self.db = store.Store(self.mediadb)
self.containers[AUDIO_ALL_CONTAINER_ID] = \
Container( AUDIO_ALL_CONTAINER_ID,ROOT_CONTAINER_ID, 'All tracks',
children_callback=lambda :list(self.db.query(Track,sort=Track.title.ascending)),
store=self,play_container=True)
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_ALL_CONTAINER_ID])
self.containers[AUDIO_ALBUM_CONTAINER_ID] = \
Container( AUDIO_ALBUM_CONTAINER_ID,ROOT_CONTAINER_ID, 'Albums',
children_callback=lambda :list(self.db.query(Album,sort=Album.title.ascending)))
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_ALBUM_CONTAINER_ID])
self.containers[AUDIO_ARTIST_CONTAINER_ID] = \
Container( AUDIO_ARTIST_CONTAINER_ID,ROOT_CONTAINER_ID, 'Artists',
children_callback=lambda :list(self.db.query(Artist,sort=Artist.name.ascending)))
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_ARTIST_CONTAINER_ID])
self.db.server = self.server
self.db.urlbase = self.urlbase
self.db.containers = self.containers
if db_is_new is True:
self.get_music_files(self.medialocation)
self.get_album_covers()
#self.show_db()
#self.show_artists()
#self.show_albums()
#self.show_tracks_by_artist(u'Meat Loaf')
#self.show_tracks_by_artist(u'Beyonce')
#self.show_tracks_by_title(u'Bad')
#self.show_tracks_to_filename(u'säen')
self.current_connection_id = None
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
['internal:%s:audio/mpeg:*' % self.server.coherence.hostname,
'http-get:*:audio/mpeg:*',
'internal:%s:application/ogg:*' % self.server.coherence.hostname,
'http-get:*:application/ogg:*'],
default=True)
if __name__ == '__main__':
from twisted.internet import reactor
from twisted.internet import task
def run():
m = MediaStore(None, medialocation='/data/audio/music',
coverlocation='/data/audio/covers',
mediadb='/tmp/media.db')
m.upnp_init()
reactor.callWhenRunning(run)
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | misc~Rhythmbox-Plugin~upnp_coherence~UpnpSource.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
#
# Copyright 2011, Caleb Callaway <[email protected]>
# Copyright 2007-2010 Frank Scholz <[email protected]>
# Copyright 2007, James Livingston <[email protected]>
import rb, rhythmdb
import gobject, gtk
import re
from coherence import __version_info__ as coherence_version
from coherence import log
from coherence.upnp.core import DIDLLite
class UpnpSource(rb.BrowserSource,log.Loggable):
logCategory = 'rb_media_store'
__gproperties__ = {
'plugin': (rb.Plugin, 'plugin', 'plugin', gobject.PARAM_WRITABLE|gobject.PARAM_CONSTRUCT_ONLY),
'client': (gobject.TYPE_PYOBJECT, 'client', 'client', gobject.PARAM_WRITABLE|gobject.PARAM_CONSTRUCT_ONLY),
'udn': (gobject.TYPE_PYOBJECT, 'udn', 'udn', gobject.PARAM_WRITABLE|gobject.PARAM_CONSTRUCT_ONLY),
}
def __init__(self):
rb.BrowserSource.__init__(self)
self.__db = None
self.__activated = False
self.container_watch = []
def do_set_property(self, property, value):
if property.name == 'plugin':
self.__plugin = value
elif property.name == 'client':
self.__client = value
self.props.name = self.__client.device.get_friendly_name()
elif property.name == 'udn':
self.__udn = value
elif property.name == 'entry-type':
self.__entry_type = value
else:
raise AttributeError('unknown property %s' % property.name)
def do_selected (self):
if not self.__activated:
print "activating upnp source"
self.__activated = True
shell = self.get_property('shell')
self.__db = shell.get_property('db')
self.__entry_type = self.get_property('entry-type')
self.load_db()
self.__client.content_directory.subscribe_for_variable('ContainerUpdateIDs', self.state_variable_change)
self.__client.content_directory.subscribe_for_variable('SystemUpdateID', self.state_variable_change)
def do_get_status(self):
if (self.browse_count > 0):
return ('Loading contents of %s' % self.props.name, None, 0)
else:
qm = self.get_property("query-model")
return (qm.compute_status_normal("%d song", "%d songs"), None, 2.0)
def load_db(self):
self.browse_count = 0
self.load_children(0)
def load_children(self, id):
self.browse_count += 1
d = self.__client.content_directory.browse(id, browse_flag='BrowseDirectChildren', process_result=False, backward_compatibility=False)
d.addCallback(self.process_media_server_browse, self.__udn)
d.addErrback(self.err_back)
def err_back(self, *args, **kw):
self.info("Browse action failed: %s" % str(args))
self.browse_count -= 1
def state_variable_change(self, variable, udn=None):
self.info("%s changed from >%s< to >%s<", variable.name, variable.old_value, variable.value)
if variable.old_value == '':
return
if variable.name == 'SystemUpdateID':
self.load_db(0)
elif variable.name == 'ContainerUpdateIDs':
changes = variable.value.split(',')
while len(changes) > 1:
container = changes.pop(0).strip()
update_id = changes.pop(0).strip()
if container in self.container_watch:
self.info("we have a change in %r, container needs a reload", container)
self.load_db(container)
def process_media_server_browse(self, results, udn):
self.browse_count -= 1
didl = DIDLLite.DIDLElement.fromString(results['Result'])
for item in didl.getItems():
self.info("process_media_server_browse %r %r", item.id, item)
if item.upnp_class.startswith('object.container'):
self.load_children(item.id)
if item.upnp_class.startswith('object.item.audioItem'):
url = None
duration = None
size = None
bitrate = None
for res in item.res:
remote_protocol,remote_network,remote_content_format,remote_flags = res.protocolInfo.split(':')
self.info("%r %r %r %r",remote_protocol,remote_network,remote_content_format,remote_flags)
if remote_protocol == 'http-get':
url = res.data
duration = res.duration
size = res.size
bitrate = res.bitrate
break
if url is not None and item.refID is None:
self.info("url %r %r",url,item.title)
entry = self.__db.entry_lookup_by_location (url)
if entry == None:
entry = self.__db.entry_new(self.__entry_type, url)
self.__db.set(entry, rhythmdb.PROP_TITLE, item.title)
try:
if item.artist is not None:
self.__db.set(entry, rhythmdb.PROP_ARTIST, item.artist)
except AttributeError:
pass
try:
if item.album is not None:
self.__db.set(entry, rhythmdb.PROP_ALBUM, item.album)
except AttributeError:
pass
try:
if item.genre is not None:
self.__db.set(entry, rhythmdb.PROP_GENRE, item.genre)
except AttributeError:
pass
try:
self.info("%r %r", item.title,item.originalTrackNumber)
if item.originalTrackNumber is not None:
self.__db.set(entry, rhythmdb.PROP_TRACK_NUMBER, int(item.originalTrackNumber))
except AttributeError:
pass
if duration is not None:
#match duration via regular expression.
#in case RB ever supports fractions of a second, here's the full regexp:
#"(\d+):([0-5][0-9]):([0-5][0-9])(?:\.(\d+))?(?:\.(\d+)\/(\d+))?"
self.info("duration: %r" %(duration))
match = re.match("(\d+):([0-5][0-9]):([0-5][0-9])", duration)
if match is not None:
h = match.group(1)
m = match.group(2)
s = match.group(3)
seconds = int(h)*3600 + int(m)*60 + int(s)
self.info("duration parsed as %r:%r:%r (%r seconds)" % (h,m,s,seconds))
self.__db.set(entry, rhythmdb.PROP_DURATION, seconds)
if size is not None:
try:
self.__db.set(entry, rhythmdb.PROP_FILE_SIZE,int(size))
except AttributeError:
pass
if bitrate is not None:
try:
self.__db.set(entry, rhythmdb.PROP_BITRATE,int(bitrate))
except AttributeError:
pass
self.__db.commit()
gobject.type_register(UpnpSource)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~dvbd_storage.py |
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
from datetime import datetime
import urllib
from twisted.internet import reactor, defer
from twisted.python import failure, util
from twisted.python.filepath import FilePath
from coherence.upnp.core import DIDLLite
import dbus
import dbus.service
import coherence.extern.louie as louie
from coherence.backend import BackendItem, BackendStore
ROOT_CONTAINER_ID = 0
RECORDINGS_CONTAINER_ID = 100
CHANNELS_CONTAINER_ID = 200
CHANNEL_GROUPS_CONTAINER_ID = 300
BASE_CHANNEL_GROUP_ID = 1000
BUS_NAME = 'org.gnome.DVB'
RECORDINGSSTORE_OBJECT_PATH = '/org/gnome/DVB/RecordingsStore'
MANAGER_OBJECT_PATH = '/org/gnome/DVB/Manager'
class Container(BackendItem):
logCategory = 'dvbd_store'
def __init__(self, id, parent_id, name, store=None, children_callback=None, container_class=DIDLLite.Container):
self.id = id
self.parent_id = parent_id
self.name = name
self.mimetype = 'directory'
self.item = container_class(id, parent_id,self.name)
self.item.childCount = 0
self.update_id = 0
if children_callback != None:
self.children = children_callback
else:
self.children = util.OrderedDict()
if store!=None:
self.get_url = lambda: store.urlbase + str(self.id)
def add_child(self, child):
id = child.id
if isinstance(child.id, basestring):
_,id = child.id.split('.')
self.children[id] = child
if self.item.childCount != None:
self.item.childCount += 1
def get_children(self,start=0,end=0):
self.info("container.get_children %r %r", start, end)
if callable(self.children):
return self.children(start,end-start)
else:
children = self.children.values()
if end == 0:
return children[start:]
else:
return children[start:end]
def remove_children(self):
if not callable(self.children):
self.children = util.OrderedDict()
self.item.childCount = 0
def get_child_count(self):
if self.item.childCount != None:
return self.item.childCount
if callable(self.children):
return len(self.children())
else:
return len(self.children)
def get_item(self):
return self.item
def get_name(self):
return self.name
def get_id(self):
return self.id
class Channel(BackendItem):
logCategory = 'dvbd_store'
def __init__(self,store,
id,parent_id,
name, url, network,
mimetype):
self.store = store
self.id = 'channel.%s' % id
self.parent_id = parent_id
self.real_id = id
self.name = unicode(name)
self.network = unicode(network)
self.stream_url = url
self.mimetype = str(mimetype)
def get_children(self, start=0, end=0):
return []
def get_child_count(self):
return 0
def get_item(self, parent_id=None):
self.debug("Channel get_item %r @ %r" %(self.id,self.parent_id))
item = DIDLLite.VideoBroadcast(self.id,self.parent_id)
item.title = self.name
res = DIDLLite.Resource(self.stream_url, 'rtsp-rtp-udp:*:%s:*' % self.mimetype)
item.res.append(res)
return item
def get_id(self):
return self.id
def get_name(self):
return self.name
class Recording(BackendItem):
logCategory = 'dvbd_store'
def __init__(self,store,
id,parent_id,
file,title,
date,duration,
mimetype):
self.store = store
self.id = 'recording.%s' % id
self.parent_id = parent_id
self.real_id = id
path = unicode(file)
# make sure path is an absolute local path (and not an URL)
if path.startswith("file://"):
path = path[7:]
self.location = FilePath(path)
self.title = unicode(title)
self.mimetype = str(mimetype)
self.date = datetime.fromtimestamp(int(date))
self.duration = int(duration)
try:
self.size = self.location.getsize()
except Exception, msg:
self.size = 0
self.bitrate = 0
self.url = self.store.urlbase + str(self.id)
def get_children(self, start=0, end=0):
return []
def get_child_count(self):
return 0
def get_item(self, parent_id=None):
self.debug("Recording get_item %r @ %r" %(self.id,self.parent_id))
# create item
item = DIDLLite.VideoBroadcast(self.id,self.parent_id)
item.date = self.date
item.title = self.title
# add http resource
res = DIDLLite.Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
if self.size > 0:
res.size = self.size
if self.duration > 0:
res.duration = str(self.duration)
if self.bitrate > 0:
res.bitrate = str(bitrate)
item.res.append(res)
# add internal resource
res = DIDLLite.Resource('file://'+ urllib.quote(self.get_path()), 'internal:%s:%s:*' % (self.store.server.coherence.hostname,self.mimetype))
if self.size > 0:
res.size = self.size
if self.duration > 0:
res.duration = str(self.duration)
if self.bitrate > 0:
res.bitrate = str(bitrate)
item.res.append(res)
return item
def get_id(self):
return self.id
def get_name(self):
return self.title
def get_url(self):
return self.url
def get_path(self):
return self.location.path
class DVBDStore(BackendStore):
""" this is a backend to the DVB Daemon
http://www.k-d-w.org/node/42
"""
implements = ['MediaServer']
logCategory = 'dvbd_store'
def __init__(self, server, **kwargs):
if server.coherence.config.get('use_dbus','no') != 'yes':
raise Exception('this backend needs use_dbus enabled in the configuration')
BackendStore.__init__(self,server,**kwargs)
self.config = kwargs
self.name = kwargs.get('name','TV')
self.update_id = 0
self.channel_groups = []
if kwargs.get('enable_destroy','no') == 'yes':
self.upnp_DestroyObject = self.hidden_upnp_DestroyObject
self.bus = dbus.SessionBus()
dvb_daemon_recordingsStore = self.bus.get_object(BUS_NAME,RECORDINGSSTORE_OBJECT_PATH)
dvb_daemon_manager = self.bus.get_object(BUS_NAME,MANAGER_OBJECT_PATH)
self.store_interface = dbus.Interface(dvb_daemon_recordingsStore, 'org.gnome.DVB.RecordingsStore')
self.manager_interface = dbus.Interface(dvb_daemon_manager, 'org.gnome.DVB.Manager')
dvb_daemon_recordingsStore.connect_to_signal('Changed', self.recording_changed,
dbus_interface='org.gnome.DVB.RecordingsStore')
self.containers = {}
self.containers[ROOT_CONTAINER_ID] = \
Container(ROOT_CONTAINER_ID,-1,self.name,store=self)
self.containers[RECORDINGS_CONTAINER_ID] = \
Container(RECORDINGS_CONTAINER_ID,ROOT_CONTAINER_ID,'Recordings',store=self)
self.containers[CHANNELS_CONTAINER_ID] = \
Container(CHANNELS_CONTAINER_ID,ROOT_CONTAINER_ID,'Channels',store=self)
self.containers[CHANNEL_GROUPS_CONTAINER_ID] = \
Container(CHANNEL_GROUPS_CONTAINER_ID, ROOT_CONTAINER_ID, 'Channel Groups',
store=self)
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[RECORDINGS_CONTAINER_ID])
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[CHANNELS_CONTAINER_ID])
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[CHANNEL_GROUPS_CONTAINER_ID])
def query_finished(r):
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
def query_failed(error):
self.error("ERROR: %s", error)
louie.send('Coherence.UPnP.Backend.init_failed', None, backend=self, msg=error)
# get_device_groups is called after get_channel_groups,
# because we need channel groups first
channel_d = self.get_channel_groups()
channel_d.addCallback(self.get_device_groups)
channel_d.addErrback(query_failed)
d = defer.DeferredList((channel_d, self.get_recordings()))
d.addCallback(query_finished)
d.addErrback(query_failed)
def __repr__(self):
return "DVBDStore"
def get_by_id(self,id):
self.info("looking for id %r", id)
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
item = None
try:
id = int(id)
item = self.containers[id]
except (ValueError,KeyError):
try:
type,id = id.split('.')
if type == 'recording':
return self.containers[RECORDINGS_CONTAINER_ID].children[id]
except (ValueError,KeyError):
return None
return item
def recording_changed(self, id, mode):
self.containers[RECORDINGS_CONTAINER_ID].remove_children()
def handle_result(r):
self.debug("recording changed, handle_result: %s",
self.containers[RECORDINGS_CONTAINER_ID].update_id)
self.containers[RECORDINGS_CONTAINER_ID].update_id += 1
if( self.server and
hasattr(self.server,'content_directory_server')):
if hasattr(self, 'update_id'):
self.update_id += 1
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
value = (RECORDINGS_CONTAINER_ID,self.containers[RECORDINGS_CONTAINER_ID].update_id)
self.debug("ContainerUpdateIDs new value: %s", value)
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
def handle_error(error):
self.error("ERROR: %s", error)
return error
d = self.get_recordings()
d.addCallback(handle_result)
d.addErrback(handle_error)
def get_recording_details(self, id):
self.debug("GET RECORDING DETAILS")
def process_details(data):
self.debug("GOT RECORDING DETAILS %s", data)
rid, name, desc, length, start, channel, location = data
if len(name) == 0:
name = 'Recording ' + str(rid)
return {'id':rid,'name':name,'path':location,'date': start,'duration':length}
def handle_error(error):
self.error("ERROR: %s", error)
return error
d = defer.Deferred()
d.addCallback(process_details)
d.addErrback(handle_error)
self.store_interface.GetAllInformations(id,
reply_handler=lambda x, success: d.callback(x),
error_handler=lambda x, success: d.errback(x))
return d
def get_recordings(self):
self.debug("GET RECORDINGS")
def handle_error(error):
self.error("ERROR: %s", error)
return error
def process_query_result(ids):
self.debug("GOT RECORDINGS: %s", ids)
if len(ids) == 0:
return []
l = []
for id in ids:
l.append(self.get_recording_details(id))
dl = defer.DeferredList(l)
return dl
def process_details(results):
#print 'process_details', results
for result,recording in results:
#print result, recording['name']
if result == True:
#print "add", recording['id'], recording['name'], recording['path'], recording['date'], recording['duration']
video_item = Recording(self,
recording['id'],
RECORDINGS_CONTAINER_ID,
recording['path'],
recording['name'],
recording['date'],
recording['duration'],
'video/mpegts')
self.containers[RECORDINGS_CONTAINER_ID].add_child(video_item)
d = defer.Deferred()
d.addCallback(process_query_result)
d.addCallback(process_details)
d.addErrback(handle_error)
d.addErrback(handle_error)
self.store_interface.GetRecordings(reply_handler=lambda x: d.callback(x),
error_handler=lambda x: d.errback(x))
return d
def get_channel_details(self, channelList_interface, id):
self.debug("GET CHANNEL DETAILS %s" , id)
def get_name(id):
d = defer.Deferred()
channelList_interface.GetChannelName(id,
reply_handler=lambda x,success: d.callback(x),
error_handler=lambda x,success: d.errback(x))
return d
def get_network(id):
d = defer.Deferred()
channelList_interface.GetChannelNetwork(id,
reply_handler=lambda x,success: d.callback(x),
error_handler=lambda x,success: d.errback(x))
return d
def get_url(id):
d = defer.Deferred()
channelList_interface.GetChannelURL(id,
reply_handler=lambda x,success: d.callback(x),
error_handler=lambda x,success: d.errback(x))
return d
def process_details(r, id):
self.debug("GOT DETAILS %d: %s", id, r)
name = r[0][1]
network = r[1][1]
url = r[2][1]
return {'id':id, 'name':name.encode('latin-1'), 'network':network, 'url':url}
def handle_error(error):
return error
dl = defer.DeferredList((get_name(id),get_network(id), get_url(id)))
dl.addCallback(process_details,id)
dl.addErrback(handle_error)
return dl
def get_channelgroup_members(self, channel_items, channelList_interface):
self.debug("GET ALL CHANNEL GROUP MEMBERS")
def handle_error(error):
self.error("ERROR: %s", error)
return error
def process_getChannelsOfGroup(results, group_id):
for channel_id in results:
channel_id = int(channel_id)
if channel_id in channel_items:
item = channel_items[channel_id]
container_id = BASE_CHANNEL_GROUP_ID + group_id
self.containers[container_id].add_child(item)
def get_members(channelList_interface, group_id):
self.debug("GET CHANNEL GROUP MEMBERS %d", group_id)
d = defer.Deferred()
d.addCallback(process_getChannelsOfGroup, group_id)
d.addErrback(handle_error)
channelList_interface.GetChannelsOfGroup(group_id,
reply_handler=lambda x, success: d.callback(x),
error_handler=lambda x, success: d.callback(x))
return d
l = []
for group_id, group_name in self.channel_groups:
l.append(get_members(channelList_interface, group_id))
dl = defer.DeferredList(l)
return dl
def get_tv_channels(self, channelList_interface):
self.debug("GET TV CHANNELS")
def handle_error(error):
self.error("ERROR: %s", error)
return error
def process_getChannels_result(channels, channelList_interface):
self.debug("GetChannels: %s", channels)
if len(channels) == 0:
return []
l = []
for channel_id in channels:
l.append(self.get_channel_details(channelList_interface, channel_id))
dl = defer.DeferredList(l)
return dl
def process_details(results):
self.debug('GOT DEVICE GROUP DETAILS %s', results)
channels = {}
for result,channel in results:
#print channel
if result == True:
name = unicode(channel['name'], errors='ignore')
#print "add", name, channel['url']
video_item = Channel(self,
channel['id'],
CHANNELS_CONTAINER_ID,
name,
channel['url'],
channel['network'],
'video/mpegts')
self.containers[CHANNELS_CONTAINER_ID].add_child(video_item)
channels[int(channel['id'])] = video_item
return channels
d = defer.Deferred()
d.addCallback(process_getChannels_result, channelList_interface)
d.addCallback(process_details)
d.addCallback(self.get_channelgroup_members, channelList_interface)
d.addErrback(handle_error)
d.addErrback(handle_error)
d.addErrback(handle_error)
channelList_interface.GetTVChannels(reply_handler=lambda x: d.callback(x),
error_handler=lambda x: d.errback(x))
return d
def get_deviceGroup_details(self, devicegroup_interface):
self.debug("GET DEVICE GROUP DETAILS")
def handle_error(error):
self.error("ERROR: %s", error)
return error
def process_getChannelList_result(result):
self.debug("GetChannelList: %s", result)
dvbd_channelList = self.bus.get_object(BUS_NAME,result)
channelList_interface = dbus.Interface (dvbd_channelList, 'org.gnome.DVB.ChannelList')
return self.get_tv_channels(channelList_interface)
d = defer.Deferred()
d.addCallback(process_getChannelList_result)
d.addErrback(handle_error)
devicegroup_interface.GetChannelList(reply_handler=lambda x: d.callback(x),
error_handler=lambda x: d.errback(x))
return d
def get_device_groups(self, results):
self.debug("GET DEVICE GROUPS")
def handle_error(error):
self.error("ERROR: %s", error)
return error
def process_query_result(ids):
self.debug("GetRegisteredDeviceGroups: %s", ids)
if len(ids) == 0:
return
l = []
for group_object_path in ids:
dvbd_devicegroup = self.bus.get_object(BUS_NAME, group_object_path)
devicegroup_interface = dbus.Interface(dvbd_devicegroup, 'org.gnome.DVB.DeviceGroup')
l.append(self.get_deviceGroup_details(devicegroup_interface))
dl = defer.DeferredList(l)
return dl
d = defer.Deferred()
d.addCallback(process_query_result)
d.addErrback(handle_error)
self.manager_interface.GetRegisteredDeviceGroups(reply_handler=lambda x: d.callback(x),
error_handler=lambda x: d.errback(x))
return d
def get_channel_groups(self):
self.debug("GET CHANNEL GROUPS")
def handle_error(error):
self.error("ERROR: %s", error)
return error
def process_GetChannelGroups_result(data):
self.debug("GOT CHANNEL GROUPS %s", data)
for group in data:
self.channel_groups.append(group) # id, name
container_id = BASE_CHANNEL_GROUP_ID + group[0]
group_item = Container(container_id, CHANNEL_GROUPS_CONTAINER_ID,
group[1], store=self)
self.containers[container_id] = group_item
self.containers[CHANNEL_GROUPS_CONTAINER_ID].add_child(group_item)
d = defer.Deferred()
d.addCallback(process_GetChannelGroups_result)
d.addErrback(handle_error)
self.manager_interface.GetChannelGroups(reply_handler=lambda x: d.callback(x),
error_handler=lambda x: d.errback(x))
return d
def upnp_init(self):
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
['http-get:*:video/mpegts:*',
'internal:%s:video/mpegts:*' % self.server.coherence.hostname,],
'rtsp-rtp-udp:*:video/mpegts:*',)
def hidden_upnp_DestroyObject(self, *args, **kwargs):
ObjectID = kwargs['ObjectID']
item = self.get_by_id(ObjectID)
if item == None:
return failure.Failure(errorCode(701))
def handle_success(deleted):
print 'deleted', deleted, kwargs['ObjectID']
if deleted == False:
return failure.Failure(errorCode(715))
return {}
def handle_error(error):
return failure.Failure(errorCode(701))
d = defer.Deferred()
self.store_interface.Delete(int(item.real_id),
reply_handler=lambda x: d.callback(x),
error_handler=lambda x: d.errback(x))
d.addCallback(handle_success)
d.addErrback(handle_error)
return d
class DVBDScheduledRecording(BackendStore):
logCategory = 'dvbd_store'
def __init__(self, server, **kwargs):
if server.coherence.config.get('use_dbus','no') != 'yes':
raise Exception('this backend needs use_dbus enabled in the configuration')
BackendStore.__init__(self, server, **kwargs)
self.state_update_id = 0
self.bus = dbus.SessionBus()
# We have one ScheduleRecording service for each device group
# TODO use one ScheduledRecording for each device group
self.device_group_interface = None
dvbd_recorder = self.device_group_interface.GetRecorder()
self.recorder_interface = self.bus.get_object(BUS_NAME, dvdb_recorder)
def __repr__(self):
return "DVBDScheduledRecording"
def get_timer_details(self, tid):
self.debug("GET TIMER DETAILS %d", tid)
def handle_error(error):
self.error("ERROR: %s", error)
return error
def get_infos(tid):
d = defer.Callback()
self.recorder_interface.GetAllInformations(tid,
reply_handler=lambda x, success: d.callback(x),
error_handler=lambda x, success: d.errback(x))
return d
def get_start_time(tid):
d = defer.Callback()
self.recorder_interface.GetStartTime(tid,
reply_handler=lambda x, success: d.callback(x),
error_handler=lambda x, success: d.errback(x))
return d
def process_details(results):
tid, duration, active, channel_name, title = results[0][1]
start = results[1][1]
start_datetime = datetime (*start)
# TODO return what we actually need
# FIXME we properly want the channel id here rather than the name
return {'id': tid, 'duration': duration, 'channel': channel,
'start': start_datetime}
d = defer.DeferredList((self.get_infos(tid), self.get_start_time(tid)))
d.addCallback(process_details)
d.addErrback(handle_error)
return d
def get_timers(self):
self.debug("GET TIMERS")
def handle_error(error):
self.error("ERROR: %s", error)
return error
def process_GetTimers_results(timer_ids):
l = []
for tid in timer_ids:
l.append(self.get_timer_details(tid))
dl = defer.DeferredList(l)
return dl
d = defer.Deferred()
d.addCallback(process_GetTimers_result)
d.addErrback(handle_error)
self.recorder_interface.GetTimers(reply_handler=lambda x: d.callback(x),
error_handler=lambda x: d.errback(x))
return d
def add_timer(self, channel_id, start_datetime, duration):
self.debug("ADD TIMER")
def handle_error(error):
self.error("ERROR: %s", error)
return error
def process_AddTimer_result(timer_id):
self.state_update_id += 1
return timer_id
d = defer.Deferred()
d.addCallback(process_AddTimer_result)
d.addErrback(handle_error)
self.recorder_interface.AddTimer(channel_id, start_datetime.year,
start_datetime.month, start_datetime.day, start_datetime.hour,
start_datetime.minute, duration,
reply_handler=lambda x, success: d.callback(x),
error_handler=lambda x, success: d.errback(x))
return d
def delete_timer(self, tid):
self.debug("DELETE TIMER %d", tid)
def handle_error(error):
self.error("ERROR: %s", error)
return error
def process_DeleteTimer_result(success):
if not success:
# TODO: return 704
return
self.state_update_id += 1
d = defer.Deferred()
d.addCallback(process_DeleteTimer_result)
d.addErrback(handle_error)
self.recorder_interface.DeleteTimer(tid,
reply_handler=lambda x, success: d.callback(x),
error_handler=lambda x, success: d.errback(x))
return d
def upnp_GetPropertyList(self, *args, **kwargs):
pass
def upnp_GetAllowedValues(self, *args, **kwargs):
pass
def upnp_GetStateUpdateID(self, *args, **kwargs):
return self.state_update_id
def upnp_BrowseRecordSchedules(self, *args, **kwargs):
schedules = []
sched = RecordSchedule() # ChannelID, StartDateTime, Duration
return self.get_timers()
def upnp_BrowseRecordTasks(self, *args, **kwargs):
rec_sched_id = int(kwargs['RecordScheduleID'])
tasks = []
task = RecordTask() # ScheduleID, ChannelID, StartDateTime, Duration
return self.get_timer_details(rec_sched_id)
def upnp_CreateRecordSchedule(self, *args, **kwargs):
schedule = kwargs['RecordScheduleParts']
channel_id = schedule.getChannelID()
# returns a python datetime object
start = schedule.getStartDateTime()
# duration in minutes
duration = schedule.getDuration()
return self.add_timer(channel_id, start, duration)
def upnp_DeleteRecordSchedule(self, *args, **kwargs):
rec_sched_id = int(kwargs['RecordScheduleID'])
def handle_error(error):
self.error("ERROR: %s", error)
return error
def process_IsTimerActive_result(is_active, rec_sched_id):
if is_active:
# TODO: Return 705
return
else:
return self.delete_timer(rec_sched_id)
d = defer.Deferred()
d.addCallback(process_IsTimerActive_result, rec_sched_id)
d.addErrback(handle_error)
self.recorder_interface.IsTimerActive(rec_sched_id,
reply_handler=lambda x: d.callback(x),
error_handler=lambda x: d.errback(x))
return d
def upnp_GetRecordSchedule(self, *args, **kwargs):
rec_sched_id = int(kwargs['RecordScheduleID'])
return self.get_timer_details(rec_sched_id)
def upnp_GetRecordTask(self, *args, **kwargs):
rec_task_id = int(kwargs['RecordTaskID'])
return self.get_timer_details(rec_task_id)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~devices~media_server_client.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006, Frank Scholz <[email protected]>
from coherence.upnp.services.clients.connection_manager_client import ConnectionManagerClient
from coherence.upnp.services.clients.content_directory_client import ContentDirectoryClient
from coherence.upnp.services.clients.av_transport_client import AVTransportClient
from coherence import log
import coherence.extern.louie as louie
class MediaServerClient(log.Loggable):
logCategory = 'ms_client'
def __init__(self, device):
self.device = device
self.device_type = self.device.get_friendly_device_type()
self.version = int(self.device.get_device_type_version())
self.icons = device.icons
self.scheduled_recording = None
self.content_directory = None
self.connection_manager = None
self.av_transport = None
self.detection_completed = False
louie.connect(self.service_notified, signal='Coherence.UPnP.DeviceClient.Service.notified', sender=self.device)
for service in self.device.get_services():
if service.get_type() in ["urn:schemas-upnp-org:service:ContentDirectory:1",
"urn:schemas-upnp-org:service:ContentDirectory:2"]:
self.content_directory = ContentDirectoryClient( service)
if service.get_type() in ["urn:schemas-upnp-org:service:ConnectionManager:1",
"urn:schemas-upnp-org:service:ConnectionManager:2"]:
self.connection_manager = ConnectionManagerClient( service)
if service.get_type() in ["urn:schemas-upnp-org:service:AVTransport:1",
"urn:schemas-upnp-org:service:AVTransport:2"]:
self.av_transport = AVTransportClient( service)
#if service.get_type() in ["urn:schemas-upnp-org:service:ScheduledRecording:1",
# "urn:schemas-upnp-org:service:ScheduledRecording:2"]:
# self.scheduled_recording = ScheduledRecordingClient( service)
self.info("MediaServer %s" % (self.device.get_friendly_name()))
if self.content_directory:
self.info("ContentDirectory available")
else:
self.warning("ContentDirectory not available, device not implemented properly according to the UPnP specification")
return
if self.connection_manager:
self.info("ConnectionManager available")
else:
self.warning("ConnectionManager not available, device not implemented properly according to the UPnP specification")
return
if self.av_transport:
self.info("AVTransport (optional) available")
if self.scheduled_recording:
self.info("ScheduledRecording (optional) available")
#d = self.content_directory.browse(0) # browse top level
#d.addCallback( self.process_meta)
#def __del__(self):
# #print "MediaServerClient deleted"
# pass
def remove(self):
self.info("removal of MediaServerClient started")
if self.content_directory != None:
self.content_directory.remove()
if self.connection_manager != None:
self.connection_manager.remove()
if self.av_transport != None:
self.av_transport.remove()
if self.scheduled_recording != None:
self.scheduled_recording.remove()
#del self
def service_notified(self, service):
self.info('notified about %r' % service)
if self.detection_completed == True:
return
if self.content_directory != None:
if not hasattr(self.content_directory.service, 'last_time_updated'):
return
if self.content_directory.service.last_time_updated == None:
return
if self.connection_manager != None:
if not hasattr(self.connection_manager.service, 'last_time_updated'):
return
if self.connection_manager.service.last_time_updated == None:
return
if self.av_transport != None:
if not hasattr(self.av_transport.service, 'last_time_updated'):
return
if self.av_transport.service.last_time_updated == None:
return
if self.scheduled_recording != None:
if not hasattr(self.scheduled_recording.service, 'last_time_updated'):
return
if self.scheduled_recording.service.last_time_updated == None:
return
self.detection_completed = True
louie.send('Coherence.UPnP.DeviceClient.detection_completed', None,
client=self,udn=self.device.udn)
self.info('detection_completed for %r' % self)
def state_variable_change( self, variable, usn):
self.info(variable.name, 'changed from', variable.old_value, 'to', variable.value)
def print_results(self, results):
self.info("results=", results)
def process_meta( self, results):
for k,v in results.iteritems():
dfr = self.content_directory.browse(k, "BrowseMetadata")
dfr.addCallback( self.print_results)
| [] |
2024-01-10 | opendreambox/python-coherence | misc~Rhythmbox-Plugin~upnp_coherence~MediaStore.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
#
# Copyright 2011, Caleb Callaway <[email protected]>
# Copyright 2007-2010, Frank Scholz <[email protected]>
# Copyright 2007, James Livingston <[email protected]>
import os.path
import rhythmdb
import coherence.extern.louie as louie
import urllib
from coherence import __version_info__
from coherence.upnp.core import DIDLLite
from coherence.backend import BackendItem, BackendStore
ROOT_CONTAINER_ID = 0
AUDIO_CONTAINER = 100
AUDIO_ALL_CONTAINER_ID = 101
AUDIO_ARTIST_CONTAINER_ID = 102
AUDIO_ALBUM_CONTAINER_ID = 103
AUDIO_PLAYLIST_CONTAINER_ID = 104
CONTAINER_COUNT = 10000
TRACK_COUNT = 1000000
# most of this class is from Coherence, originally under the MIT licence
class Container(BackendItem):
logCategory = 'rb_media_store'
def __init__(self, id, parent_id, name, children_callback=None,store=None,play_container=False):
self.id = id
self.parent_id = parent_id
self.name = name
self.mimetype = 'directory'
self.store = store
self.play_container = play_container
self.update_id = 0
if children_callback != None:
self.children = children_callback
else:
self.children = []
def add_child(self, child):
self.children.append(child)
def get_children(self,start=0,request_count=0):
if callable(self.children):
children = self.children(self.id)
else:
children = self.children
self.info("Container get_children %r (%r,%r)", children, start, request_count)
if request_count == 0:
return children[start:]
else:
return children[start:request_count]
def get_child_count(self):
return len(self.get_children())
def get_item(self, parent_id=None):
item = DIDLLite.Container(self.id,self.parent_id,self.name)
item.childCount = self.get_child_count()
if self.store and self.play_container == True:
if item.childCount > 0:
res = DIDLLite.PlayContainerResource(self.store.server.uuid,cid=self.get_id(),fid=str(TRACK_COUNT + int(self.get_children()[0].get_id())))
item.res.append(res)
return item
def get_name(self):
return self.name
def get_id(self):
return self.id
class Playlist(BackendItem):
logCategory = 'rb_media_store'
def __init__(self, store, child, id):
self.id = id
self.store = store
# 2: RB_SOURCELIST_MODEL_COLUMN_NAME
# 3: RB_SOURCELIST_MODEL_COLUMN_SOURCE
self.title, self.source = self.store.playlist_model.get(child, 2, 3)
self.children = None
query = self.store.db.query_new()
self.store.db.query_append(query,
[ rhythmdb.QUERY_PROP_EQUALS,
rhythmdb.PROP_TYPE,
self.store.db.entry_type_get_by_name('song') ],
[ rhythmdb.QUERY_PROP_EQUALS,
rhythmdb.PROP_ALBUM,
self.title ])
def get_children(self, start=0, request_count=0):
if self.children == None:
self.children = map(self._create_track_from_playlist_item,
# who knows what the other children/magic numbers mean
self.source.get_children()[0].get_children()[1].get_children()[0].get_model())
return self.children
def _create_track_from_playlist_item(self, item):
uri = item[0].get_playback_uri()
entry = self.store.db.entry_lookup_by_location(uri)
id = self.store.db.entry_get(entry, rhythmdb.PROP_ENTRY_ID)
return Track(self.store, id, self.id)
def get_child_count(self):
try:
return len(self.get_children())
except:
return 0
def get_item(self):
item = DIDLLite.PlaylistContainer(self.id, AUDIO_PLAYLIST_CONTAINER_ID, self.title)
if __version_info__ >= (0,6,4):
if self.get_child_count() > 0:
res = DIDLLite.PlayContainerResource(self.store.server.uuid,cid=self.get_id(),fid=str(TRACK_COUNT+int(self.get_children()[0].get_id())))
item.res.append(res)
return item
def get_id(self):
return self.id
def get_name(self):
return self.title
class Album(BackendItem):
logCategory = 'rb_media_store'
def __init__(self, store, title, id, parent_id):
self.id = id
self.title = title
self.store = store
query = self.store.db.query_new()
self.store.db.query_append(query,[rhythmdb.QUERY_PROP_EQUALS, rhythmdb.PROP_TYPE, self.store.db.entry_type_get_by_name('song')],
[rhythmdb.QUERY_PROP_EQUALS, rhythmdb.PROP_ALBUM, self.title])
self.tracks_per_album_query = self.store.db.query_model_new(query)
#self.tracks_per_album_query.set_sort_order(rhythmdb.rhythmdb_query_model_track_sort_func)
self.store.db.do_full_query_async_parsed(self.tracks_per_album_query, query)
def get_children(self,start=0,request_count=0):
children = []
def track_sort(x,y):
entry = self.store.db.entry_lookup_by_id (x.id)
x_track = self.store.db.entry_get (entry, rhythmdb.PROP_TRACK_NUMBER)
entry = self.store.db.entry_lookup_by_id (y.id)
y_track = self.store.db.entry_get (entry, rhythmdb.PROP_TRACK_NUMBER)
return cmp(x_track,y_track)
def collate (model, path, iter):
self.info("Album get_children %r %r %r" %(model, path, iter))
id = model.get(iter, 0)[0]
children.append(Track(self.store,id,self.id))
self.tracks_per_album_query.foreach(collate)
children.sort(cmp=track_sort)
if request_count == 0:
return children[start:]
else:
return children[start:request_count]
def get_child_count(self):
return len(self.get_children())
def get_item(self, parent_id = AUDIO_ALBUM_CONTAINER_ID):
item = DIDLLite.MusicAlbum(self.id, parent_id, self.title)
if __version_info__ >= (0,6,4):
if self.get_child_count() > 0:
res = DIDLLite.PlayContainerResource(self.store.server.uuid,cid=self.get_id(),fid=str(TRACK_COUNT+int(self.get_children()[0].get_id())))
item.res.append(res)
return item
def get_id(self):
return self.id
def get_name(self):
return self.title
def get_cover(self):
return self.cover
class Artist(BackendItem):
logCategory = 'rb_media_store'
def __init__(self, store, name, id, parent_id):
self.id = id
self.name = name
self.store = store
query = self.store.db.query_new()
self.store.db.query_append(query,[rhythmdb.QUERY_PROP_EQUALS, rhythmdb.PROP_TYPE, self.store.db.entry_type_get_by_name('song')],
[rhythmdb.QUERY_PROP_EQUALS, rhythmdb.PROP_ARTIST, self.name])
self.tracks_per_artist_query = self.store.db.query_model_new(query)
self.store.db.do_full_query_async_parsed(self.tracks_per_artist_query, query)
self.albums_per_artist_query = self.store.db.property_model_new(rhythmdb.PROP_ALBUM)
self.albums_per_artist_query.props.query_model = self.tracks_per_artist_query
def get_artist_all_tracks(self,id):
children = []
def collate (model, path, iter):
id = model.get(iter, 0)[0]
print id
children.append(Track(self.store,id,self.id))
self.tracks_per_artist_query.foreach(collate)
return children
def get_children(self,start=0,request_count=0):
children = []
def collate (model, path, iter):
name = model.get(iter, 0)[0]
priority = model.get(iter, 1)[0]
self.info("get_children collate %r %r", name, priority)
if priority is False:
try:
album = self.store.albums[name]
children.append(album)
except:
self.warning("hmm, a new album %r, that shouldn't happen", name)
self.albums_per_artist_query.foreach(collate)
if len(children):
all_id = 'artist_all_tracks_%d' % (self.id)
if all_id not in self.store.containers:
self.store.containers[all_id] = \
Container( all_id, self.id, 'All tracks of %s' % self.name,
children_callback=self.get_artist_all_tracks,
store=self.store,play_container=True)
children.insert(0,self.store.containers[all_id])
if request_count == 0:
return children[start:]
else:
return children[start:request_count]
def get_child_count(self):
return len(self.get_children())
def get_item(self, parent_id = AUDIO_ARTIST_CONTAINER_ID):
item = DIDLLite.MusicArtist(self.id, parent_id, self.name)
return item
def get_id(self):
return self.id
def get_name(self):
return self.name
class Track(BackendItem):
logCategory = 'rb_media_store'
def __init__(self, store, id, parent_id):
self.store = store
if type(id) == int:
self.id = id
else:
self.id = self.store.db.entry_get (id, rhythmdb.PROP_ENTRY_ID)
self.parent_id = parent_id
def get_children(self, start=0, request_count=0):
return []
def get_child_count(self):
return 0
def get_item(self, parent_id=None):
self.info("Track get_item %r @ %r" %(self.id,self.parent_id))
host = ""
# load common values
entry = self.store.db.entry_lookup_by_id(self.id)
# Bitrate is in bytes/second, not kilobits/second
bitrate = self.store.db.entry_get(entry, rhythmdb.PROP_BITRATE) * 1024 / 8
# Duration is in HH:MM:SS format
seconds = self.store.db.entry_get(entry, rhythmdb.PROP_DURATION)
hours = seconds / 3600
seconds = seconds - hours * 3600
minutes = seconds / 60
seconds = seconds - minutes * 60
duration = ("%02d:%02d:%02d") % (hours, minutes, seconds)
location = self.get_path(entry)
mimetype = self.store.db.entry_get(entry, rhythmdb.PROP_MIMETYPE)
# This isn't a real mime-type
if mimetype == "application/x-id3":
mimetype = "audio/mpeg"
size = self.store.db.entry_get(entry, rhythmdb.PROP_FILE_SIZE)
album = self.store.db.entry_get(entry, rhythmdb.PROP_ALBUM)
if self.parent_id == None:
try:
self.parent_id = self.store.albums[album].id
except:
pass
# create item
item = DIDLLite.MusicTrack(self.id + TRACK_COUNT,self.parent_id)
item.album = album
item.artist = self.store.db.entry_get(entry, rhythmdb.PROP_ARTIST)
#item.date =
item.genre = self.store.db.entry_get(entry, rhythmdb.PROP_GENRE)
item.originalTrackNumber = str(self.store.db.entry_get (entry, rhythmdb.PROP_TRACK_NUMBER))
item.title = self.store.db.entry_get(entry, rhythmdb.PROP_TITLE) # much nicer if it was entry.title
cover = self.store.db.entry_request_extra_metadata(entry, "rb:coverArt-uri")
#self.warning("cover for %r is %r", item.title, cover)
if cover != None:
_,ext = os.path.splitext(cover)
item.albumArtURI = ''.join((self.get_url(),'?cover',ext))
# add http resource
res = DIDLLite.Resource(self.get_url(), 'http-get:*:%s:*' % mimetype)
if size > 0:
res.size = size
if duration > 0:
res.duration = str(duration)
if bitrate > 0:
res.bitrate = str(bitrate)
item.res.append(res)
# add internal resource
res = DIDLLite.Resource('track-%d' % self.id, 'rhythmbox:%s:%s:*' % (self.store.server.coherence.hostname, mimetype))
if size > 0:
res.size = size
if duration > 0:
res.duration = str(duration)
if bitrate > 0:
res.bitrate = str(bitrate)
item.res.append(res)
return item
def get_id(self):
return self.id
def get_name(self):
entry = self.store.db.entry_lookup_by_id (self.id)
return self.store.db.entry_get(entry, rhythmdb.PROP_TITLE)
def get_url(self):
return self.store.urlbase + str(self.id + TRACK_COUNT)
def get_path(self, entry = None):
if entry is None:
entry = self.store.db.entry_lookup_by_id (self.id)
uri = self.store.db.entry_get(entry, rhythmdb.PROP_LOCATION)
self.info("Track get_path uri = %r", uri)
location = None
if uri.startswith("file://"):
location = unicode(urllib.unquote(uri[len("file://"):]))
self.info("Track get_path location = %r", location)
return location
def get_cover(self):
entry = self.store.db.entry_lookup_by_id(self.id)
cover = self.store.db.entry_request_extra_metadata(entry, "rb:coverArt-uri")
return cover
class MediaStore(BackendStore):
logCategory = 'rb_media_store'
implements = ['MediaServer']
def __init__(self, server, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.warning("__init__ MediaStore %r", kwargs)
self.db = kwargs['db']
self.plugin = kwargs['plugin']
self.wmc_mapping.update({'4': lambda : self.get_by_id(AUDIO_ALL_CONTAINER_ID), # all tracks
'7': lambda : self.get_by_id(AUDIO_ALBUM_CONTAINER_ID), # all albums
'6': lambda : self.get_by_id(AUDIO_ARTIST_CONTAINER_ID), # all artists
'14': lambda : self.get_by_id(AUDIO_PLAYLIST_CONTAINER_ID), # all playlists
})
self.next_id = CONTAINER_COUNT
self.albums = None
self.artists = None
self.tracks = None
self.playlists = None
self.urlbase = kwargs.get('urlbase','')
if( len(self.urlbase) > 0 and self.urlbase[len(self.urlbase)-1] != '/'):
self.urlbase += '/'
try:
self.name = kwargs['name']
except KeyError:
self.name = "Rhythmbox on %s" % self.server.coherence.hostname
query = self.db.query_new()
self.info(query)
self.db.query_append(query, [rhythmdb.QUERY_PROP_EQUALS, rhythmdb.PROP_TYPE, self.db.entry_type_get_by_name('song')])
qm = self.db.query_model_new(query)
self.db.do_full_query_async_parsed(qm, query)
self.album_query = self.db.property_model_new(rhythmdb.PROP_ALBUM)
self.album_query.props.query_model = qm
self.artist_query = self.db.property_model_new(rhythmdb.PROP_ARTIST)
self.artist_query.props.query_model = qm
self.playlist_model = self.plugin.shell.get_playlist_manager().props.display_page_model
self.containers = {}
self.containers[ROOT_CONTAINER_ID] = \
Container( ROOT_CONTAINER_ID,-1, "Rhythmbox on %s" % self.server.coherence.hostname)
self.containers[AUDIO_ALL_CONTAINER_ID] = \
Container( AUDIO_ALL_CONTAINER_ID,ROOT_CONTAINER_ID, 'All tracks',
children_callback=self.children_tracks,
store=self,play_container=True)
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_ALL_CONTAINER_ID])
self.containers[AUDIO_ALBUM_CONTAINER_ID] = \
Container( AUDIO_ALBUM_CONTAINER_ID,ROOT_CONTAINER_ID, 'Albums',
children_callback=self.children_albums)
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_ALBUM_CONTAINER_ID])
self.containers[AUDIO_ARTIST_CONTAINER_ID] = \
Container( AUDIO_ARTIST_CONTAINER_ID,ROOT_CONTAINER_ID, 'Artists',
children_callback=self.children_artists)
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_ARTIST_CONTAINER_ID])
self.containers[AUDIO_PLAYLIST_CONTAINER_ID] = \
Container( AUDIO_PLAYLIST_CONTAINER_ID,ROOT_CONTAINER_ID, 'Playlists',
children_callback=self.children_playlists)
self.containers[ROOT_CONTAINER_ID].add_child(self.containers[AUDIO_PLAYLIST_CONTAINER_ID])
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
def get_by_id(self,id):
self.info("looking for id %r", id)
if isinstance(id, basestring) and id.startswith('artist_all_tracks_'):
try:
return self.containers[id]
except:
return None
id = id.split('@',1)
item_id = id[0]
item_id = int(item_id)
if item_id < TRACK_COUNT:
try:
item = self.containers[item_id]
except KeyError:
item = None
else:
item = Track(self, (item_id - TRACK_COUNT),None)
return item
def get_next_container_id(self):
ret = self.next_id
self.next_id += 1
return ret
def upnp_init(self):
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo', [
'rhythmbox:%s:*:*' % self.server.coherence.hostname,
'http-get:*:audio/mpeg:*',
])
self.warning("__init__ MediaStore initialized")
def children_tracks(self, parent_id):
tracks = []
def track_cb (entry):
if self.db.entry_get (entry, rhythmdb.PROP_HIDDEN):
return
id = self.db.entry_get (entry, rhythmdb.PROP_ENTRY_ID)
track = Track(self, id, parent_id)
tracks.append(track)
self.db.entry_foreach_by_type (self.db.entry_type_get_by_name('song'), track_cb)
return tracks
def children_albums(self,parent_id):
albums = {}
self.info('children_albums')
def album_sort(x,y):
r = cmp(x.title,y.title)
self.info("sort %r - %r = %r", x.title, y.title, r)
return r
def collate (model, path, iter):
name = model.get(iter, 0)[0]
priority = model.get(iter, 1)[0]
self.info("children_albums collate %r %r", name, priority)
if priority is False:
id = self.get_next_container_id()
album = Album(self, name, id,parent_id)
self.containers[id] = album
albums[name] = album
if self.albums is None:
self.album_query.foreach(collate)
self.albums = albums
albums = self.albums.values() #.sort(cmp=album_sort)
albums.sort(cmp=album_sort)
return albums
def children_artists(self,parent_id):
artists = []
def collate (model, path, iter):
name = model.get(iter, 0)[0]
priority = model.get(iter, 1)[0]
if priority is False:
id = self.get_next_container_id()
artist = Artist(self,name, id,parent_id)
self.containers[id] = artist
artists.append(artist)
if self.artists is None:
self.artist_query.foreach(collate)
self.artists = artists
return self.artists
def children_playlists(self,killbug=False):
playlists = []
def playlist_sort(x,y):
r = cmp(x.title,y.title)
self.info("sort %r - %r = %r", x.title, y.title, r)
return r
def collate (model, path, iter, parent_path):
parent = model.iter_parent(iter)
if parent and model.get_path(parent) == parent_path:
id = self.get_next_container_id()
playlist = Playlist(self, iter, id)
self.containers[id] = playlist
playlists.append(playlist)
if self.playlists is None:
PLAYLISTS_PARENT = 2 # 0 -> Library, 1 -> Stores, 2 -> Playlists
parent = self.playlist_model.iter_nth_child(None, PLAYLISTS_PARENT)
parent_path = self.playlist_model.get_path(parent)
self.playlist_model.foreach(collate, parent_path)
self.playlists = playlists
self.playlists.sort(cmp=playlist_sort)
return self.playlists
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~devices~wan_connection_device_client.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2010 Frank Scholz <[email protected]>
from coherence.upnp.services.clients.wan_ip_connection_client import WANIPConnectionClient
from coherence.upnp.services.clients.wan_ppp_connection_client import WANPPPConnectionClient
from coherence import log
import coherence.extern.louie as louie
class WANConnectionDeviceClient(log.Loggable):
logCategory = 'igd_client'
def __init__(self, device):
self.device = device
self.device_type = self.device.get_friendly_device_type()
self.version = int(self.device.get_device_type_version())
self.icons = device.icons
self.wan_ip_connection = None
self.wan_ppp_connection = None
self.detection_completed = False
louie.connect(self.service_notified, signal='Coherence.UPnP.DeviceClient.Service.notified', sender=self.device)
for service in self.device.get_services():
if service.get_type() in ["urn:schemas-upnp-org:service:WANIPConnection:1"]:
self.wan_ip_connection = WANIPConnectionClient(service)
if service.get_type() in ["urn:schemas-upnp-org:service:WANPPPConnection:1"]:
self.wan_ppp_connection = WANPPPConnectionClient(service)
self.info("WANConnectionDevice %s" % (self.device.get_friendly_name()))
if self.wan_ip_connection:
self.info("WANIPConnection service available")
if self.wan_ppp_connection:
self.info("WANPPPConnection service available")
def remove(self):
self.info("removal of WANConnectionDeviceClient started")
if self.wan_ip_connection != None:
self.wan_ip_connection.remove()
if self.wan_ppp_connection != None:
self.wan_ppp_connection.remove()
def service_notified(self, service):
self.info("Service %r sent notification" % service);
if self.detection_completed == True:
return
if self.wan_ip_connection != None:
if not hasattr(self.wan_ip_connection.service, 'last_time_updated'):
return
if self.wan_ip_connection.service.last_time_updated == None:
return
if self.wan_ppp_connection != None:
if not hasattr(self.wan_ppp_connection.service, 'last_time_updated'):
return
if self.wan_ppp_connection.service.last_time_updated == None:
return
self.detection_completed = True
louie.send('Coherence.UPnP.EmbeddedDeviceClient.detection_completed', None,
self)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~gstreamer_renderer.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2006,2007,2008,2009 Frank Scholz <[email protected]>
from sets import Set
from twisted.internet import reactor, defer
from twisted.internet.task import LoopingCall
from twisted.python import failure
from coherence.upnp.core.soap_service import errorCode
from coherence.upnp.core import DIDLLite
import string
import os, platform
from StringIO import StringIO
import tokenize
import pygst
pygst.require('0.10')
import gst
import coherence.extern.louie as louie
from coherence.extern.simple_plugin import Plugin
from coherence import log
class Player(log.Loggable):
logCategory = 'gstreamer_player'
max_playbin_volume = 1.
def __init__(self, default_mimetype='audio/mpeg', audio_sink_name=None,
video_sink_name=None, audio_sink_options=None,
video_sink_options=None):
self.audio_sink_name = audio_sink_name or "autoaudiosink"
self.video_sink_name = video_sink_name or "autovideosink"
self.audio_sink_options = audio_sink_options or {}
self.video_sink_options = video_sink_options or {}
self.player = None
self.source = None
self.sink = None
self.bus = None
self.views = []
self.playing = False
self.duration = None
self.mimetype = default_mimetype
self.create_pipeline(self.mimetype)
def add_view(self,view):
self.views.append(view)
def remove_view(self,view):
self.views.remove(view)
def update(self,message=None):
for v in self.views:
v(message=message)
def _is_not_playbin2_friendly(self):
uname = platform.uname()[1]
result = False
if uname.startswith('Nokia'):
try:
device = uname.split("-")[1]
except:
device = "unknown"
result = device != "N900"
return result
def create_pipeline(self, mimetype):
self.debug("creating pipeline")
if self._is_not_playbin2_friendly():
self.bus = None
self.player = None
self.source = None
self.sink = None
if mimetype == 'application/ogg':
self.player = gst.parse_launch('gnomevfssrc name=source ! oggdemux ! ivorbisdec ! audioconvert ! dsppcmsink name=sink')
self.player.set_name('oggplayer')
self.set_volume = self.set_volume_dsp_pcm_sink
self.get_volume = self.get_volume_dsp_pcm_sink
elif mimetype == 'application/flac':
self.player = gst.parse_launch('gnomevfssrc name=source ! flacdemux ! flacdec ! audioconvert ! dsppcmsink name=sink')
self.player.set_name('flacplayer')
self.set_volume = self.set_volume_dsp_pcm_sink
self.get_volume = self.get_volume_dsp_pcm_sink
else:
self.player = gst.parse_launch('gnomevfssrc name=source ! id3lib ! dspmp3sink name=sink')
self.player.set_name('mp3player')
self.set_volume = self.set_volume_dsp_mp3_sink
self.get_volume = self.get_volume_dsp_mp3_sink
self.source = self.player.get_by_name('source')
self.sink = self.player.get_by_name('sink')
self.player_uri = 'location'
self.mute = self.mute_hack
self.unmute = self.unmute_hack
self.get_mute = self.get_mute_hack
else:
self.player = gst.element_factory_make('playbin2', 'player')
self.player_uri = 'uri'
self.source = self.sink = self.player
self.set_volume = self.set_volume_playbin
self.get_volume = self.get_volume_playbin
self.mute = self.mute_playbin
self.unmute = self.unmute_playbin
self.get_mute = self.get_mute_playbin
audio_sink = gst.element_factory_make(self.audio_sink_name)
self._set_props(audio_sink, self.audio_sink_options)
self.player.set_property("audio-sink", audio_sink)
video_sink = gst.element_factory_make(self.video_sink_name)
self._set_props(video_sink, self.video_sink_options)
self.player.set_property("video-sink", video_sink)
self.bus = self.player.get_bus()
self.player_clean = True
self.bus.connect('message', self.on_message)
self.bus.add_signal_watch()
self.update_LC = LoopingCall(self.update)
def _set_props(self, element, props):
for option, value in props.iteritems():
value = self._py_value(value)
element.set_property(option, value)
def _py_value(self, s):
value = None
g = tokenize.generate_tokens(StringIO(s).readline)
for toknum, tokval, _, _, _ in g:
if toknum == tokenize.NUMBER:
if '.' in tokval:
value = float(tokval)
else:
value = int(tokval)
elif toknum == tokenize.NAME:
value = tokval
if value is not None:
break
return value
def get_volume_playbin(self):
""" playbin volume is a double from 0.0 - 10.0
"""
volume = self.sink.get_property('volume')
return int((volume*100) / self.max_playbin_volume)
def set_volume_playbin(self, volume):
volume = int(volume)
if volume < 0:
volume=0
if volume > 100:
volume=100
volume = (volume * self.max_playbin_volume) / 100.
self.sink.set_property('volume', volume)
def get_volume_dsp_mp3_sink(self):
""" dspmp3sink volume is a n in from 0 to 65535
"""
volume = self.sink.get_property('volume')
return int(volume*100/65535)
def set_volume_dsp_mp3_sink(self, volume):
volume = int(volume)
if volume < 0:
volume=0
if volume > 100:
volume=100
self.sink.set_property('volume', volume*65535/100)
def get_volume_dsp_pcm_sink(self):
""" dspmp3sink volume is a n in from 0 to 65535
"""
volume = self.sink.get_property('volume')
return int(volume*100/65535)
def set_volume_dsp_pcm_sink(self, volume):
volume = int(volume)
if volume < 0:
volume=0
if volume > 100:
volume=100
self.sink.set_property('volume', volume*65535/100)
def mute_playbin(self):
self.player.set_property('mute', True)
def unmute_playbin(self):
self.player.set_property('mute', False)
def get_mute_playbin(self):
return self.player.get_property('mute')
def mute_hack(self):
if hasattr(self,'stored_volume'):
self.stored_volume = self.sink.get_property('volume')
self.sink.set_property('volume', 0)
else:
self.sink.set_property('mute', True)
def unmute_hack(self):
if hasattr(self,'stored_volume'):
self.sink.set_property('volume', self.stored_volume)
else:
self.sink.set_property('mute', False)
def get_mute_hack(self):
if hasattr(self,'stored_volume'):
muted = self.sink.get_property('volume') == 0
else:
try:
muted = self.sink.get_property('mute')
except TypeError:
if not hasattr(self,'stored_volume'):
self.stored_volume = self.sink.get_property('volume')
muted = self.stored_volume == 0
except:
muted = False
self.warning("can't get mute state")
return muted
def get_state(self):
return self.player.get_state()
def get_uri(self):
""" playbin2 has an empty uri property after a
pipeline stops, as the uri is nowdays the next
track to play, not the current one
"""
if self.player.get_name() != 'player':
return self.source.get_property(self.player_uri)
else:
try:
return self.current_uri
except:
return None
def set_uri(self,uri):
self.source.set_property(self.player_uri, uri.encode('utf-8'))
if self.player.get_name() == 'player':
self.current_uri = uri.encode('utf-8')
def on_message(self, bus, message):
#print "on_message", message
#print "from", message.src.get_name()
t = message.type
#print t
if t == gst.MESSAGE_ERROR:
err, debug = message.parse_error()
self.warning("Gstreamer error: %s,%r" % (err.message, debug))
if self.playing == True:
self.seek('-0')
#self.player.set_state(gst.STATE_READY)
elif t == gst.MESSAGE_TAG:
for key in message.parse_tag().keys():
self.tags[key] = message.structure[key]
#print self.tags
elif t == gst.MESSAGE_STATE_CHANGED:
if message.src == self.player:
old, new, pending = message.parse_state_changed()
#print "player (%s) state_change:" %(message.src.get_path_string()), old, new, pending
if new == gst.STATE_PLAYING:
self.playing = True
self.update_LC.start( 1, False)
self.update()
elif old == gst.STATE_PLAYING:
self.playing = False
try:
self.update_LC.stop()
except:
pass
self.update()
#elif new == gst.STATE_READY:
# self.update()
elif t == gst.MESSAGE_EOS:
self.debug("reached file end")
self.seek('-0')
self.update(message=gst.MESSAGE_EOS)
def query_position( self):
#print "query_position"
try:
position, format = self.player.query_position(gst.FORMAT_TIME)
except:
#print "CLOCK_TIME_NONE", gst.CLOCK_TIME_NONE
position = gst.CLOCK_TIME_NONE
position = 0
#print position
if self.duration == None:
try:
self.duration, format = self.player.query_duration(gst.FORMAT_TIME)
except:
self.duration = gst.CLOCK_TIME_NONE
self.duration = 0
#import traceback
#print traceback.print_exc()
#print self.duration
r = {}
if self.duration == 0:
self.duration = None
self.debug("duration unknown")
return r
r[u'raw'] = {u'position':unicode(str(position)), u'remaining':unicode(str(self.duration - position)), u'duration':unicode(str(self.duration))}
position_human = u'%d:%02d' % (divmod( position/1000000000, 60))
duration_human = u'%d:%02d' % (divmod( self.duration/1000000000, 60))
remaining_human = u'%d:%02d' % (divmod( (self.duration-position)/1000000000, 60))
r[u'human'] = {u'position':position_human, u'remaining':remaining_human, u'duration':duration_human}
r[u'percent'] = {u'position':position*100/self.duration, u'remaining':100-(position*100/self.duration)}
self.debug(r)
return r
def load( self, uri, mimetype):
self.debug("load --> %r %r" % (uri, mimetype))
_,state,_ = self.player.get_state()
if( state == gst.STATE_PLAYING or state == gst.STATE_PAUSED):
self.stop()
#print "player -->", self.player.get_name()
if self.player.get_name() != 'player':
self.create_pipeline(mimetype)
self.player.set_state(gst.STATE_READY)
self.set_uri(uri)
self.player_clean = True
self.duration = None
self.mimetype = mimetype
self.tags = {}
#self.player.set_state(gst.STATE_PAUSED)
#self.update()
self.debug("load <--")
self.play()
def play( self):
uri = self.get_uri()
mimetype = self.mimetype
self.debug("play --> %r %r" % (uri, mimetype))
if self.player.get_name() != 'player':
if self.player_clean == False:
#print "rebuild pipeline"
self.player.set_state(gst.STATE_NULL)
self.create_pipeline(mimetype)
self.set_uri(uri)
self.player.set_state(gst.STATE_READY)
else:
self.player_clean = True
self.player.set_state(gst.STATE_PLAYING)
self.debug("play <--")
def pause(self):
self.debug("pause --> %r" % self.get_uri())
self.player.set_state(gst.STATE_PAUSED)
self.debug("pause <--")
def stop(self):
self.debug("stop --> %r" % self.get_uri())
self.seek('-0')
self.player.set_state(gst.STATE_READY)
self.update(message=gst.MESSAGE_EOS)
self.debug("stop <-- %r " % self.get_uri())
def seek(self, location):
"""
@param location: simple number = time to seek to, in seconds
+nL = relative seek forward n seconds
-nL = relative seek backwards n seconds
"""
_,state,_ = self.player.get_state()
if state != gst.STATE_PAUSED:
self.player.set_state(gst.STATE_PAUSED)
l = long(location)*1000000000
p = self.query_position()
#print p['raw']['position'], l
if location[0] == '+':
l = long(p[u'raw'][u'position']) + (long(location[1:])*1000000000)
l = min( l, long(p[u'raw'][u'duration']))
elif location[0] == '-':
if location == '-0':
l = 0L
else:
l = long(p[u'raw'][u'position']) - (long(location[1:])*1000000000)
l = max( l, 0L)
self.debug("seeking to %r" % l)
"""
self.player.seek( 1.0, gst.FORMAT_TIME,
gst.SEEK_FLAG_FLUSH | gst.SEEK_FLAG_ACCURATE,
gst.SEEK_TYPE_SET, l,
gst.SEEK_TYPE_NONE, 0)
"""
event = gst.event_new_seek(1.0, gst.FORMAT_TIME,
gst.SEEK_FLAG_FLUSH | gst.SEEK_FLAG_KEY_UNIT,
gst.SEEK_TYPE_SET, l,
gst.SEEK_TYPE_NONE, 0)
res = self.player.send_event(event)
if res:
pass
#print "setting new stream time to 0"
#self.player.set_new_stream_time(0L)
elif location != '-0':
print "seek to %r failed" % location
if location == '-0':
content_type, _ = self.mimetype.split("/")
try:
self.update_LC.stop()
except:
pass
if self.player.get_name() != 'player':
self.player.set_state(gst.STATE_NULL)
self.player_clean = False
elif content_type != "image":
self.player.set_state(gst.STATE_READY)
self.update()
else:
self.player.set_state(state)
if state == gst.STATE_PAUSED:
self.update()
class GStreamerPlayer(log.Loggable,Plugin):
""" a backend with a GStreamer based audio player
needs gnomevfssrc from gst-plugins-base
unfortunately gnomevfs has way too much dependencies
# not working -> http://bugzilla.gnome.org/show_bug.cgi?id=384140
# needs the neonhttpsrc plugin from gst-plugins-bad
# tested with CVS version
# and with this patch applied
# --> http://bugzilla.gnome.org/show_bug.cgi?id=375264
# not working
and id3demux from gst-plugins-good CVS too
"""
logCategory = 'gstreamer_player'
implements = ['MediaRenderer']
vendor_value_defaults = {'RenderingControl': {'A_ARG_TYPE_Channel':'Master'},
'AVTransport': {'A_ARG_TYPE_SeekMode':('ABS_TIME','REL_TIME','TRACK_NR')}}
vendor_range_defaults = {'RenderingControl': {'Volume': {'maximum':100}}}
def __init__(self, device, **kwargs):
if(device.coherence.config.get('use_dbus','no') != 'yes' and
device.coherence.config.get('glib','no') != 'yes'):
raise Exception('this media renderer needs use_dbus enabled in the configuration')
self.name = kwargs.get('name','GStreamer Audio Player')
audio_sink_name = kwargs.get("audio_sink_name")
audio_sink_options = kwargs.get("audio_sink_options")
video_sink_name = kwargs.get("video_sink_name")
video_sink_options = kwargs.get("video_sink_options")
self.player = Player(audio_sink_name=audio_sink_name,
video_sink_name=video_sink_name,
audio_sink_options=audio_sink_options,
video_sink_options=video_sink_options)
self.player.add_view(self.update)
self.metadata = None
self.duration = None
self.view = []
self.tags = {}
self.server = device
self.playcontainer = None
self.dlna_caps = ['playcontainer-0-1']
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
def __repr__(self):
return str(self.__class__).split('.')[-1]
def update(self, message=None):
_, current,_ = self.player.get_state()
self.debug("update current %r", current)
connection_manager = self.server.connection_manager_server
av_transport = self.server.av_transport_server
conn_id = connection_manager.lookup_avt_id(self.current_connection_id)
if current == gst.STATE_PLAYING:
state = 'playing'
av_transport.set_variable(conn_id, 'TransportState', 'PLAYING')
elif current == gst.STATE_PAUSED:
state = 'paused'
av_transport.set_variable(conn_id, 'TransportState',
'PAUSED_PLAYBACK')
elif self.playcontainer != None and message == gst.MESSAGE_EOS and \
self.playcontainer[0]+1 < len(self.playcontainer[2]):
state = 'transitioning'
av_transport.set_variable(conn_id, 'TransportState', 'TRANSITIONING')
next_track = ()
item = self.playcontainer[2][self.playcontainer[0]+1]
infos = connection_manager.get_variable('SinkProtocolInfo')
local_protocol_infos = infos.value.split(',')
res = item.res.get_matching(local_protocol_infos,
protocol_type='internal')
if len(res) == 0:
res = item.res.get_matching(local_protocol_infos)
if len(res) > 0:
res = res[0]
infos = res.protocolInfo.split(':')
remote_protocol, remote_network, remote_content_format, _ = infos
didl = DIDLLite.DIDLElement()
didl.addItem(item)
next_track = (res.data, didl.toString(), remote_content_format)
self.playcontainer[0] = self.playcontainer[0]+1
if len(next_track) == 3:
av_transport.set_variable(conn_id, 'CurrentTrack',
self.playcontainer[0]+1)
self.load(next_track[0], next_track[1], next_track[2])
self.play()
else:
state = 'idle'
av_transport.set_variable(conn_id, 'TransportState', 'STOPPED')
elif message == gst.MESSAGE_EOS and \
len(av_transport.get_variable('NextAVTransportURI').value) > 0:
state = 'transitioning'
av_transport.set_variable(conn_id, 'TransportState', 'TRANSITIONING')
CurrentURI = av_transport.get_variable('NextAVTransportURI').value
metadata = av_transport.get_variable('NextAVTransportURIMetaData')
CurrentURIMetaData = metadata.value
av_transport.set_variable(conn_id, 'NextAVTransportURI', '')
av_transport.set_variable(conn_id, 'NextAVTransportURIMetaData', '')
r = self.upnp_SetAVTransportURI(self, InstanceID=0,
CurrentURI=CurrentURI,
CurrentURIMetaData=CurrentURIMetaData)
if r == {}:
self.play()
else:
state = 'idle'
av_transport.set_variable(conn_id, 'TransportState', 'STOPPED')
else:
state = 'idle'
av_transport.set_variable(conn_id, 'TransportState', 'STOPPED')
self.info("update %r" % state)
self._update_transport_position(state)
def _update_transport_position(self, state):
connection_manager = self.server.connection_manager_server
av_transport = self.server.av_transport_server
conn_id = connection_manager.lookup_avt_id(self.current_connection_id)
position = self.player.query_position()
#print position
for view in self.view:
view.status(self.status(position))
if position.has_key(u'raw'):
if self.duration == None and 'duration' in position[u'raw']:
self.duration = int(position[u'raw'][u'duration'])
if self.metadata != None and len(self.metadata)>0:
# FIXME: duration breaks client parsing MetaData?
elt = DIDLLite.DIDLElement.fromString(self.metadata)
for item in elt:
for res in item.findall('res'):
formatted_duration = self._format_time(self.duration)
res.attrib['duration'] = formatted_duration
self.metadata = elt.toString()
#print self.metadata
if self.server != None:
av_transport.set_variable(conn_id,
'AVTransportURIMetaData',
self.metadata)
av_transport.set_variable(conn_id,
'CurrentTrackMetaData',
self.metadata)
self.info("%s %d/%d/%d - %d%%/%d%% - %s/%s/%s", state,
string.atol(position[u'raw'][u'position'])/1000000000,
string.atol(position[u'raw'][u'remaining'])/1000000000,
string.atol(position[u'raw'][u'duration'])/1000000000,
position[u'percent'][u'position'],
position[u'percent'][u'remaining'],
position[u'human'][u'position'],
position[u'human'][u'remaining'],
position[u'human'][u'duration'])
duration = string.atol(position[u'raw'][u'duration'])
formatted = self._format_time(duration)
av_transport.set_variable(conn_id, 'CurrentTrackDuration', formatted)
av_transport.set_variable(conn_id, 'CurrentMediaDuration', formatted)
position = string.atol(position[u'raw'][u'position'])
formatted = self._format_time(position)
av_transport.set_variable(conn_id, 'RelativeTimePosition', formatted)
av_transport.set_variable(conn_id, 'AbsoluteTimePosition', formatted)
def _format_time(self, time):
fmt = '%d:%02d:%02d'
try:
m, s = divmod(time / 1000000000, 60)
h, m = divmod(m, 60)
except:
h = m = s = 0
fmt = '%02d:%02d:%02d'
formatted = fmt % (h, m, s)
return formatted
def load( self, uri,metadata, mimetype=None):
self.info("loading: %r %r " % (uri, mimetype))
_,state,_ = self.player.get_state()
connection_id = self.server.connection_manager_server.lookup_avt_id(self.current_connection_id)
self.stop(silent=True) # the check whether a stop is really needed is done inside stop
if mimetype is None:
_,ext = os.path.splitext(uri)
if ext == '.ogg':
mimetype = 'application/ogg'
elif ext == '.flac':
mimetype = 'application/flac'
else:
mimetype = 'audio/mpeg'
self.player.load( uri, mimetype)
self.metadata = metadata
self.mimetype = mimetype
self.tags = {}
if self.playcontainer == None:
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURIMetaData',metadata)
self.server.av_transport_server.set_variable(connection_id, 'NumberOfTracks',1)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrack',1)
else:
self.server.av_transport_server.set_variable(connection_id, 'AVTransportURI',self.playcontainer[1])
self.server.av_transport_server.set_variable(connection_id, 'NumberOfTracks',len(self.playcontainer[2]))
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrack',self.playcontainer[0]+1)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackURI',uri)
self.server.av_transport_server.set_variable(connection_id, 'CurrentTrackMetaData',metadata)
#self.server.av_transport_server.set_variable(connection_id, 'TransportState', 'TRANSITIONING')
#self.server.av_transport_server.set_variable(connection_id, 'CurrentTransportActions','PLAY,STOP,PAUSE,SEEK,NEXT,PREVIOUS')
if uri.startswith('http://'):
transport_actions = Set(['PLAY,STOP,PAUSE'])
else:
transport_actions = Set(['PLAY,STOP,PAUSE,SEEK'])
if len(self.server.av_transport_server.get_variable('NextAVTransportURI').value) > 0:
transport_actions.add('NEXT')
if self.playcontainer != None:
if len(self.playcontainer[2]) - (self.playcontainer[0]+1) > 0:
transport_actions.add('NEXT')
if self.playcontainer[0] > 0:
transport_actions.add('PREVIOUS')
self.server.av_transport_server.set_variable(connection_id, 'CurrentTransportActions',transport_actions)
if state == gst.STATE_PLAYING:
self.info("was playing...")
self.play()
self.update()
def status( self, position):
uri = self.player.get_uri()
if uri == None:
return {u'state':u'idle',u'uri':u''}
else:
r = {u'uri':unicode(uri),
u'position':position}
if self.tags != {}:
try:
r[u'artist'] = unicode(self.tags['artist'])
except:
pass
try:
r[u'title'] = unicode(self.tags['title'])
except:
pass
try:
r[u'album'] = unicode(self.tags['album'])
except:
pass
if self.player.get_state()[1] == gst.STATE_PLAYING:
r[u'state'] = u'playing'
elif self.player.get_state()[1] == gst.STATE_PAUSED:
r[u'state'] = u'paused'
else:
r[u'state'] = u'idle'
return r
def start( self, uri):
self.load( uri)
self.play()
def stop(self,silent=False):
self.info('Stopping: %r' % self.player.get_uri())
if self.player.get_uri() == None:
return
if self.player.get_state()[1] in [gst.STATE_PLAYING,gst.STATE_PAUSED]:
self.player.stop()
if silent is True:
self.server.av_transport_server.set_variable(self.server.connection_manager_server.lookup_avt_id(self.current_connection_id), 'TransportState', 'STOPPED')
def play( self):
self.info("Playing: %r" % self.player.get_uri())
if self.player.get_uri() == None:
return
self.player.play()
self.server.av_transport_server.set_variable(self.server.connection_manager_server.lookup_avt_id(self.current_connection_id), 'TransportState', 'PLAYING')
def pause( self):
self.info('Pausing: %r' % self.player.get_uri())
self.player.pause()
self.server.av_transport_server.set_variable(self.server.connection_manager_server.lookup_avt_id(self.current_connection_id), 'TransportState', 'PAUSED_PLAYBACK')
def seek(self, location, old_state):
self.player.seek(location)
if old_state != None:
self.server.av_transport_server.set_variable(0, 'TransportState', old_state)
def mute(self):
self.player.mute()
rcs_id = self.server.connection_manager_server.lookup_rcs_id(self.current_connection_id)
self.server.rendering_control_server.set_variable(rcs_id, 'Mute', 'True')
def unmute(self):
self.player.unmute()
rcs_id = self.server.connection_manager_server.lookup_rcs_id(self.current_connection_id)
self.server.rendering_control_server.set_variable(rcs_id, 'Mute', 'False')
def get_mute(self):
return self.player.get_mute()
def get_volume(self):
return self.player.get_volume()
def set_volume(self, volume):
self.player.set_volume(volume)
rcs_id = self.server.connection_manager_server.lookup_rcs_id(self.current_connection_id)
self.server.rendering_control_server.set_variable(rcs_id, 'Volume', volume)
def playcontainer_browse(self,uri):
"""
dlna-playcontainer://uuid%3Afe814e3e-5214-4c24-847b-383fb599ff01?sid=urn%3Aupnp-org%3AserviceId%3AContentDirectory&cid=1441&fid=1444&fii=0&sc=&md=0
"""
from urllib import unquote
from cgi import parse_qs
from coherence.extern.et import ET
from coherence.upnp.core.utils import parse_xml
def handle_reply(r,uri,action,kw):
try:
next_track = ()
elt = DIDLLite.DIDLElement.fromString(r['Result'])
item = elt.getItems()[0]
local_protocol_infos=self.server.connection_manager_server.get_variable('SinkProtocolInfo').value.split(',')
res = item.res.get_matching(local_protocol_infos, protocol_type='internal')
if len(res) == 0:
res = item.res.get_matching(local_protocol_infos)
if len(res) > 0:
res = res[0]
remote_protocol,remote_network,remote_content_format,_ = res.protocolInfo.split(':')
didl = DIDLLite.DIDLElement()
didl.addItem(item)
next_track = (res.data,didl.toString(),remote_content_format)
""" a list with these elements:
the current track index
- will change during playback of the container items
the initial complete playcontainer-uri
a list of all the items in the playcontainer
the action methods to do the Browse call on the device
the kwargs for the Browse call
- kwargs['StartingIndex'] will be modified during further Browse requests
"""
self.playcontainer = [int(kw['StartingIndex']),uri,elt.getItems()[:],action,kw]
def browse_more(starting_index,number_returned,total_matches):
self.info("browse_more", starting_index,number_returned,total_matches)
try:
def handle_error(r):
pass
def handle_reply(r,starting_index):
elt = DIDLLite.DIDLElement.fromString(r['Result'])
self.playcontainer[2] += elt.getItems()[:]
browse_more(starting_index,int(r['NumberReturned']),int(r['TotalMatches']))
if((number_returned != 5 or
number_returned < (total_matches-starting_index)) and
(total_matches-number_returned) != starting_index):
self.info("seems we have been returned only a part of the result")
self.info("requested %d, starting at %d" % (5,starting_index))
self.info("got %d out of %d" % (number_returned, total_matches))
self.info("requesting more starting now at %d" % (starting_index+number_returned))
self.playcontainer[4]['StartingIndex'] = str(starting_index+number_returned)
d = self.playcontainer[3].call(**self.playcontainer[4])
d.addCallback(handle_reply,starting_index+number_returned)
d.addErrback(handle_error)
except:
import traceback
traceback.print_exc()
browse_more(int(kw['StartingIndex']),int(r['NumberReturned']),int(r['TotalMatches']))
if len(next_track) == 3:
return next_track
except:
import traceback
traceback.print_exc()
return failure.Failure(errorCode(714))
def handle_error(r):
return failure.Failure(errorCode(714))
try:
udn,args = uri[21:].split('?')
udn = unquote(udn)
args = parse_qs(args)
type = args['sid'][0].split(':')[-1]
try:
sc = args['sc'][0]
except:
sc = ''
device = self.server.coherence.get_device_with_id(udn)
service = device.get_service_by_type(type)
action = service.get_action('Browse')
kw = {'ObjectID':args['cid'][0],
'BrowseFlag':'BrowseDirectChildren',
'StartingIndex':args['fii'][0],
'RequestedCount':str(5),
'Filter':'*',
'SortCriteria':sc}
d = action.call(**kw)
d.addCallback(handle_reply,uri,action,kw)
d.addErrback(handle_error)
return d
except:
return failure.Failure(errorCode(714))
def upnp_init(self):
self.current_connection_id = None
self.server.connection_manager_server.set_variable(0, 'SinkProtocolInfo',
['internal:%s:audio/mpeg:*' % self.server.coherence.hostname,
'http-get:*:audio/mpeg:*',
'internal:%s:audio/mp4:*' % self.server.coherence.hostname,
'http-get:*:audio/mp4:*',
'internal:%s:application/ogg:*' % self.server.coherence.hostname,
'http-get:*:application/ogg:*',
'internal:%s:audio/ogg:*' % self.server.coherence.hostname,
'http-get:*:audio/ogg:*',
'internal:%s:video/ogg:*' % self.server.coherence.hostname,
'http-get:*:video/ogg:*',
'internal:%s:application/flac:*' % self.server.coherence.hostname,
'http-get:*:application/flac:*',
'internal:%s:audio/flac:*' % self.server.coherence.hostname,
'http-get:*:audio/flac:*',
'internal:%s:video/x-msvideo:*' % self.server.coherence.hostname,
'http-get:*:video/x-msvideo:*',
'internal:%s:video/mp4:*' % self.server.coherence.hostname,
'http-get:*:video/mp4:*',
'internal:%s:video/quicktime:*' % self.server.coherence.hostname,
'http-get:*:video/quicktime:*',
'internal:%s:image/gif:*' % self.server.coherence.hostname,
'http-get:*:image/gif:*',
'internal:%s:image/jpeg:*' % self.server.coherence.hostname,
'http-get:*:image/jpeg:*',
'internal:%s:image/png:*' % self.server.coherence.hostname,
'http-get:*:image/png:*',
'http-get:*:*:*'],
default=True)
self.server.av_transport_server.set_variable(0, 'TransportState', 'NO_MEDIA_PRESENT', default=True)
self.server.av_transport_server.set_variable(0, 'TransportStatus', 'OK', default=True)
self.server.av_transport_server.set_variable(0, 'CurrentPlayMode', 'NORMAL', default=True)
self.server.av_transport_server.set_variable(0, 'CurrentTransportActions', '', default=True)
self.server.rendering_control_server.set_variable(0, 'Volume', self.get_volume())
self.server.rendering_control_server.set_variable(0, 'Mute', self.get_mute())
def upnp_Play(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Speed = int(kwargs['Speed'])
self.play()
return {}
def upnp_Pause(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
self.pause()
return {}
def upnp_Stop(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
self.stop()
return {}
def upnp_Seek(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Unit = kwargs['Unit']
Target = kwargs['Target']
if InstanceID != 0:
return failure.Failure(errorCode(718))
if Unit in ['ABS_TIME','REL_TIME']:
old_state = self.server.av_transport_server.get_variable('TransportState').value
self.server.av_transport_server.set_variable(InstanceID, 'TransportState', 'TRANSITIONING')
sign = ''
if Target[0] == '+':
Target = Target[1:]
sign = '+'
if Target[0] == '-':
Target = Target[1:]
sign = '-'
h,m,s = Target.split(':')
seconds = int(h)*3600 + int(m)*60 + int(s)
self.seek(sign+str(seconds), old_state)
if Unit in ['TRACK_NR']:
if self.playcontainer == None:
NextURI = self.server.av_transport_server.get_variable('NextAVTransportURI',InstanceID).value
if NextURI != '':
self.server.av_transport_server.set_variable(InstanceID, 'TransportState', 'TRANSITIONING')
NextURIMetaData = self.server.av_transport_server.get_variable('NextAVTransportURIMetaData').value
self.server.av_transport_server.set_variable(InstanceID, 'NextAVTransportURI', '')
self.server.av_transport_server.set_variable(InstanceID, 'NextAVTransportURIMetaData', '')
r = self.upnp_SetAVTransportURI(self, InstanceID=InstanceID,CurrentURI=NextURI,CurrentURIMetaData=NextURIMetaData)
return r
else:
Target = int(Target)
if 0 < Target <= len(self.playcontainer[2]):
self.server.av_transport_server.set_variable(InstanceID, 'TransportState', 'TRANSITIONING')
next_track = ()
item = self.playcontainer[2][Target-1]
local_protocol_infos=self.server.connection_manager_server.get_variable('SinkProtocolInfo').value.split(',')
res = item.res.get_matching(local_protocol_infos, protocol_type='internal')
if len(res) == 0:
res = item.res.get_matching(local_protocol_infos)
if len(res) > 0:
res = res[0]
remote_protocol,remote_network,remote_content_format,_ = res.protocolInfo.split(':')
didl = DIDLLite.DIDLElement()
didl.addItem(item)
next_track = (res.data,didl.toString(),remote_content_format)
self.playcontainer[0] = Target-1
if len(next_track) == 3:
self.server.av_transport_server.set_variable(self.server.connection_manager_server.lookup_avt_id(self.current_connection_id), 'CurrentTrack',Target)
self.load(next_track[0],next_track[1],next_track[2])
self.play()
return {}
return failure.Failure(errorCode(711))
return {}
def upnp_Next(self,*args,**kwargs):
InstanceID = int(kwargs['InstanceID'])
track_nr = self.server.av_transport_server.get_variable('CurrentTrack')
return self.upnp_Seek(self,InstanceID=InstanceID,Unit='TRACK_NR',Target=str(int(track_nr.value)+1))
def upnp_Previous(self,*args,**kwargs):
InstanceID = int(kwargs['InstanceID'])
track_nr = self.server.av_transport_server.get_variable('CurrentTrack')
return self.upnp_Seek(self,InstanceID=InstanceID,Unit='TRACK_NR',Target=str(int(track_nr.value)-1))
def upnp_SetNextAVTransportURI(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
NextURI = kwargs['NextURI']
current_connection_id = self.server.connection_manager_server.lookup_avt_id(self.current_connection_id)
NextMetaData = kwargs['NextURIMetaData']
self.server.av_transport_server.set_variable(current_connection_id, 'NextAVTransportURI',NextURI)
self.server.av_transport_server.set_variable(current_connection_id, 'NextAVTransportURIMetaData',NextMetaData)
if len(NextURI) == 0 and self.playcontainer == None:
transport_actions = self.server.av_transport_server.get_variable('CurrentTransportActions').value
transport_actions = Set(transport_actions.split(','))
try:
transport_actions.remove('NEXT')
self.server.av_transport_server.set_variable(current_connection_id, 'CurrentTransportActions',transport_actions)
except KeyError:
pass
return {}
transport_actions = self.server.av_transport_server.get_variable('CurrentTransportActions').value
transport_actions = Set(transport_actions.split(','))
transport_actions.add('NEXT')
self.server.av_transport_server.set_variable(current_connection_id, 'CurrentTransportActions',transport_actions)
return {}
def upnp_SetAVTransportURI(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
CurrentURI = kwargs['CurrentURI']
CurrentURIMetaData = kwargs['CurrentURIMetaData']
#print "upnp_SetAVTransportURI",InstanceID, CurrentURI, CurrentURIMetaData
if CurrentURI.startswith('dlna-playcontainer://'):
def handle_result(r):
self.load(r[0],r[1],mimetype=r[2])
return {}
def pass_error(r):
return r
d = defer.maybeDeferred(self.playcontainer_browse,CurrentURI)
d.addCallback(handle_result)
d.addErrback(pass_error)
return d
elif len(CurrentURIMetaData)==0:
self.playcontainer = None
self.load(CurrentURI,CurrentURIMetaData)
return {}
else:
local_protocol_infos=self.server.connection_manager_server.get_variable('SinkProtocolInfo').value.split(',')
#print local_protocol_infos
elt = DIDLLite.DIDLElement.fromString(CurrentURIMetaData)
if elt.numItems() == 1:
item = elt.getItems()[0]
res = item.res.get_matching(local_protocol_infos, protocol_type='internal')
if len(res) == 0:
res = item.res.get_matching(local_protocol_infos)
if len(res) > 0:
res = res[0]
remote_protocol,remote_network,remote_content_format,_ = res.protocolInfo.split(':')
self.playcontainer = None
self.load(res.data,CurrentURIMetaData,mimetype=remote_content_format)
return {}
return failure.Failure(errorCode(714))
def upnp_SetMute(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Channel = kwargs['Channel']
DesiredMute = kwargs['DesiredMute']
if DesiredMute in ['TRUE', 'True', 'true', '1','Yes','yes']:
self.mute()
else:
self.unmute()
return {}
def upnp_SetVolume(self, *args, **kwargs):
InstanceID = int(kwargs['InstanceID'])
Channel = kwargs['Channel']
DesiredVolume = int(kwargs['DesiredVolume'])
self.set_volume(DesiredVolume)
return {}
if __name__ == '__main__':
import sys
p = Player(None)
if len(sys.argv) > 1:
reactor.callWhenRunning( p.start, sys.argv[1])
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~extern~telepathy~tubeconn.py | # Copyright (C) 2007 Collabora Ltd. <http://www.collabora.co.uk/>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# Modified by Philippe Normand.
from dbus.connection import Connection
from dbus import PROPERTIES_IFACE
from telepathy.interfaces import CHANNEL_TYPE_DBUS_TUBE
from coherence import log
class TubeConnection(Connection, log.Loggable):
logCategory = "tube_connection"
def __new__(cls, conn, tube, address, group_iface=None, mainloop=None):
self = super(TubeConnection, cls).__new__(cls, address,
mainloop=mainloop)
self._tube = tube
self.participants = {}
self.bus_name_to_handle = {}
self._mapping_watches = []
if group_iface is None:
method = conn.GetSelfHandle
else:
method = group_iface.GetSelfHandle
method(reply_handler=self._on_get_self_handle_reply,
error_handler=self._on_get_self_handle_error)
return self
def _on_get_self_handle_reply(self, handle):
self.self_handle = handle
tube_channel = self._tube[CHANNEL_TYPE_DBUS_TUBE]
match = tube_channel.connect_to_signal('DBusNamesChanged',
self._on_dbus_names_changed)
self._tube[PROPERTIES_IFACE].Get(CHANNEL_TYPE_DBUS_TUBE, 'DBusNames',
reply_handler=self._on_get_dbus_names_reply,
error_handler=self._on_get_dbus_names_error)
self._dbus_names_changed_match = match
def _on_get_self_handle_error(self, e):
self.warning('GetSelfHandle failed: %s', e)
def close(self):
self._dbus_names_changed_match.remove()
self._on_dbus_names_changed({}, self.participants.keys())
super(TubeConnection, self).close()
def _on_get_dbus_names_reply(self, names):
self._on_dbus_names_changed(names, ())
def _on_get_dbus_names_error(self, e):
self.warning('Get DBusNames property failed: %s', e)
def _on_dbus_names_changed(self, added, removed):
for handle, bus_name in added.items():
if handle == self.self_handle:
# I've just joined - set my unique name
self.set_unique_name(bus_name)
self.participants[handle] = bus_name
self.bus_name_to_handle[bus_name] = handle
# call the callback while the removed people are still in
# participants, so their bus names are available
for callback in self._mapping_watches:
callback(added, removed)
for handle in removed:
bus_name = self.participants.pop(handle, None)
self.bus_name_to_handle.pop(bus_name, None)
def watch_participants(self, callback):
self._mapping_watches.append(callback)
if self.participants:
# GetDBusNames already returned: fake a participant add event
# immediately
added = list(self.participants.iteritems())
callback(added, [])
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~extern~galleryremote~gallery.py | # Copyright (C) 2008 Jean-Michel Sizun <jm.sizun AT gmail>
#
# Copyright (C) 2008 Brent Woodruff
# http://www.fprimex.com
#
# Copyright (C) 2004 John Sutherland <[email protected]>
# http://garion.tzo.com/python/
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#
# Change log:
#
# 16-Nov-08 - Migrated from urllib to coherence infrastructure
#
# 04-Aug-08 - Added Gallery2 compatibility
# Changed fetch_albums and fetch_albums_prune to return dicts
# Added docstrings
# Created package and registered with Pypi
#
# 09-Jun-04 - Removed self.cookie='' from _doRequest to allow multiple
# transactions for each login.
# Fixed cut paste error in newAlbum.
# (both patches from Yuti Takhteyev
from coherence.upnp.core.utils import getPage
import StringIO
import string
class Gallery:
"""
The Gallery class implements the Gallery Remote protocol as documented
here:
http://codex.gallery2.org/Gallery_Remote:Protocol
The Gallery project is an open source web based photo album organizer
written in php. Gallery's web site is:
http://gallery.menalto.com/
This class is a 3rd party product which is not maintained by the
creators of the Gallery project.
Example usage:
from galleryremote import Gallery
my_gallery = Gallery('http://www.yoursite.com/gallery2', 2)
my_gallery.login('username','password')
albums = my_gallery.fetch_albums()
"""
def __init__(self, url, version=2):
"""
Create a Gallery for remote access.
url - base address of the gallery
version - version of the gallery being connected to (default 2),
either 1 for Gallery1 or 2 for Gallery2
"""
self.version = version # Gallery1 or Gallery2
if version == 1:
self.url = url + '/gallery_remote2.php'
else:
# default to G2
self.url = url + '/main.php'
self.auth_token = None
self.logged_in = 0
self.cookie = ''
self.protocol_version = '2.5'
def _do_request(self, request):
"""
Send a request, encoded as described in the Gallery Remote protocol.
request - a dictionary of protocol parameters and values
"""
if self.auth_token != None:
request['g2_authToken'] = self.auth_token
url = self.url
if (len(request) > 0) :
url += '?'
for key,value in request.iteritems():
url += '%s=%s&' % (key,value)
headers = None
if self.cookie != '':
headers = {'Cookie' : self.cookie}
def gotPage(result):
data,headers = result
response = self._parse_response( data )
if response['status'] != '0':
raise Exception(response['status_text'])
try:
self.auth_token = response['auth_token']
except:
pass
if headers.has_key('set-cookie'):
cookie_info = headers['set-cookie'][-1]
self.cookie = cookie_info.split(';')[0]
return response
def gotError(error):
print "Unable to process Gallery2 request: %s" % url
print "Error: %s" % error
return None
d = getPage(url, headers=headers)
d.addCallback(gotPage)
d.addErrback(gotError)
return d
def _parse_response(self, response):
"""
Decode the response from a request, returning a request dict
response - The response from a gallery request, encoded according
to the gallery remote protocol
"""
myStr = StringIO.StringIO(response)
for line in myStr:
if string.find( line, '#__GR2PROTO__' ) != -1:
break
# make sure the 1st line is #__GR2PROTO__
if string.find( line, '#__GR2PROTO__' ) == -1:
raise Exception("Bad response: %r" % response)
resDict = {}
for myS in myStr:
myS = myS.strip()
strList = string.split(myS, '=', 2)
try:
resDict[strList[0]] = strList[1]
except:
resDict[strList[0]] = ''
return resDict
def _get(self, response, kwd):
"""
"""
try:
retval = response[kwd]
except:
retval = ''
return retval
def login(self, username, password):
"""
Establish an authenticated session to the remote gallery.
username - A valid gallery user's username
password - That valid user's password
"""
if self.version == 1:
request = {
'protocol_version': self.protocol_version,
'cmd': 'login',
'uname': username,
'password': password
}
else:
request = {
'g2_controller' : 'remote:GalleryRemote',
'g2_form[protocol_version]' : self.protocol_version,
'g2_form[cmd]' : 'login',
'g2_form[uname]': username,
'g2_form[password]': password
}
def gotPage(result):
if result is None:
print "Unable to login as %s to gallery2 server (%s)" % (username, self.url)
return
self.logged_in = 1
d = self._do_request(request)
d.addCallbacks(gotPage)
return d
def fetch_albums(self):
"""
Obtain a dict of albums contained in the gallery keyed by
album name. In Gallery1, the name is alphanumeric. In Gallery2,
the name is the unique identifying number for that album.
"""
if self.version == 1:
request = {
'protocol_version' : self.protocol_version,
'cmd' : 'fetch-albums'
}
else:
request = {
'g2_controller' : 'remote:GalleryRemote',
'g2_form[protocol_version]' : self.protocol_version,
'g2_form[cmd]' : 'fetch-albums'
}
d = self._do_request(request)
def gotResponse(response):
if response is None:
print "Unable to retrieve list of albums!"
return None
albums = {}
for x in range(1, int(response['album_count']) + 1):
album = {}
album['name'] = self._get(response,'album.name.' + str(x))
album['title'] = self._get(response,'album.title.' + str(x))
album['summary'] = self._get(response,'album.summary.' + str(x))
album['parent'] = self._get(response,'album.parent.' + str(x))
album['resize_size'] = self._get(response,'album.resize_size.' + str(x))
album['perms.add'] = self._get(response,'album.perms.add.' + str(x))
album['perms.write'] = self._get(response,'album.perms.write.' + str(x))
album['perms.del_item'] = self._get(response,'album.perms.del_item.' + str(x))
album['perms.del_alb'] = self._get(response,'album.perms.del_alb.' + str(x))
album['perms.create_sub'] = self._get(response,'album.perms.create_sub.' + str(x))
album['perms.info.extrafields'] = self._get(response,'album.info.extrafields' + str(x))
albums[album['name']] = album
return albums
d.addCallback(gotResponse)
return d
def fetch_albums_prune(self):
"""
Obtain a dict of albums contained in the gallery keyed by
album name. In Gallery1, the name is alphanumeric. In Gallery2,
the name is the unique identifying number for that album.
From the protocol docs:
"The fetch_albums_prune command asks the server to return a list
of all albums that the user can either write to, or that are
visible to the user and contain a sub-album that is writable
(including sub-albums several times removed)."
"""
if self.version == 1:
request = {
'protocol_version' : self.protocol_version,
'cmd' : 'fetch-albums-prune'
}
else:
request = {
'g2_controller' : 'remote:GalleryRemote',
'g2_form[protocol_version]' : self.protocol_version,
'g2_form[cmd]' : 'fetch-albums-prune'
}
response = self._do_request(request)
def gotResponse(response):
# as long as it comes back here without an exception, we're ok.
albums = {}
for x in range(1, int(response['album_count']) + 1):
album = {}
album['name'] = self._get(response,'album.name.' + str(x))
album['title'] = self._get(response,'album.title.' + str(x))
album['summary'] = self._get(response,'album.summary.' + str(x))
album['parent'] = self._get(response,'album.parent.' + str(x))
album['resize_size'] = self._get(response,'album.resize_size.' + str(x))
album['perms.add'] = self._get(response,'album.perms.add.' + str(x))
album['perms.write'] = self._get(response,'album.perms.write.' + str(x))
album['perms.del_item'] = self._get(response,'album.perms.del_item.' + str(x))
album['perms.del_alb'] = self._get(response,'album.perms.del_alb.' + str(x))
album['perms.create_sub'] = self._get(response,'album.perms.create_sub.' + str(x))
album['perms.info.extrafields'] = self._get(response,'album.info.extrafields' + str(x))
albums[album['name']] = album
return albums
d.addCallback(gotResponse)
return d
def add_item(self, album, filename, caption, description):
"""
Add a photo to the specified album.
album - album name / identifier
filename - image to upload
caption - string caption to add to the image
description - string description to add to the image
"""
if self.version == 1:
request = {
'protocol_version' : self.protocol_version,
'cmd' : 'add-item',
'set_albumName' : album,
'userfile' : file,
'userfile_name' : filename,
'caption' : caption,
'extrafield.Description' : description
}
else:
request = {
'g2_form[protocol_version]' : self.protocol_version,
'g2_form[cmd]' : 'add-item',
'g2_form[set_albumName]' : album,
'g2_form[userfile]' : file,
'g2_form[userfile_name]' : filename,
'g2_form[caption]' : caption,
'g2_form[extrafield.Description]' : description
}
file = open(filename)
d = self._do_request(request)
# if we get here, everything went ok.
return d
def album_properties(self, album):
"""
Obtain album property information for the specified album.
album - the album name / identifier to obtain information for
"""
if self.version == 1:
request = {
'protocol_version' : self.protocol_version,
'cmd' : 'album-properties',
'set_albumName' : album
}
else:
request = {
'g2_controller' : 'remote:GalleryRemote',
'g2_form[protocol_version]' : self.protocol_version,
'g2_form[cmd]' : 'album-properties',
'g2_form[set_albumName]' : album
}
d = self._do_request(request)
def gotResponse(response):
res_dict = {}
if response.has_key('auto_resize'):
res_dict['auto_resize'] = response['auto_resize']
if response.has_key('add_to_beginning'):
res_dict['add_to_beginning'] = response['add_to_beginning']
return res_dict
d.addCallback(gotResponse)
return d
def new_album(self, parent, name=None, title=None, description=None):
"""
Add an album to the specified parent album.
parent - album name / identifier to contain the new album
name - unique string name of the new album
title - string title of the album
description - string description to add to the image
"""
if self.version == 1:
request = {
'g2_controller' : 'remote:GalleryRemote',
'protocol_version' : self.protocol_version,
'cmd' : 'new-album',
'set_albumName' : parent
}
if name != None:
request['newAlbumName'] = name
if title != None:
request['newAlbumTitle'] = title
if description != None:
request['newAlbumDesc'] = description
else:
request = {
'g2_controller' : 'remote:GalleryRemote',
'g2_form[protocol_version]' : self.protocol_version,
'g2_form[cmd]' : 'new-album',
'g2_form[set_albumName]' : parent
}
if name != None:
request['g2_form[newAlbumName]'] = name
if title != None:
request['g2_form[newAlbumTitle]'] = title
if description != None:
request['g2_form[newAlbumDesc]'] = description
d = self._do_request(request)
def gotResponse(response):
return response['album_name']
d.addCallback(d)
return d
def fetch_album_images(self, album):
"""
Get the image information for all images in the specified album.
album - specifies the album from which to obtain image information
"""
if self.version == 1:
request = {
'protocol_version' : self.protocol_version,
'cmd' : 'fetch-album-images',
'set_albumName' : album,
'albums_too' : 'no',
'extrafields' : 'yes'
}
else:
request = {
'g2_controller' : 'remote:GalleryRemote',
'g2_form[protocol_version]' : self.protocol_version,
'g2_form[cmd]' : 'fetch-album-images',
'g2_form[set_albumName]' : album,
'g2_form[albums_too]' : 'no',
'g2_form[extrafields]' : 'yes'
}
d = self._do_request(request)
def gotResponse (response):
if response is None:
print "Unable to retrieve list of item for album %s." % album
return None
images = []
for x in range(1, int(response['image_count']) + 1):
image = {}
image['name'] = self._get(response, 'image.name.' + str(x))
image['title'] = self._get(response, 'image.title.' + str(x))
image['raw_width'] = self._get(response, 'image.raw_width.' + str(x))
image['raw_height'] = self._get(response, 'image.raw_height.' + str(x))
image['resizedName'] = self._get(response, 'image.resizedName.' + str(x))
image['resized_width'] = self._get(response, 'image.resized_width.' + str(x))
image['resized_height'] = self._get(response, 'image.resized_height.' + str(x))
image['thumbName'] = self._get(response, 'image.thumbName.' + str(x))
image['thumb_width'] = self._get(response, 'image.thumb_width.' + str(x))
image['thumb_height'] = self._get(response, 'image.thumb_height.' + str(x))
image['raw_filesize'] = self._get(response, 'image.raw_filesize.' + str(x))
image['caption'] = self._get(response, 'image.caption.' + str(x))
image['clicks'] = self._get(response, 'image.clicks.' + str(x))
image['capturedate.year'] = self._get(response, 'image.capturedate.year' + str(x))
image['capturedate.mon'] = self._get(response, 'image.capturedate.mon' + str(x))
image['capturedate.mday'] = self._get(response, 'image.capturedate.mday' + str(x))
image['capturedate.hours'] = self._get(response, 'image.capturedate.hours' + str(x))
image['capturedate.minutes'] = self._get(response, 'image.capturedate.minutes' + str(x))
image['capturedate.seconds'] = self._get(response, 'image.capturedate.seconds' + str(x))
image['description'] = self._get(response, 'image.extrafield.Description.' + str(x))
images.append(image)
return images
d.addCallback(gotResponse)
return d
def get_URL_for_image(self, gallery2_id):
url = '%s/main.php?g2_view=core.DownloadItem&g2_itemId=%s' % (self.url, gallery2_id)
return url
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~itv_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Backend to retrieve the video streams from Shoutcast TV
# Copyright 2007, Frank Scholz <[email protected]>
# Copyright 2008,2009 Jean-Michel Sizun <jmDOTsizunATfreeDOTfr>
from twisted.internet import defer,reactor
from twisted.web import server
from coherence.upnp.core import utils
from coherence.upnp.core import DIDLLite
from coherence.extern.simple_plugin import Plugin
from coherence import log
from coherence.backend import BackendItem, BackendStore
import zlib
from coherence.backend import BackendStore,BackendItem
ROOT_CONTAINER_ID = 0
SHOUTCAST_WS_URL = 'http://www.shoutcast.com/sbin/newtvlister.phtml?service=winamp2&no_compress=1'
SHOUTCAST_TUNEIN_URL = 'http://www.shoutcast.com/sbin/tunein-tvstation.pls?id=%s'
VIDEO_MIMETYPE = 'video/x-nsv'
class ProxyStream(utils.ReverseProxyUriResource, log.Loggable):
logCategory = 'itv'
stream_url = None
def __init__(self, uri):
self.stream_url = None
utils.ReverseProxyUriResource.__init__(self, uri)
def requestFinished(self, result):
""" self.connection is set in utils.ReverseProxyResource.render """
self.info("ProxyStream requestFinished")
if self.connection is not None:
self.connection.transport.loseConnection()
def render(self, request):
if self.stream_url is None:
def got_playlist(result):
if result is None:
self.warning('Error to retrieve playlist - nothing retrieved')
return requestFinished(result)
result = result[0].split('\n')
for line in result:
if line.startswith('File1='):
self.stream_url = line[6:].split(";")[0]
break
#print "stream URL:", self.stream_url
if self.stream_url is None:
self.warning('Error to retrieve playlist - inconsistent playlist file')
return requestFinished(result)
#self.resetUri(self.stream_url)
request.uri = self.stream_url
return self.render(request)
def got_error(error):
self.warning(error)
return None
playlist_url = self.uri
#print "playlist URL:", playlist_url
d = utils.getPage(playlist_url, timeout=20)
d.addCallbacks(got_playlist, got_error)
return server.NOT_DONE_YET
if request.clientproto == 'HTTP/1.1':
self.connection = request.getHeader('connection')
if self.connection:
tokens = map(str.lower, self.connection.split(' '))
if 'close' in tokens:
d = request.notifyFinish()
d.addBoth(self.requestFinished)
else:
d = request.notifyFinish()
d.addBoth(self.requestFinished)
return utils.ReverseProxyUriResource.render(self, request)
class Container(BackendItem):
def __init__(self, id, store, parent_id, title):
self.url = store.urlbase+str(id)
self.parent_id = parent_id
self.id = id
self.name = title
self.mimetype = 'directory'
self.update_id = 0
self.children = []
self.store = store
self.item = DIDLLite.Container(self.id, self.parent_id, self.name)
self.item.childCount = 0
self.sorted = False
def add_child(self, child):
id = child.id
if isinstance(child.id, basestring):
_,id = child.id.split('.')
if self.children is None:
self.children = []
self.children.append(child)
self.item.childCount += 1
self.sorted = False
def get_children(self, start=0, end=0):
if self.sorted == False:
def childs_sort(x,y):
r = cmp(x.name,y.name)
return r
self.children.sort(cmp=childs_sort)
self.sorted = True
if end != 0:
return self.children[start:end]
return self.children[start:]
def get_child_count(self):
if self.children is None:
return 0
return len(self.children)
def get_path(self):
return self.url
def get_item(self):
return self.item
def get_name(self):
return self.name
def get_id(self):
return self.id
class ITVItem(BackendItem):
logCategory = 'itv'
def __init__(self, store, id, obj, parent):
self.parent = parent
self.id = id
self.name = obj.get('name')
self.mimetype = obj.get('mimetype')
self.description = None
self.date = None
self.item = None
self.duration = None
self.store = store
self.url = self.store.urlbase + str(self.id)
self.stream_url = obj.get('url')
self.location = ProxyStream(self.stream_url)
def get_item(self):
if self.item == None:
self.item = DIDLLite.VideoItem(self.id, self.parent.id, self.name)
self.item.description = self.description
self.item.date = self.date
res = DIDLLite.Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
res.duration = self.duration
#res.size = 0 #None
self.item.res.append(res)
return self.item
def get_path(self):
return self.url
class ITVStore(BackendStore):
logCategory = 'itv'
implements = ['MediaServer']
description = ('Shoutcast TV', 'cexposes the list of video streams from Shoutcast TV.', None)
options = [{'option':'name', 'text':'Server Name:', 'type':'string','default':'my media','help': 'the name under this MediaServer shall show up with on other UPnP clients'},
{'option':'version','text':'UPnP Version:','type':'int','default':2,'enum': (2,1),'help': 'the highest UPnP version this MediaServer shall support','level':'advance'},
{'option':'uuid','text':'UUID Identifier:','type':'string','help':'the unique (UPnP) identifier for this MediaServer, usually automatically set','level':'advance'},
{'option':'genrelist','text':'Server URL','type':'string', 'default':SHOUTCAST_WS_URL}
]
def __init__(self, server, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.next_id = 1000
self.config = kwargs
self.name = kwargs.get('name','iTV')
self.update_id = 0
self.store = {}
self.wmc_mapping = {'4': 1000}
self.shoutcast_ws_url = self.config.get('genrelist',SHOUTCAST_WS_URL)
self.init_completed()
def __repr__(self):
return self.__class__.__name__
def storeItem(self, parent, item, id):
self.store[id] = item
parent.add_child(item)
def appendGenre( self, genre, parent):
id = self.getnextID()
item = Container(id, self, -1, genre)
self.storeItem(parent, item, id)
return item
def appendFeed( self, obj, parent):
id = self.getnextID()
item = ITVItem(self, id, obj, parent)
self.storeItem(parent, item, id)
return item
def len(self):
return len(self.store)
def get_by_id(self,id):
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
try:
return self.store[int(id)]
except (ValueError,KeyError):
pass
return None
def getnextID(self):
ret = self.next_id
self.next_id += 1
return ret
def upnp_init(self):
self.current_connection_id = None
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
['http-get:*:%s:*' % VIDEO_MIMETYPE,
],
default=True)
rootItem = Container(ROOT_CONTAINER_ID,self,-1, self.name)
self.store[ROOT_CONTAINER_ID] = rootItem
self.retrieveList_attemptCount = 0
self.retrieveList(rootItem)
def retrieveList(self, parent):
self.info("Retrieving Shoutcast TV listing...")
def got_page(result):
if self.retrieveList_attemptCount == 0:
self.info("Connection to ShoutCast service successful for TV listing")
else:
self.warning("Connection to ShoutCast service successful for TV listing after %d attempts." % self.retrieveList_attemptCount)
result = result[0]
result = utils.parse_xml(result, encoding='utf-8')
genres = []
stations = {}
for stationResult in result.findall('station'):
mimetype = VIDEO_MIMETYPE
station_id = stationResult.get('id')
bitrate = stationResult.get('br')
rating = stationResult.get('rt')
name = stationResult.get('name').encode('utf-8')
genre = stationResult.get('genre')
url = SHOUTCAST_TUNEIN_URL % (station_id)
if genres.count(genre) == 0:
genres.append(genre)
sameStation = stations.get(name)
if sameStation == None or bitrate>sameStation['bitrate']:
station = {'name':name,
'station_id':station_id,
'mimetype':mimetype,
'id':station_id,
'url':url,
'bitrate':bitrate,
'rating':rating,
'genre':genre }
stations[name] = station
genreItems = {}
for genre in genres:
genreItem = self.appendGenre(genre, parent)
genreItems[genre] = genreItem
for station in stations.values():
genre = station.get('genre')
parentItem = genreItems[genre]
self.appendFeed({'name':station.get('name'),
'mimetype':station['mimetype'],
'id':station.get('station_id'),
'url':station.get('url')},
parentItem)
def got_error(error):
self.warning("Connection to ShoutCast service failed. Will retry in 5s!")
self.debug("%r", error.getTraceback())
# will retry later
self.retrieveList_attemptCount += 1
reactor.callLater(5, self.retrieveList, parent=parent)
d = utils.getPage(self.shoutcast_ws_url)
d.addCallbacks(got_page, got_error)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~services~servers~switch_power_server.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
# Switch Power service
from twisted.web import resource
from twisted.python import failure
from twisted.internet import task
from coherence.upnp.core.soap_service import UPnPPublisher
from coherence.upnp.core.soap_service import errorCode
from coherence.upnp.core import service
from coherence import log
class SwitchPowerControl(service.ServiceControl,UPnPPublisher):
def __init__(self, server):
self.service = server
self.variables = server.get_variables()
self.actions = server.get_actions()
class SwitchPowerServer(service.ServiceServer, resource.Resource,
log.Loggable):
logCategory = 'switch_power_server'
def __init__(self, device, backend=None):
self.device = device
if backend == None:
backend = self.device.backend
resource.Resource.__init__(self)
service.ServiceServer.__init__(self, 'SwitchPower', self.device.version, backend)
self.control = SwitchPowerControl(self)
self.putChild(self.scpd_url, service.scpdXML(self, self.control))
self.putChild(self.control_url, self.control) | [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~iradio_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# a Shoutcast radio media server for the Coherence UPnP Framework
# (heavily revamped from the existing IRadio plugin)
# Copyright 2007, Frank Scholz <[email protected]>
# Copyright 2009-2010, Jean-Michel Sizun <jmDOTsizunATfreeDOTfr>
from twisted.internet import defer,reactor
from twisted.python.failure import Failure
from twisted.web import server
from coherence.upnp.core import utils
from coherence.upnp.core import DIDLLite
from coherence.upnp.core.DIDLLite import classChooser, Resource, DIDLElement
import coherence.extern.louie as louie
from coherence.extern.simple_plugin import Plugin
from coherence import log
from coherence.backend import BackendItem, BackendStore, Container, LazyContainer, AbstractBackendStore
from urlparse import urlsplit
SHOUTCAST_WS_URL = 'http://www.shoutcast.com/sbin/newxml.phtml'
genre_families = {
# genre hierarchy created from http://forums.winamp.com/showthread.php?s=&threadid=303231
"Alternative" : ["Adult Alternative", "Britpop", "Classic Alternative", "College", "Dancepunk", "Dream Pop", "Emo", "Goth", "Grunge", "Indie Pop", "Indie Rock", "Industrial", "Lo-Fi", "Modern Rock", "New Wave", "Noise Pop", "Post-Punk", "Power Pop", "Punk", "Ska", "Xtreme"],
"Blues" : ["Acoustic Blues", "Chicago Blues", "Contemporary Blues", "Country Blues", "Delta Blues", "Electric Blues", "Cajun/Zydeco" ],
"Classical" : [ "Baroque", "Chamber", "Choral", "Classical Period", "Early Classical", "Impressionist", "Modern", "Opera", "Piano", "Romantic", "Symphony" ],
"Country" : ["Alt-Country", "Americana", "Bluegrass", "Classic Country", "Contemporary Bluegrass", "Contemporary Country", "Honky Tonk", "Hot Country Hits", "Western" ],
"Easy Listening" : ["Exotica", "Light Rock", "Lounge", "Orchestral Pop", "Polka", "Space Age Pop" ],
"Electronic" : ["Acid House", "Ambient", "Big Beat", "Breakbeat", "Dance", "Demo", "Disco", "Downtempo", "Drum and Bass", "Electro", "Garage", "Hard House", "House", "IDM", "Remixes", "Jungle", "Progressive", "Techno", "Trance", "Tribal", "Trip Hop" ],
"Folk" : ["Alternative Folk", "Contemporary Folk", "Folk Rock", "New Acoustic", "Traditional Folk", "World Folk" ],
"Themes" : ["Adult", "Best Of", "Chill", "Experimental", "Female", "Heartache", "LGBT", "Love/Romance", "Party Mix", "Patriotic", "Rainy Day Mix", "Reality", "Sexy", "Shuffle", "Travel Mix", "Tribute", "Trippy", "Work Mix" ],
"Rap" : ["Alternative Rap", "Dirty South", "East Coast Rap", "Freestyle", "Hip Hop", "Gangsta Rap", "Mixtapes", "Old School", "Turntablism", "Underground Hip-Hop", "West Coast Rap"],
"Inspirational" : ["Christian", "Christian Metal", "Christian Rap", "Christian Rock", "Classic Christian", "Contemporary Gospel", "Gospel", "Praise/Worship", "Sermons/Services", "Southern Gospel", "Traditional Gospel" ],
"International" : ["African", "Afrikaans", "Arabic", "Asian", "Brazilian", "Caribbean", "Celtic", "European", "Filipino", "Greek", "Hawaiian/Pacific", "Hindi", "Indian", "Japanese", "Jewish", "Klezmer", "Mediterranean", "Middle Eastern", "North American", "Polskie", "Polska", "Soca", "South American", "Tamil", "Worldbeat", "Zouk" ],
"Jazz" : ["Acid Jazz", "Avant Garde", "Big Band", "Bop", "Classic Jazz", "Cool Jazz", "Fusion", "Hard Bop", "Latin Jazz", "Smooth Jazz", "Swing", "Vocal Jazz", "World Fusion" ],
"Latin" : ["Bachata", "Banda", "Bossa Nova", "Cumbia", "Latin Dance", "Latin Pop", "Latin Rap/Hip-Hop", "Latin Rock", "Mariachi", "Merengue", "Ranchera", "Reggaeton", "Regional Mexican", "Salsa", "Tango", "Tejano", "Tropicalia"],
"Metal" : ["Black Metal", "Classic Metal", "Extreme Metal", "Grindcore", "Hair Metal", "Heavy Metal", "Metalcore", "Power Metal", "Progressive Metal", "Rap Metal" ],
"New Age" : ["Environmental", "Ethnic Fusion", "Healing", "Meditation", "Spiritual" ],
"Decades" : ["30s", "40s", "50s", "60s", "70s", "80s", "90s"],
"Pop" : ["Adult Contemporary", "Barbershop", "Bubblegum Pop", "Dance Pop", "Idols", "Oldies", "JPOP", "Soft Rock", "Teen Pop", "Top 40", "World Pop" ],
"R&B/Urban" : ["Classic R&B", "Contemporary R&B", "Doo Wop", "Funk", "Motown", "Neo-Soul", "Quiet Storm", "Soul", "Urban Contemporary", "Reggae", "Contemporary Reggae", "Dancehall", "Dub", "Pop-Reggae", "Ragga", "Rock Steady", "Reggae Roots"],
"Rock" : ["Adult Album Alternative", "British Invasion", "Classic Rock", "Garage Rock", "Glam", "Hard Rock", "Jam Bands", "Piano Rock", "Prog Rock", "Psychedelic", "Rock & Roll", "Rockabilly", "Singer/Songwriter", "Surf"],
"Seasonal/Holiday" : ["Anniversary", "Birthday", "Christmas", "Halloween", "Hanukkah", "Honeymoon", "Valentine", "Wedding", "Winter"],
"Soundtracks" : ["Anime", "Bollywood", "Kids", "Original Score", "Showtunes", "Video Game Music"],
"Talk" : ["Comedy", "Community", "Educational", "Government", "News", "Old Time Radio", "Other Talk", "Political", "Public Radio", "Scanner", "Spoken Word", "Sports", "Technology", "Hardcore", "Eclectic", "Instrumental" ],
"Misc" : [],
}
synonym_genres = {
# TODO: extend list with entries from "Misc" which are clearly the same
"24h" : ["24h", "24hs"],
"80s" : ["80s", "80er"],
"Acid Jazz" : ["Acid", "Acid Jazz"],
"Adult" : ["Adult", "Adulto"],
"Alternative" : ["Alt", "Alternativa", "Alternative", "Alternativo"],
"Francais" : ["Francais", "French"],
"Heavy Metal" : ["Heavy Metal", "Heavy", "Metal"],
"Hip Hop" : ["Hip", "Hop", "Hippop", "Hip Hop"],
"Islam" : [ "Islam", "Islamic"],
"Italy" : ["Italia", "Italian", "Italiana", "Italo", "Italy"],
"Latina" : ["Latin", "Latina", "Latino" ],
}
useless_title_content =[
# TODO: extend list with title expressions which are clearly useless
" - [SHOUTcast.com]"
]
useless_genres = [
# TODO: extend list with entries from "Misc" which are clearly useless
"genres", "go", "here",
"Her", "Hbwa"
]
class PlaylistStreamProxy(utils.ReverseProxyUriResource, log.Loggable):
""" proxies audio streams published as M3U playlists (typically the case for shoutcast streams) """
logCategory = 'PlaylistStreamProxy'
stream_url = None
def __init__(self, uri):
self.stream_url = None
utils.ReverseProxyUriResource.__init__(self, uri)
def requestFinished(self, result):
""" self.connection is set in utils.ReverseProxyResource.render """
self.debug("ProxyStream requestFinished")
if self.connection is not None:
self.connection.transport.loseConnection()
def render(self, request):
if self.stream_url is None:
def got_playlist(result):
if result is None:
self.warning('Error to retrieve playlist - nothing retrieved')
return requestFinished(result)
result = result[0].split('\n')
for line in result:
if line.startswith('File1='):
self.stream_url = line[6:]
break
if self.stream_url is None:
self.warning('Error to retrieve playlist - inconsistent playlist file')
return requestFinished(result)
#self.resetUri(self.stream_url)
request.uri = self.stream_url
return self.render(request)
def got_error(error):
self.warning('Error to retrieve playlist - unable to retrieve data')
self.warning(error)
return None
playlist_url = self.uri
d = utils.getPage(playlist_url, timeout=20)
d.addCallbacks(got_playlist, got_error)
return server.NOT_DONE_YET
self.info("this is our render method",request.method, request.uri, request.client, request.clientproto)
self.info("render", request.getAllHeaders())
if request.clientproto == 'HTTP/1.1':
self.connection = request.getHeader('connection')
if self.connection:
tokens = map(str.lower, self.connection.split(' '))
if 'close' in tokens:
d = request.notifyFinish()
d.addBoth(self.requestFinished)
else:
d = request.notifyFinish()
d.addBoth(self.requestFinished)
return utils.ReverseProxyUriResource.render(self, request)
class IRadioItem(BackendItem):
logCategory = 'iradio'
def __init__(self, station_id, title, stream_url, mimetype):
self.station_id = station_id
self.name = title
self.mimetype = mimetype
self.stream_url = stream_url
self.location = PlaylistStreamProxy(self.stream_url)
self.item = None
def replace_by (self, item):
# do nothing: we suppose the replacement item is the same
return
def get_item(self):
if self.item == None:
upnp_id = self.get_id()
upnp_parent_id = self.parent.get_id()
self.item = DIDLLite.AudioBroadcast(upnp_id, upnp_parent_id, self.name)
res = Resource(self.url, 'http-get:*:%s:%s' % (self.mimetype,
';'.join(('DLNA.ORG_PN=MP3',
'DLNA.ORG_CI=0',
'DLNA.ORG_OP=01',
'DLNA.ORG_FLAGS=01700000000000000000000000000000'))))
res.size = 0 #None
self.item.res.append(res)
return self.item
def get_path(self):
self.url = self.store.urlbase + str(self.storage_id)
return self.url
def get_id(self):
return self.storage_id
class IRadioStore(AbstractBackendStore):
logCategory = 'iradio'
implements = ['MediaServer']
genre_parent_items = {} # will list the parent genre for every given genre
def __init__(self, server, **kwargs):
AbstractBackendStore.__init__(self,server,**kwargs)
self.name = kwargs.get('name','iRadioStore')
self.refresh = int(kwargs.get('refresh',60))*60
self.shoutcast_ws_url = self.config.get('genrelist',SHOUTCAST_WS_URL)
# set root item
root_item = Container(None, self.name)
self.set_root_item(root_item)
# set root-level genre family containers
# and populate the genre_parent_items dict from the family hierarchy information
for family, genres in genre_families.items():
family_item = self.append_genre(root_item, family)
if family_item is not None:
self.genre_parent_items[family] = root_item
for genre in genres:
self.genre_parent_items[genre] = family_item
# retrieve asynchronously the list of genres from the souhtcast server
# genres not already attached to a family will be attached to the "Misc" family
self.retrieveGenreList_attemptCount = 0
deferredRoot = self.retrieveGenreList()
# self.init_completed() # will be fired when the genre list is retrieved
def append_genre(self, parent, genre):
if genre in useless_genres:
return None
if synonym_genres.has_key(genre):
same_genres = synonym_genres[genre]
else:
same_genres = [genre]
title = genre.encode('utf-8')
family_item = LazyContainer(parent, title, genre, self.refresh, self.retrieveItemsForGenre, genres=same_genres, per_page=1)
# we will use a specific child items sorter
# in order to get the sub-genre containers first
def childs_sort(x,y):
if x.__class__ == y.__class__:
return cmp(x.name,y.name) # same class, we compare the names
else:
# the IRadioItem is deemed the lowest item class,
# other classes are compared by name (as usual)
if isinstance(x, IRadioItem):
return 1
elif isinstance(y, IRadioItem):
return -1
else:
return cmp(x.name,y.name)
family_item.sorting_method = childs_sort
parent.add_child(family_item, external_id=genre)
return family_item
def __repr__(self):
return self.__class__.__name__
def upnp_init(self):
self.current_connection_id = None
self.wmc_mapping = {'4': self.get_root_id()}
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
['http-get:*:audio/mpeg:*',
'http-get:*:audio/x-scpls:*'],
default=True)
# populate a genre container (parent) with the sub-genre containers
# and corresponding IRadio (list retrieved from the shoutcast server)
def retrieveItemsForGenre (self, parent, genres, per_page=1, offset=0, page=0):
genre = genres[page]
if page < len(genres)-1:
parent.childrenRetrievingNeeded = True
url = '%s?genre=%s' % (self.shoutcast_ws_url, genre)
if genre_families.has_key(genre):
family_genres = genre_families[genre]
for family_genre in family_genres:
self.append_genre(parent, family_genre)
def got_page(result):
self.info('connection to ShoutCast service successful for genre %s' % genre)
result = utils.parse_xml(result, encoding='utf-8')
tunein = result.find('tunein')
if tunein != None:
tunein = tunein.get('base','/sbin/tunein-station.pls')
prot,host_port,path,_,_ = urlsplit(self.shoutcast_ws_url)
tunein = prot + '://' + host_port + tunein
stations = {}
for stationResult in result.findall('station'):
mimetype = stationResult.get('mt')
station_id = stationResult.get('id')
bitrate = stationResult.get('br')
name = stationResult.get('name').encode('utf-8')
# remove useless substrings (eg. '[Shoutcast.com]' ) from title
for substring in useless_title_content:
name = name.replace(substring, "")
lower_name = name.lower()
url = '%s?id=%s' % (tunein, stationResult.get('id'))
sameStation = stations.get(lower_name)
if sameStation == None or bitrate>sameStation['bitrate']:
station = {'name':name,
'station_id':station_id,
'mimetype':mimetype,
'id':station_id,
'url':url,
'bitrate':bitrate }
stations[lower_name] = station
for station in stations.values():
station_id = station.get('station_id')
name = station.get('name')
url = station.get('url')
mimetype = station.get('mimetype')
item = IRadioItem(station_id, name, url, mimetype)
parent.add_child(item, external_id = station_id)
return True
def got_error(error):
self.warning("connection to ShoutCast service failed: %s" % url)
self.debug("%r", error.getTraceback())
parent.childrenRetrievingNeeded = True # we retry
return Failure("Unable to retrieve stations for genre" % genre)
d = utils.getPage(url)
d.addCallbacks(got_page, got_error)
return d
# retrieve the whole list of genres from the shoutcast server
# to complete the population of the genre families classification
# (genres not previously classified are put into the "Misc" family)
# ...and fire mediaserver init completion
def retrieveGenreList(self):
def got_page(result):
if self.retrieveGenreList_attemptCount == 0:
self.info("Connection to ShoutCast service successful for genre listing")
else:
self.warning("Connection to ShoutCast service successful for genre listing after %d attempts." % self.retrieveGenreList_attemptCount)
result = utils.parse_xml(result, encoding='utf-8')
genres = {}
main_synonym_genre = {}
for main_genre, sub_genres in synonym_genres.items():
genres[main_genre] = sub_genres
for genre in sub_genres:
main_synonym_genre[genre] = main_genre
for genre in result.findall('genre'):
name = genre.get('name')
if name not in main_synonym_genre:
genres[name] = [name]
main_synonym_genre[name] = name
for main_genre, sub_genres in genres.items():
if not self.genre_parent_items.has_key(main_genre):
genre_families["Misc"].append(main_genre)
self.init_completed()
def got_error(error):
self.warning("connection to ShoutCast service for genre listing failed - Will retry! %r", error)
self.debug("%r", error.getTraceback())
self.retrieveGenreList_attemptCount += 1
reactor.callLater(5, self.retrieveGenreList)
d = utils.getPage(self.shoutcast_ws_url)
d.addCallback(got_page)
d.addErrback(got_error)
return d
| [] |
2024-01-10 | opendreambox/python-coherence | misc~Nautilus~coherence_upnp_export_extension.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008 Frank Scholz <[email protected]>
""" Coherence and Nautilus bridge to export folders as a DLNA/UPnP MediaServer
usable as Nautilus Extension or a Script
for use an extension, copy it to ~/.nautilus/python-extensions
or for a system-wide installation to /usr/lib/nautilus/extensions-2.0/python
for us as a script put it into ~/.gnome2/nautilus-scripts with
a describing name of maybe "export as UPnP MediaServer"
connection to Coherence is established via DBus
when used as a script it will export every folder as
a separate MediaServer
the extension will use the same MediaServer over the lifetime of Nautilus
and just add new folders
"""
import sys
import os
import dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
import dbus.service
BUS_NAME = 'org.Coherence'
OBJECT_PATH = '/org/Coherence'
def do_export(name,directories):
bus = dbus.SessionBus()
coherence = bus.get_object(BUS_NAME,OBJECT_PATH)
r = coherence.add_plugin('FSStore',
{'name': name,
'content':','.join(directories)},
dbus_interface=BUS_NAME)
return r
try:
import nautilus
from urllib import unquote
class CoherenceExportExtension(nautilus.MenuProvider):
def __init__(self):
print "CoherenceExportExtension", os.getpid()
try:
from coherence.ui.av_widgets import DeviceExportWidget
self.ui = DeviceExportWidget(standalone=False)
self.ui_create()
except:
print "can't setup Coherence connection"
self.ui = None
def ui_destroy(self,*args):
self.window = None
def ui_create(self):
import pygtk
pygtk.require("2.0")
import gtk
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_default_size(350, 300)
self.window.set_title('Coherence DLNA/UPnP Share')
self.window.connect("delete_event", self.ui_destroy)
self.window.add(self.ui.build_ui(root=self.window))
def get_file_items(self, window, files):
if self.ui == None:
return
if len(files) == 0:
return
for file in files:
if not file.is_directory():
return
item = nautilus.MenuItem('CoherenceExportExtension::export_resources',
'Sharing as a MediaServer...',
'Share the selected folders as a DLNA/UPnP MediaServer')
item.connect('activate', self.export_resources, files)
return item,
def export_resources(self, menu, files):
if len(files) == 0:
return
self.build()
if self.window == None:
self.ui_create()
self.ui.add_files([unquote(file.get_uri()[7:]) for file in files])
self.window.show_all()
except ImportError:
pass
if __name__ == '__main__':
import os.path
files = [x for x in sys.argv[1:] if os.path.isdir(x)]
do_export('Nautilus',files)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~devices~dimmable_light.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
from twisted.internet import task
from twisted.internet import reactor
from twisted.web import resource, static
from coherence import __version__
from coherence.extern.et import ET, indent
from coherence.upnp.services.servers.switch_power_server import SwitchPowerServer
from coherence.upnp.services.servers.dimming_server import DimmingServer
from coherence.upnp.devices.basics import RootDeviceXML, DeviceHttpRoot, BasicDeviceMixin
import coherence.extern.louie as louie
from coherence import log
class HttpRoot(DeviceHttpRoot):
logCategory = 'dimmablelight'
class DimmableLight(log.Loggable,BasicDeviceMixin):
logCategory = 'dimmablelight'
device_type = 'DimmableLight'
version = 1
def fire(self,backend,**kwargs):
if kwargs.get('no_thread_needed',False) == False:
""" this could take some time, put it in a thread to be sure it doesn't block
as we can't tell for sure that every backend is implemented properly """
from twisted.internet import threads
d = threads.deferToThread(backend, self, **kwargs)
def backend_ready(backend):
self.backend = backend
def backend_failure(x):
self.warning('backend not installed, %s activation aborted' % self.device_type)
self.debug(x)
d.addCallback(backend_ready)
d.addErrback(backend_failure)
# FIXME: we need a timeout here so if the signal we wait for not arrives we'll
# can close down this device
else:
self.backend = backend(self, **kwargs)
def init_complete(self, backend):
if self.backend != backend:
return
self._services = []
self._devices = []
try:
self.switch_power_server = SwitchPowerServer(self)
self._services.append(self.switch_power_server)
except LookupError,msg:
self.warning( 'SwitchPowerServer', msg)
raise LookupError(msg)
try:
self.dimming_server = DimmingServer(self)
self._services.append(self.dimming_server)
except LookupError,msg:
self.warning( 'SwitchPowerServer', msg)
raise LookupError(msg)
upnp_init = getattr(self.backend, "upnp_init", None)
if upnp_init:
upnp_init()
self.web_resource = HttpRoot(self)
self.coherence.add_web_resource( str(self.uuid)[5:], self.web_resource)
version = self.version
while version > 0:
self.web_resource.putChild( 'description-%d.xml' % version,
RootDeviceXML( self.coherence.hostname,
str(self.uuid),
self.coherence.urlbase,
device_type=self.device_type, version=version,
friendly_name=self.backend.name,
model_description='Coherence UPnP %s' % self.device_type,
model_name='Coherence UPnP %s' % self.device_type,
services=self._services,
devices=self._devices,
icons=self.icons))
version -= 1
self.web_resource.putChild('SwitchPower', self.switch_power_server)
self.web_resource.putChild('Dimming', self.dimming_server)
for icon in self.icons:
if icon.has_key('url'):
if icon['url'].startswith('file://'):
self.web_resource.putChild(os.path.basename(icon['url']),
static.File(icon['url'][7:]))
self.register()
self.warning("%s %s (%s) activated with %s" % (self.backend.name, self.device_type, self.backend, str(self.uuid)[5:]))
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~extern~telepathy~client.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2009 Philippe Normand <[email protected]>
import time
import dbus.glib
from dbus import PROPERTIES_IFACE
from telepathy.client import Channel
from telepathy.interfaces import CONN_INTERFACE, CHANNEL_INTERFACE_GROUP, \
CHANNEL_TYPE_CONTACT_LIST, CHANNEL_TYPE_TEXT, CHANNEL_INTERFACE, \
CONNECTION, CONNECTION_INTERFACE_ALIASING, CHANNEL, CONNECTION_INTERFACE_CONTACTS, \
CONNECTION_INTERFACE_SIMPLE_PRESENCE, CHANNEL_INTERFACE_MESSAGES, \
CONNECTION_INTERFACE_REQUESTS, CHANNEL_INTERFACE_TUBE, CHANNEL_TYPE_DBUS_TUBE
from telepathy.constants import CONNECTION_HANDLE_TYPE_CONTACT, \
CONNECTION_HANDLE_TYPE_LIST, CONNECTION_HANDLE_TYPE_ROOM, \
CONNECTION_STATUS_CONNECTED, CONNECTION_STATUS_DISCONNECTED, \
CONNECTION_STATUS_CONNECTING, TUBE_CHANNEL_STATE_LOCAL_PENDING, \
TUBE_CHANNEL_STATE_REMOTE_PENDING, TUBE_CHANNEL_STATE_OPEN, \
TUBE_CHANNEL_STATE_NOT_OFFERED, HANDLE_TYPE_LIST
from coherence.extern.telepathy.tubeconn import TubeConnection
from coherence.extern.telepathy.connect import tp_connect
from coherence import log
from twisted.internet import defer
TUBE_STATE = {TUBE_CHANNEL_STATE_LOCAL_PENDING : 'local pending',
TUBE_CHANNEL_STATE_REMOTE_PENDING : 'remote pending',
TUBE_CHANNEL_STATE_OPEN : 'open',
TUBE_CHANNEL_STATE_NOT_OFFERED: 'not offered'}
DBUS_PROPERTIES = 'org.freedesktop.DBus.Properties'
class Client(log.Loggable):
logCategory = "tp_client"
def __init__(self, manager, protocol,
account, muc_id, conference_server=None, existing_client=False):
log.Loggable.__init__(self)
self.account = account
self.existing_client = existing_client
self.channel_text = None
self._unsent_messages = []
self._tube_conns = {}
self._tubes = {}
self._channels = []
self._pending_tubes = {}
self._text_channels = {}
self.joined = False
if self.existing_client:
self.muc_id = self.existing_client.muc_id
self.conn = self.existing_client.conn
self.ready_cb(self.conn)
self.connection_dfr = defer.succeed(self.conn)
else:
if protocol == 'local-xmpp':
self.muc_id = muc_id
else:
self.muc_id = "%s@%s" % (muc_id, conference_server)
self.connection_dfr = tp_connect(manager, protocol, account, self.ready_cb)
self.connection_dfr.addCallbacks(self._got_connection, self.error_cb)
def _got_connection(self, connection):
self.conn = connection
if connection.GetStatus() == CONNECTION_STATUS_DISCONNECTED:
connection.Connect()
return connection
def start(self):
pass
def stop(self):
if not self.existing_client:
try:
self.conn[CONNECTION].Disconnect()
except Exception, exc:
self.warning("Error while disconnecting: %s", exc)
def ready_cb(self, conn):
self.debug("ready callback")
self.self_handle = self.conn[CONN_INTERFACE].GetSelfHandle()
self.conn[CONNECTION_INTERFACE_REQUESTS].connect_to_signal("NewChannels",
self.new_channels_cb)
self.conn[CONNECTION].connect_to_signal('StatusChanged', self.status_changed_cb)
if not self.existing_client:
self.debug("connecting...")
self.conn[CONNECTION].Connect()
self.conn[CONNECTION].GetInterfaces(reply_handler=self.get_interfaces_cb,
error_handler=self.error_cb)
def error_cb(self, error):
print "Error:", error
def status_changed_cb(self, status, reason):
self.debug("status changed to %r: %r", status, reason)
if status == CONNECTION_STATUS_CONNECTING:
self.info('connecting')
elif status == CONNECTION_STATUS_CONNECTED:
self.info('connected')
elif status == CONNECTION_STATUS_DISCONNECTED:
self.info('disconnected')
def get_interfaces_cb(self, interfaces):
self.fill_roster()
def fill_roster(self):
self.info("Filling up the roster")
self.roster = {}
conn = self.conn
class ensure_channel_cb(object):
def __init__(self, parent, group):
self.parent = parent
self.group = group
def __call__(self, yours, path, properties):
channel = Channel(conn.service_name, path)
self.channel = channel
# request the list of members
channel[DBUS_PROPERTIES].Get(CHANNEL_INTERFACE_GROUP,
'Members',
reply_handler = self.members_cb,
error_handler = self.parent.error_cb)
def members_cb(self, handles):
# request information for this list of handles using the
# Contacts interface
conn[CONNECTION_INTERFACE_CONTACTS].GetContactAttributes(
handles, [
CONNECTION,
CONNECTION_INTERFACE_ALIASING,
CONNECTION_INTERFACE_SIMPLE_PRESENCE,
],
False,
reply_handler = self.get_contact_attributes_cb,
error_handler = self.parent.error_cb)
def get_contact_attributes_cb(self, attributes):
self.parent.roster[self.group] = attributes
if 'subscribe' in self.parent.roster and \
'publish' in self.parent.roster:
self.parent.join_muc()
def no_channel_available(error):
print error
for name in ('subscribe', 'publish'):
conn[CONNECTION_INTERFACE_REQUESTS].EnsureChannel({
CHANNEL + '.ChannelType' : CHANNEL_TYPE_CONTACT_LIST,
CHANNEL + '.TargetHandleType': HANDLE_TYPE_LIST,
CHANNEL + '.TargetID' : name,
},
reply_handler = ensure_channel_cb(self, name),
error_handler = no_channel_available)
def join_muc(self):
conn_obj = self.conn[CONN_INTERFACE]
# workaround to be sure that the muc service is fully resolved in
# Salut.
if conn_obj.GetProtocol() == "local-xmpp":
time.sleep(2)
muc_id = self.muc_id
self.info("joining MUC %r", muc_id)
if self.existing_client:
self.channel_text = self.existing_client.channel_text
self._text_channel_available()
self.new_channels_cb(self.existing_client._channels)
self._tubes = self.existing_client._pending_tubes
for path, tube in self._tubes.iteritems():
self.connect_tube_signals(tube)
self.got_tube(tube)
else:
conn_iface = self.conn[CONNECTION_INTERFACE_REQUESTS]
params = {CHANNEL_INTERFACE+".ChannelType": CHANNEL_TYPE_TEXT,
CHANNEL_INTERFACE+".TargetHandleType": CONNECTION_HANDLE_TYPE_ROOM,
CHANNEL_INTERFACE+".TargetID": muc_id}
def got_channel(chan_path, props):
self.channel_text = Channel(self.conn.dbus_proxy.bus_name, chan_path)
self._text_channel_available()
def got_error(exception):
self.warning("Could not join MUC: %s", exception)
conn_iface.CreateChannel(params,reply_handler=got_channel,
error_handler=got_error)
def _text_channel_available(self):
room_iface = self.channel_text[CHANNEL_INTERFACE_GROUP]
self.self_handle = room_iface.GetSelfHandle()
room_iface.connect_to_signal("MembersChanged", self.text_channel_members_changed_cb)
if self.self_handle in room_iface.GetMembers():
self.joined = True
self.muc_joined()
def new_channels_cb(self, channels):
self.debug("new channels %r", channels)
self._channels.extend(channels)
for path, props in channels:
self.debug("new channel with path %r and props %r", path, props)
channel_type = props[CHANNEL_INTERFACE + ".ChannelType"]
if channel_type == CHANNEL_TYPE_DBUS_TUBE:
tube = Channel(self.conn.dbus_proxy.bus_name, path)
self.connect_tube_signals(tube)
tube.props = props
self._tubes[path] = tube
self.got_tube(tube)
def connect_tube_signals(self, tube):
tube_iface = tube[CHANNEL_INTERFACE_TUBE]
state_changed = lambda state: self.tube_channel_state_changed_cb(tube,
state)
tube_iface.connect_to_signal("TubeChannelStateChanged", state_changed)
channel_iface = tube[CHANNEL_INTERFACE]
channel_iface.connect_to_signal("Closed",
lambda: self.tube_closed(tube))
def got_tube(self, tube):
props = tube.props
self.debug("got tube with props %r", props)
initiator_id = props[CHANNEL_INTERFACE + ".InitiatorID"]
service = props[CHANNEL_TYPE_DBUS_TUBE + ".ServiceName"]
state = tube[PROPERTIES_IFACE].Get(CHANNEL_INTERFACE_TUBE, 'State')
self.info("new D-Bus tube offered by %s. Service: %s. State: %s",
initiator_id, service, TUBE_STATE[state])
def tube_opened(self, tube):
tube_path = tube.object_path
state = tube[PROPERTIES_IFACE].Get(CHANNEL_INTERFACE_TUBE, 'State')
self.info("tube %r opened (state: %s)", tube_path, TUBE_STATE[state])
group_iface = self.channel_text[CHANNEL_INTERFACE_GROUP]
tube_address = tube.local_address
tube_conn = TubeConnection(self.conn, tube, tube_address,
group_iface=group_iface)
self._tube_conns[tube_path] = tube_conn
return tube_conn
def received_cb(self, id, timestamp, sender, type, flags, text):
channel_obj = self.channel_text[CHANNEL_TYPE_TEXT]
channel_obj.AcknowledgePendingMessages([id])
conn_obj = self.conn[telepathy.CONN_INTERFACE]
contact = conn_obj.InspectHandles(telepathy.HANDLE_TYPE_CONTACT,
[sender])[0]
self.info("Received message from %s: %s", contact, text)
def tube_channel_state_changed_cb(self, tube, state):
if state == TUBE_CHANNEL_STATE_OPEN:
self.tube_opened(tube)
def tube_closed(self, tube):
tube_path = tube.object_path
self.info("tube %r closed", tube_path)
self._tube_conns[tube_path].close()
del self._tube_conns[tube_path]
del self._tubes[tube_path]
def text_channel_members_changed_cb(self, message, added, removed,
local_pending, remote_pending,
actor, reason):
if self.self_handle in added and not self.joined:
self.joined = True
self.muc_joined()
def muc_joined(self):
self.info("MUC joined")
for msg in self._unsent_messages:
self.send_text(msg)
self._unsent_messages = []
def send_text(self, text):
if self.channel_text:
self.info("Sending text %r", text)
channel_obj = self.channel_text[CHANNEL_TYPE_TEXT]
channel_obj.Send(telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL, text)
else:
self.info("Queing text %r until muc is joined", text)
self._unsent_messages.append(text)
def send_message(self, target_handle, message):
channel = self._text_channels.get(target_handle)
if not channel:
conn_iface = self.conn[CONNECTION_INTERFACE_REQUESTS]
params = {CHANNEL_INTERFACE+".ChannelType": CHANNEL_TYPE_TEXT,
CHANNEL_INTERFACE+".TargetHandleType": CONNECTION_HANDLE_TYPE_CONTACT,
CHANNEL_INTERFACE+ ".TargetHandle": target_handle}
def got_channel(chan_path, props):
channel = Channel(self.conn.dbus_proxy.bus_name, chan_path)
self._text_channels[target_handle] = channel
self.send_message(target_handle, message)
def got_error(exception):
print exception
conn_iface.CreateChannel(params, reply_handler=got_channel, error_handler=got_error)
else:
new_message = [
{}, # let the CM fill in the headers
{
'content': message,
'content-type': 'text/plain',
},
]
channel[CHANNEL_INTERFACE_MESSAGES].SendMessage(new_message, 0,
reply_handler=self.send_message_cb,
error_handler=self.error_cb)
def send_message_cb (self, token):
print "Sending message with token %s" % token
| [
"text/plain"
] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~services~clients~test~test_switch_power_client.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
"""
Test cases for L{upnp.services.clients.switch_power_client}
"""
import os
from twisted.trial import unittest
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from coherence import __version__
from coherence.base import Coherence
from coherence.upnp.core.uuid import UUID
from coherence.upnp.devices.control_point import DeviceQuery
import coherence.extern.louie as louie
class TestSwitchPowerClient(unittest.TestCase):
def setUp(self):
louie.reset()
self.coherence = Coherence({'unittest':'yes','logmode':'error','subsystem_log':{'controlpoint':'error'},'controlpoint':'yes'})
self.uuid = UUID()
p = self.coherence.add_plugin('SimpleLight', name='test-light-%d'%os.getpid(),uuid=str(self.uuid))
def tearDown(self):
def cleaner(r):
self.coherence.clear()
return r
dl = self.coherence.shutdown()
dl.addBoth(cleaner)
return dl
def test_get_state(self):
""" tries to find the activated SimpleLight backend
and queries its state.
The state is expected to be "off"
"""
d = Deferred()
def the_result(r):
#print "the_result", r
self.assertEqual(str(self.uuid), r.udn)
call = r.client.switch_power.get_status()
def got_answer(r):
self.assertEqual(int(r['ResultStatus']), 0)
d.callback(None)
call.addCallback(got_answer)
self.coherence.ctrl.add_query(DeviceQuery('uuid', str(self.uuid), the_result, timeout=10, oneshot=True))
return d
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~feed_storage.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2009, Dominik Ruf <dominikruf at googlemail dot com>
from coherence.backend import BackendItem
from coherence.backend import BackendStore
from coherence.upnp.core import DIDLLite
from coherence.upnp.core.utils import ReverseProxyUriResource
from xml.etree.ElementTree import ElementTree
import urllib
import httplib
from urlparse import urlsplit
try:
import feedparser
except:
raise ImportError("""
This backend depends on the feedparser module.
You can get it at http://www.feedparser.org/.""")
MIME_TYPES_EXTENTION_MAPPING = {'mp3': 'audio/mpeg',}
ROOT_CONTAINER_ID = 0
AUDIO_ALL_CONTAINER_ID = 51
AUDIO_ARTIST_CONTAINER_ID = 52
AUDIO_ALBUM_CONTAINER_ID = 53
VIDEO_FOLDER_CONTAINER_ID = 54
class RedirectingReverseProxyUriResource(ReverseProxyUriResource):
def render(self, request):
self.uri = self.follow_redirect(self.uri)
self.resetUri(self.uri)
return ReverseProxyUriResource.render(self, request)
def follow_redirect(self, uri):
netloc, path, query, fragment = urlsplit(uri)[1:]
conn = httplib.HTTPConnection(netloc)
conn.request('HEAD', '%s?%s#%s' % (path, query, fragment))
res = conn.getresponse()
if(res.status == 301 or res.status == 302):
return self.follow_redirect(res.getheader('location'))
else:
return uri
class FeedStorageConfigurationException(Exception):
pass
class FeedContainer(BackendItem):
def __init__(self, parent_id, id, title):
self.id = id
self.parent_id = parent_id
self.name = title
self.mimetype = 'directory'
self.item = DIDLLite.Container(self.id, self.parent_id, self.name)
self.children = []
def get_children(self, start=0, end=0):
"""returns all the chidlren of this container"""
if end != 0:
return self.children[start:end]
return self.children[start:]
def get_child_count(self):
"""returns the number of children in this container"""
return len(self.children)
class FeedEnclosure(BackendItem):
def __init__(self, store, parent, id, title, enclosure):
self.store = store
self.parent = parent
self.external_id = id
self.name = title
self.location = RedirectingReverseProxyUriResource(enclosure.url.encode('latin-1'))
# doing this because some (Fraunhofer Podcast) feeds say there mime type is audio/x-mpeg
# which at least my XBOX doesn't like
ext = enclosure.url.rsplit('.', 1)[0]
if ext in MIME_TYPES_EXTENTION_MAPPING:
mime_type = MIME_TYPES_EXTENTION_MAPPING[ext]
else:
mime_type = enclosure.type
if(enclosure.type.startswith('audio')):
self.item = DIDLLite.AudioItem(id, parent, self.name)
elif(enclosure.type.startswith('video')):
self.item = DIDLLite.VideoItem(id, parent, self.name)
elif(enclosure.type.startswith('image')):
self.item = DIDLLite.ImageItem(id, parent, self.name)
res = DIDLLite.Resource("%s%d" % (store.urlbase, id), 'http-get:*:%s:*' % mime_type)
self.item.res.append(res)
class FeedStore(BackendStore):
"""a general feed store"""
logCategory = 'feed_store'
implements = ['MediaServer']
def __init__(self,server,**kwargs):
BackendStore.__init__(self,server,**kwargs)
self.name = kwargs.get('name', 'Feed Store')
self.urlbase = kwargs.get('urlbase','')
if( len(self.urlbase)>0 and
self.urlbase[len(self.urlbase)-1] != '/'):
self.urlbase += '/'
self.feed_urls = kwargs.get('feed_urls')
self.opml_url = kwargs.get('opml_url')
if(not(self.feed_urls or self.opml_url)):
raise FeedStorageConfigurationException("either feed_urls or opml_url has to be set")
if(self.feed_urls and self.opml_url):
raise FeedStorageConfigurationException("only feed_urls OR opml_url can be set")
self.server = server
self.refresh = int(kwargs.get('refresh', 1)) * (60 * 60) # TODO: not used yet
self.store = {}
self.wmc_mapping = {'4': str(AUDIO_ALL_CONTAINER_ID), # all tracks
'7': str(AUDIO_ALBUM_CONTAINER_ID), # all albums
'6': str(AUDIO_ARTIST_CONTAINER_ID), # all artists
'15': str(VIDEO_FOLDER_CONTAINER_ID), # all videos
}
self.store[ROOT_CONTAINER_ID] = FeedContainer(-1, ROOT_CONTAINER_ID, self.name)
self.store[AUDIO_ALL_CONTAINER_ID] = FeedContainer(-1, AUDIO_ALL_CONTAINER_ID, 'AUDIO_ALL_CONTAINER')
self.store[AUDIO_ALBUM_CONTAINER_ID] = FeedContainer(-1, AUDIO_ALBUM_CONTAINER_ID, 'AUDIO_ALBUM_CONTAINER')
self.store[VIDEO_FOLDER_CONTAINER_ID] = FeedContainer(-1, VIDEO_FOLDER_CONTAINER_ID, 'VIDEO_FOLDER_CONTAINER')
try:
self._update_data()
except Exception, e:
self.error('error while updateing the feed contant for %s: %s' % (self.name, str(e)))
self.init_completed()
def get_by_id(self,id):
"""returns the item according to the DIDLite id"""
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
try:
return self.store[int(id)]
except (ValueError,KeyError):
self.info("can't get item %d from %s feed storage" % (int(id), self.name))
return None
def _update_data(self):
"""get the feed xml, parse it, etc."""
feed_urls = []
if(self.opml_url):
tree = ElementTree(file=urllib.urlopen(self.opml_url))
body = tree.find('body')
for outline in body.findall('outline'):
feed_urls.append(outline.attrib['url'])
if(self.feed_urls):
feed_urls = self.feed_urls.split()
container_id = 100
item_id = 1001
for feed_url in feed_urls:
netloc, path, query, fragment = urlsplit(feed_url)[1:]
conn = httplib.HTTPConnection(netloc)
conn.request('HEAD', '%s?%s#%s' % (path, query, fragment))
res = conn.getresponse()
if res.status >= 400:
self.warning('error getting %s status code: %d' % (feed_url, res.status))
continue
fp_dict = feedparser.parse(feed_url)
name = fp_dict.feed.title
self.store[container_id] = FeedContainer(ROOT_CONTAINER_ID, container_id, name)
self.store[ROOT_CONTAINER_ID].children.append(self.store[container_id])
self.store[VIDEO_FOLDER_CONTAINER_ID].children.append(self.store[container_id])
self.store[AUDIO_ALBUM_CONTAINER_ID].children.append(self.store[container_id])
for item in fp_dict.entries:
for enclosure in item.enclosures:
self.store[item_id] = FeedEnclosure(self, container_id, item_id, '%04d - %s' % (item_id, item.title), enclosure)
self.store[container_id].children.append(self.store[item_id])
if enclosure.type.startswith('audio'):
self.store[AUDIO_ALL_CONTAINER_ID].children.append(self.store[item_id])
if not isinstance(self.store[container_id].item, DIDLLite.MusicAlbum):
self.store[container_id].item = DIDLLite.MusicAlbum(container_id, AUDIO_ALBUM_CONTAINER_ID, name)
item_id += 1
if container_id <= 1000:
container_id += 1
else:
raise Exception('to many containers')
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~core~ssdp.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2005, Tim Potter <[email protected]>
# Copyright 2006 John-Mark Gurney <[email protected]>
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006,2007,2008,2009 Frank Scholz <[email protected]>
#
# Implementation of a SSDP server under Twisted Python.
#
import random
import string
import sys
import time
import socket
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor, error
from twisted.internet import task
from twisted.web.http import datetimeToString
from coherence import log, SERVER_ID
import coherence.extern.louie as louie
SSDP_PORT = 1900
SSDP_ADDR = '239.255.255.250'
class SSDPServer(DatagramProtocol, log.Loggable):
"""A class implementing a SSDP server. The notifyReceived and
searchReceived methods are called when the appropriate type of
datagram is received by the server."""
logCategory = 'ssdp'
known = {}
_callbacks = {}
def __init__(self,test=False,interface=''):
# Create SSDP server
self.test = test
if self.test == False:
try:
self.port = reactor.listenMulticast(SSDP_PORT, self, listenMultiple=True)
#self.port.setLoopbackMode(1)
self.port.joinGroup(SSDP_ADDR,interface=interface)
self.resend_notify_loop = task.LoopingCall(self.resendNotify)
self.resend_notify_loop.start(777.0, now=False)
self.check_valid_loop = task.LoopingCall(self.check_valid)
self.check_valid_loop.start(333.0, now=False)
except error.CannotListenError, err:
self.warning("There seems to be already a SSDP server running on this host, no need starting a second one.")
self.active_calls = []
def shutdown(self):
for call in reactor.getDelayedCalls():
if call.func == self.send_it:
call.cancel()
if self.test == False:
if self.resend_notify_loop.running:
self.resend_notify_loop.stop()
if self.check_valid_loop.running:
self.check_valid_loop.stop()
'''Make sure we send out the byebye notifications.'''
for st in self.known:
if self.known[st]['MANIFESTATION'] == 'local':
self.doByebye(st)
def datagramReceived(self, data, (host, port)):
"""Handle a received multicast datagram."""
try:
header, payload = data.split('\r\n\r\n')[:2]
except ValueError, err:
print err
print 'Arggg,', data
import pdb; pdb.set_trace()
lines = header.split('\r\n')
cmd = string.split(lines[0], ' ')
lines = map(lambda x: x.replace(': ', ':', 1), lines[1:])
lines = filter(lambda x: len(x) > 0, lines)
headers = [string.split(x, ':', 1) for x in lines]
headers = dict(map(lambda x: (x[0].lower(), x[1]), headers))
self.msg('SSDP command %s %s - from %s:%d' % (cmd[0], cmd[1], host, port))
self.debug('with headers:', headers)
if cmd[0] == 'M-SEARCH' and cmd[1] == '*':
# SSDP discovery
self.discoveryRequest(headers, (host, port))
elif cmd[0] == 'NOTIFY' and cmd[1] == '*':
# SSDP presence
self.notifyReceived(headers, (host, port))
else:
self.warning('Unknown SSDP command %s %s from %s' % (cmd[0], cmd[1], host))
# make raw data available
# send out the signal after we had a chance to register the device
louie.send('UPnP.SSDP.datagram_received', None, data, host, port)
def register(self, manifestation, usn, st, location,
server=SERVER_ID,
cache_control='max-age=1800',
silent=False,
host=None):
"""Register a service or device that this SSDP server will
respond to."""
self.info('Registering %s (%s)' % (st, location))
root_usn = usn[:-len(st)-2]
root_st = 'upnp:rootdevice'
if not root_usn in self.known and st != root_st:
self.info("RootDevice registration enforced for %s!" %(usn,))
self.register(manifestation, root_usn, root_st, location, server, cache_control, silent, host)
self.known[usn] = {}
self.known[usn]['USN'] = usn
self.known[usn]['LOCATION'] = location
self.known[usn]['ST'] = st
self.known[usn]['EXT'] = ''
self.known[usn]['SERVER'] = server
self.known[usn]['CACHE-CONTROL'] = cache_control
self.known[usn]['MANIFESTATION'] = manifestation
self.known[usn]['SILENT'] = silent
self.known[usn]['HOST'] = host
self.known[usn]['last-seen'] = time.time()
self.msg(self.known[usn])
if manifestation == 'local':
self.doNotify(usn)
if st == 'upnp:rootdevice':
louie.send('Coherence.UPnP.SSDP.new_device', None, device_type=st, infos=self.known[usn])
#self.callback("new_device", st, self.known[usn])
def unRegister(self, usn):
self.msg("Un-registering %s" % usn)
st = self.known[usn]['ST']
if st == 'upnp:rootdevice':
louie.send('Coherence.UPnP.SSDP.removed_device', None, device_type=st, infos=self.known[usn])
#self.callback("removed_device", st, self.known[usn])
del self.known[usn]
def isKnown(self, usn):
return self.known.has_key(usn)
def notifyReceived(self, headers, (host, port)):
"""Process a presence announcement. We just remember the
details of the SSDP service announced."""
self.info('Notification from (%s,%d) for %s' % (host, port, headers['nt']))
self.debug('Notification headers:', headers)
if headers['nts'].strip() == 'ssdp:alive':
try:
self.known[headers['usn']]['last-seen'] = time.time()
self.debug('updating last-seen for %r' % headers['usn'])
except KeyError:
self.register('remote', headers['usn'], headers['nt'], headers['location'],
headers['server'], headers['cache-control'], host=host)
elif headers['nts'].strip() == 'ssdp:byebye':
if self.isKnown(headers['usn']):
self.unRegister(headers['usn'])
else:
self.warning('Unknown subtype %s for notification type %s (%s)' %
(headers['nts'], headers['nt'], headers))
louie.send('Coherence.UPnP.Log', None, 'SSDP', host, 'Notify %s for %s' % (headers['nts'], headers['usn']))
def send_it(self,response,destination,delay,usn):
self.info('send discovery response delayed by %ds for %s to %r' % (delay,usn,destination))
try:
self.transport.write(response,destination)
except (AttributeError,socket.error), msg:
self.info("failure sending out byebye notification: %r" % msg)
def discoveryRequest(self, headers, (host, port)):
"""Process a discovery request. The response must be sent to
the address specified by (host, port)."""
self.info('Discovery request from (%s,%d) for %s' % (host, port, headers['st']))
self.info('Discovery request for %s' % headers['st'])
louie.send('Coherence.UPnP.Log', None, 'SSDP', host, 'M-Search for %s' % headers['st'])
# Do we know about this service?
for i in self.known.values():
if i['MANIFESTATION'] == 'remote':
continue
if(headers['st'] == 'ssdp:all' and
i['SILENT'] == True):
continue
if( i['ST'] == headers['st'] or
headers['st'] == 'ssdp:all'):
response = []
response.append('HTTP/1.1 200 OK')
for k, v in i.items():
if k == 'USN':
usn = v
if k not in ('MANIFESTATION','SILENT','HOST'):
response.append('%s: %s' % (k, v))
response.append('DATE: %s' % datetimeToString())
response.extend(('', ''))
delay = random.randint(0, int(headers['mx']))
reactor.callLater(delay, self.send_it,
'\r\n'.join(response), (host, port), delay, usn)
def doNotify(self, usn):
"""Do notification"""
if self.known[usn]['SILENT'] == True:
return
self.info('Sending alive notification for %s' % usn)
resp = [ 'NOTIFY * HTTP/1.1',
'HOST: %s:%d' % (SSDP_ADDR, SSDP_PORT),
'NTS: ssdp:alive',
]
stcpy = dict(self.known[usn].iteritems())
stcpy['NT'] = stcpy['ST']
del stcpy['ST']
del stcpy['MANIFESTATION']
del stcpy['SILENT']
del stcpy['HOST']
del stcpy['last-seen']
resp.extend(map(lambda x: ': '.join(x), stcpy.iteritems()))
resp.extend(('', ''))
self.debug('doNotify content', resp)
try:
self.transport.write('\r\n'.join(resp), (SSDP_ADDR, SSDP_PORT))
self.transport.write('\r\n'.join(resp), (SSDP_ADDR, SSDP_PORT))
except (AttributeError,socket.error), msg:
self.info("failure sending out alive notification: %r" % msg)
def doByebye(self, usn):
"""Do byebye"""
self.info('Sending byebye notification for %s' % usn)
resp = [ 'NOTIFY * HTTP/1.1',
'HOST: %s:%d' % (SSDP_ADDR, SSDP_PORT),
'NTS: ssdp:byebye',
]
try:
stcpy = dict(self.known[usn].iteritems())
stcpy['NT'] = stcpy['ST']
del stcpy['ST']
del stcpy['MANIFESTATION']
del stcpy['SILENT']
del stcpy['HOST']
del stcpy['last-seen']
resp.extend(map(lambda x: ': '.join(x), stcpy.iteritems()))
resp.extend(('', ''))
self.debug('doByebye content', resp)
if self.transport:
try:
self.transport.write('\r\n'.join(resp), (SSDP_ADDR, SSDP_PORT))
except (AttributeError,socket.error), msg:
self.info("failure sending out byebye notification: %r" % msg)
except KeyError, msg:
self.debug("error building byebye notification: %r" % msg)
def resendNotify( self):
for usn in self.known:
if self.known[usn]['MANIFESTATION'] == 'local':
self.doNotify(usn)
def check_valid(self):
""" check if the discovered devices are still ok, or
if we haven't received a new discovery response
"""
self.debug("Checking devices/services are still valid")
removable = []
for usn in self.known:
if self.known[usn]['MANIFESTATION'] != 'local':
_,expiry = self.known[usn]['CACHE-CONTROL'].split('=')
expiry = int(expiry)
now = time.time()
last_seen = self.known[usn]['last-seen']
self.debug("Checking if %r is still valid - last seen %d (+%d), now %d" % (self.known[usn]['USN'],last_seen,expiry,now))
if last_seen + expiry + 30 < now:
self.debug("Expiring: %r" % self.known[usn])
if self.known[usn]['ST'] == 'upnp:rootdevice':
louie.send('Coherence.UPnP.SSDP.removed_device', None, device_type=self.known[usn]['ST'], infos=self.known[usn])
removable.append(usn)
while len(removable) > 0:
usn = removable.pop(0)
del self.known[usn]
def subscribe(self, name, callback):
self._callbacks.setdefault(name,[]).append(callback)
def unsubscribe(self, name, callback):
callbacks = self._callbacks.get(name,[])
if callback in callbacks:
callbacks.remove(callback)
self._callbacks[name] = callbacks
def callback(self, name, *args):
for callback in self._callbacks.get(name,[]):
callback(*args)
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~flickr_storage.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007,2008 Frank Scholz <[email protected]>
import time
import re
import os.path
import mimetools,mimetypes
from datetime import datetime
from email.Utils import parsedate_tz
try:
import hashlib
def md5(s):
m =hashlib.md5()
m.update(s)
return m.hexdigest()
except ImportError:
import md5 as oldmd5
def md5(s):
m=oldmd5.new()
m.update(s)
return m.hexdigest()
from twisted.python import failure
from twisted.web.xmlrpc import Proxy
from twisted.web import client
from twisted.internet import task
from twisted.python.filepath import FilePath
from coherence.upnp.core.utils import parse_xml, ReverseProxyResource
from coherence.upnp.core.DIDLLite import classChooser,Container,PhotoAlbum,Photo,ImageItem,Resource,DIDLElement
from coherence.upnp.core.DIDLLite import simple_dlna_tags, PlayContainerResource
from coherence.upnp.core.soap_proxy import SOAPProxy
from coherence.upnp.core.soap_service import errorCode
from coherence.upnp.core.utils import getPage
from coherence.backend import BackendItem, BackendStore
from coherence.extern.simple_plugin import Plugin
from coherence import log
from urlparse import urlsplit
ROOT_CONTAINER_ID = 0
INTERESTINGNESS_CONTAINER_ID = 100
RECENT_CONTAINER_ID = 101
FAVORITES_CONTAINER_ID = 102
GALLERY_CONTAINER_ID = 200
UNSORTED_CONTAINER_ID = 201
CONTACTS_CONTAINER_ID = 300
class FlickrAuthenticate(object):
def __init__(self,api_key,api_secret,frob,userid,password,perms):
from mechanize import Browser
browser = Browser()
browser.set_handle_robots(False)
browser.set_handle_refresh(True,max_time=1)
browser.set_handle_redirect(True)
api_sig = ''.join((api_secret,'api_key',api_key,'frob',frob,'perms',perms))
api_sig=md5(api_sig)
login_url = "http://flickr.com/services/auth/?api_key=%s&perms=%s&frob=%s&api_sig=%s" % (api_key,perms,frob,api_sig)
browser.open(login_url)
browser.select_form(name='login_form')
browser['login']=userid
browser['passwd']=password
browser.submit()
for form in browser.forms():
try:
if form['frob'] == frob:
browser.form = form
browser.submit()
break;
except:
pass
else:
raise Exception('no form for authentication found') # lame :-/
class ProxyImage(ReverseProxyResource):
def __init__(self, uri):
self.uri = uri
_,host_port,path,_,_ = urlsplit(uri)
if host_port.find(':') != -1:
host,port = tuple(host_port.split(':'))
port = int(port)
else:
host = host_port
port = 80
ReverseProxyResource.__init__(self, host, port, path)
class FlickrItem(log.Loggable):
logCategory = 'flickr_storage'
def __init__(self, id, obj, parent, mimetype, urlbase, UPnPClass,store=None,update=False,proxy=False):
self.id = id
self.real_url = None
self.obj = obj
self.upnp_class = UPnPClass
self.store = store
self.item = None
self.date = None
if isinstance(obj, str):
self.name = obj
if isinstance(self.id,basestring) and self.id.startswith('upload.'):
self.mimetype = mimetype
else:
self.mimetype = 'directory'
elif mimetype == 'directory':
title = obj.find('title')
self.name = title.text;
if len(self.name) == 0:
self.name = obj.get('id')
self.mimetype = 'directory'
elif mimetype == 'contact':
self.name = obj.get('realname')
if self.name == '':
self.name = obj.get('username')
self.nsid = obj.get('nsid')
self.mimetype = 'directory'
else:
self.name = obj.get('title') #.encode('utf-8')
if self.name == None:
self.name = obj.find('title')
if self.name != None:
self.name = self.name.text
if self.name == None or len(self.name) == 0:
self.name = 'untitled'
self.mimetype = 'image/jpeg'
self.parent = parent
if not (isinstance(self.id,basestring) and self.id.startswith('upload.')):
if parent:
parent.add_child(self,update=update)
if( len(urlbase) and urlbase[-1] != '/'):
urlbase += '/'
if self.mimetype == 'directory':
try:
self.flickr_id = obj.get('id')
except:
self.flickr_id = None
self.url = urlbase + str(self.id)
elif isinstance(self.id,basestring) and self.id.startswith('upload.'):
self.url = urlbase + str(self.id)
self.location = None
else:
self.flickr_id = obj.get('id')
try:
datetaken = obj.get('datetaken')
date,time = datetaken.split(' ')
year,month,day = date.split('-')
hour,minute,second = time.split(':')
self.date = datetime(int(year),int(month),int(day),int(hour),int(minute),int(second))
except:
import traceback
self.debug(traceback.format_exc())
self.real_url = "http://farm%s.static.flickr.com/%s/%s_%s.jpg" % (
obj.get('farm'),
obj.get('server'),
obj.get('id'),
obj.get('secret'))
if proxy == True:
self.url = urlbase + str(self.id)
self.location = ProxyImage(self.real_url)
else:
self.url = u"http://farm%s.static.flickr.com/%s/%s_%s.jpg" % (
obj.get('farm').encode('utf-8'),
obj.get('server').encode('utf-8'),
obj.get('id').encode('utf-8'),
obj.get('secret').encode('utf-8'))
if parent == None:
self.parent_id = -1
else:
self.parent_id = parent.get_id()
if self.mimetype == 'directory':
self.children = []
self.update_id = 0
def set_item_size_and_date(self):
def gotPhoto(result):
self.debug("gotPhoto", result)
_, headers = result
length = headers.get('content-length',None)
modified = headers.get('last-modified',None)
if length != None:
self.item.res[0].size = int(length[0])
if modified != None:
""" Tue, 06 Feb 2007 15:56:32 GMT """
self.item.date = datetime(*parsedate_tz(modified[0])[0:6])
def gotError(failure, url):
self.warning("error requesting", failure, url)
self.info(failure)
getPage(self.real_url,method='HEAD',timeout=60).addCallbacks(gotPhoto, gotError, None, None, [self.real_url], None)
def remove(self):
#print "FSItem remove", self.id, self.get_name(), self.parent
if self.parent:
self.parent.remove_child(self)
del self.item
def add_child(self, child, update=False):
self.children.append(child)
if update == True:
self.update_id += 1
def remove_child(self, child):
self.info("remove_from %d (%s) child %d (%s)" % (self.id, self.get_name(), child.id, child.get_name()))
if child in self.children:
self.children.remove(child)
self.update_id += 1
def get_children(self,start=0,request_count=0):
if request_count == 0:
return self.children[start:]
else:
return self.children[start:request_count]
def get_child_count(self):
return len(self.children)
def get_id(self):
return self.id
def get_location(self):
return self.location
def get_update_id(self):
if hasattr(self, 'update_id'):
return self.update_id
else:
return None
def get_path(self):
if isinstance(self.id,basestring) and self.id.startswith('upload.'):
return '/tmp/' + self.id # FIXME
return self.url
def get_name(self):
return self.name
def get_flickr_id(self):
return self.flickr_id
def get_child_by_flickr_id(self, flickr_id):
for c in self.children:
if flickr_id == c.flickr_id:
return c
return None
def get_parent(self):
return self.parent
def get_item(self):
if self.item == None:
if self.mimetype == 'directory':
self.item = self.upnp_class(self.id, self.parent_id, self.get_name())
self.item.childCount = self.get_child_count()
if self.get_child_count() > 0:
res = PlayContainerResource(self.store.server.uuid,cid=self.get_id(),fid=self.get_children()[0].get_id())
self.item.res.append(res)
else:
return self.create_item()
return self.item
def create_item(self):
def process(result):
for size in result.getiterator('size'):
#print size.get('label'), size.get('source')
if size.get('label') == 'Original':
self.original_url = (size.get('source'),size.get('width')+'x'+size.get('height'))
if self.store.proxy == False:
self.url = self.original_url[0]
else:
self.location = ProxyImage(self.original_url[0])
elif size.get('label') == 'Large':
self.large_url = (size.get('source'),size.get('width')+'x'+size.get('height'))
if self.store.proxy == False:
self.url = self.large_url[0]
else:
self.location = ProxyImage(self.large_url[0])
elif size.get('label') == 'Medium':
self.medium_url = (size.get('source'),size.get('width')+'x'+size.get('height'))
elif size.get('label') == 'Small':
self.small_url = (size.get('source'),size.get('width')+'x'+size.get('height'))
elif size.get('label') == 'Thumbnail':
self.thumb_url = (size.get('source'),size.get('width')+'x'+size.get('height'))
self.item = Photo(self.id,self.parent.get_id(),self.get_name())
#print self.id, self.store.proxy, self.url
self.item.date = self.date
self.item.attachments = {}
dlna_tags = simple_dlna_tags[:]
dlna_tags[3] = 'DLNA.ORG_FLAGS=00f00000000000000000000000000000'
if hasattr(self,'original_url'):
dlna_pn = 'DLNA.ORG_PN=JPEG_LRG'
if self.store.proxy == False:
res = Resource(self.original_url[0], 'http-get:*:%s:%s' % (self.mimetype,';'.join([dlna_pn]+dlna_tags)))
else:
res = Resource(self.url+'?attachment=original', 'http-get:*:%s:%s' % (self.mimetype,';'.join([dlna_pn]+dlna_tags)))
self.item.attachments['original'] = ProxyImage(self.original_url[0])
res.resolution = self.original_url[1]
self.item.res.append(res)
elif hasattr(self,'large_url'):
dlna_pn = 'DLNA.ORG_PN=JPEG_LRG'
if self.store.proxy == False:
res = Resource(self.large_url[0], 'http-get:*:%s:%s' % (self.mimetype,';'.join([dlna_pn]+dlna_tags)))
else:
res = Resource(self.url+'?attachment=large', 'http-get:*:%s:%s' % (self.mimetype,';'.join([dlna_pn]+dlna_tags)))
self.item.attachments['large'] = ProxyImage(self.large_url[0])
res.resolution = self.large_url[1]
self.item.res.append(res)
if hasattr(self,'medium_url'):
dlna_pn = 'DLNA.ORG_PN=JPEG_MED'
if self.store.proxy == False:
res = Resource(self.medium_url[0], 'http-get:*:%s:%s' % (self.mimetype,';'.join([dlna_pn]+dlna_tags)))
else:
res = Resource(self.url+'?attachment=medium', 'http-get:*:%s:%s' % (self.mimetype,';'.join([dlna_pn]+dlna_tags)))
self.item.attachments['medium'] = ProxyImage(self.medium_url[0])
res.resolution = self.medium_url[1]
self.item.res.append(res)
if hasattr(self,'small_url'):
dlna_pn = 'DLNA.ORG_PN=JPEG_SM'
if self.store.proxy == False:
res = Resource(self.small_url[0], 'http-get:*:%s:%s' % (self.mimetype,';'.join([dlna_pn]+dlna_tags)))
else:
res = Resource(self.url+'?attachment=small', 'http-get:*:%s:%s' % (self.mimetype,';'.join([dlna_pn]+dlna_tags)))
self.item.attachments['small'] = ProxyImage(self.small_url[0])
res.resolution = self.small_url[1]
self.item.res.append(res)
if hasattr(self,'thumb_url'):
dlna_pn = 'DLNA.ORG_PN=JPEG_TN'
if self.store.proxy == False:
res = Resource(self.thumb_url[0], 'http-get:*:%s:%s' % (self.mimetype,';'.join([dlna_pn]+dlna_tags)))
else:
res = Resource(self.url+'?attachment=thumb', 'http-get:*:%s:%s' % (self.mimetype,';'.join([dlna_pn]+dlna_tags)))
self.item.attachments['thumb'] = ProxyImage(self.thumb_url[0])
res.resolution = self.thumb_url[1]
self.item.res.append(res)
return self.item
d = self.store.flickr_photos_getSizes(photo_id=self.flickr_id)
d.addCallback(process)
return d
def get_xml(self):
return self.item.toString()
def __repr__(self):
return 'id: ' + str(self.id) + ' @ ' + str(self.url)
class FlickrStore(BackendStore):
logCategory = 'flickr_storage'
implements = ['MediaServer']
def __init__(self, server, **kwargs):
BackendStore.__init__(self,server,**kwargs)
self.next_id = 10000
self.name = kwargs.get('name','Flickr')
self.proxy = kwargs.get('proxy','false')
self.refresh = int(kwargs.get('refresh',60))*60
self.limit = int(kwargs.get('limit',100))
self.flickr_userid = kwargs.get('userid',None)
self.flickr_password = kwargs.get('password',None)
self.flickr_permissions = kwargs.get('permissions',None)
if self.proxy in [1,'Yes','yes','True','true']:
self.proxy = True
else:
self.proxy = False
ignore_patterns = kwargs.get('ignore_patterns',[])
ignore_file_pattern = re.compile('|'.join(['^\..*'] + list(ignore_patterns)))
self.wmc_mapping = {'16': 0}
self.update_id = 0
self.flickr = Proxy('http://api.flickr.com/services/xmlrpc/')
self.flickr_api_key = '837718c8a622c699edab0ea55fcec224'
self.flickr_api_secret = '30a684822c341c3c'
self.store = {}
self.uploads = {}
self.refresh_store_loop = task.LoopingCall(self.refresh_store)
self.refresh_store_loop.start(self.refresh, now=False)
#self.server.coherence.store_plugin_config(self.server.uuid, {'test':'äöüß'})
self.flickr_userid = kwargs.get('userid',None)
self.flickr_password = kwargs.get('password',None)
self.flickr_permissions = kwargs.get('permissions','read')
self.flickr_authtoken = kwargs.get('authtoken',None)
if(self.flickr_authtoken == None and
self.server.coherence.writeable_config() == True):
if not None in (self.flickr_userid,self.flickr_password):
d = self.flickr_authenticate_app()
d.addBoth(lambda x: self.init_completed())
return
self.init_completed()
def __repr__(self):
return str(self.__class__).split('.')[-1]
def append( self, obj, parent):
if isinstance(obj, str):
mimetype = 'directory'
else:
mimetype = 'image/'
UPnPClass = classChooser(mimetype)
id = self.getnextID()
update = False
if hasattr(self, 'update_id'):
update = True
self.store[id] = FlickrItem( id, obj, parent, mimetype, self.urlbase,
UPnPClass, store=self,
update=update, proxy=self.proxy)
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
if parent:
#value = '%d,%d' % (parent.get_id(),parent_get_update_id())
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
if mimetype == 'directory':
return self.store[id]
def update_photo_details(result, photo):
dates = result.find('dates')
self.debug("update_photo_details", dates.get('posted'), dates.get('taken'))
photo.item.date = datetime(*time.strptime(dates.get('taken'),
"%Y-%m-%d %H:%M:%S")[0:6])
#d = self.flickr_photos_getInfo(obj.get('id'),obj.get('secret'))
#d.addCallback(update_photo_details, self.store[id])
return None
def appendDirectory( self, obj, parent):
mimetype = 'directory'
UPnPClass = classChooser(mimetype)
id = self.getnextID()
update = False
if hasattr(self, 'update_id'):
update = True
self.store[id] = FlickrItem( id, obj, parent, mimetype, self.urlbase,
UPnPClass,store=self,update=update, proxy=self.proxy)
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
if parent:
#value = '%d,%d' % (parent.get_id(),parent_get_update_id())
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
return self.store[id]
def appendPhoto( self, obj, parent):
mimetype = 'image/'
UPnPClass = classChooser(mimetype)
id = self.getnextID()
update = False
if hasattr(self, 'update_id'):
update = True
self.store[id] = FlickrItem( id, obj, parent, mimetype, self.urlbase,
UPnPClass,store=self,update=update, proxy=self.proxy)
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
if parent:
#value = '%d,%d' % (parent.get_id(),parent_get_update_id())
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
def update_photo_details(result, photo):
dates = result.find('dates')
self.debug("update_photo_details", dates.get('posted'), dates.get('taken'))
photo.item.date = datetime(*time.strptime(dates.get('taken'),
"%Y-%m-%d %H:%M:%S")[0:6])
#d = self.flickr_photos_getInfo(obj.get('id'),obj.get('secret'))
#d.addCallback(update_photo_details, self.store[id])
return None
def appendPhotoset( self, obj, parent):
mimetype = 'directory'
UPnPClass = classChooser(mimetype)
id = self.getnextID()
update = False
if hasattr(self, 'update_id'):
update = True
self.store[id] = FlickrItem( id, obj, parent, mimetype, self.urlbase,
UPnPClass,store=self,update=update, proxy=self.proxy)
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
if parent:
#value = '%d,%d' % (parent.get_id(),parent_get_update_id())
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
return self.store[id]
def appendContact( self, obj, parent):
mimetype = 'directory'
UPnPClass = classChooser(mimetype)
id = self.getnextID()
update = False
if hasattr(self, 'update_id'):
update = True
self.store[id] = FlickrItem( id, obj, parent, 'contact', self.urlbase,
UPnPClass,store=self,update=update, proxy=self.proxy)
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
if parent:
#value = '%d,%d' % (parent.get_id(),parent_get_update_id())
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
return self.store[id]
def remove(self, id):
#print 'FlickrStore remove id', id
try:
item = self.store[int(id)]
parent = item.get_parent()
item.remove()
del self.store[int(id)]
if hasattr(self, 'update_id'):
self.update_id += 1
if self.server:
self.server.content_directory_server.set_variable(0, 'SystemUpdateID', self.update_id)
#value = '%d,%d' % (parent.get_id(),parent_get_update_id())
value = (parent.get_id(),parent.get_update_id())
if self.server:
self.server.content_directory_server.set_variable(0, 'ContainerUpdateIDs', value)
except:
pass
def append_flickr_result(self, result, parent):
count = 0
for photo in result.getiterator('photo'):
self.append(photo, parent)
count += 1
self.info("initialized photo set %s with %d images" % (parent.get_name(), count))
def append_flickr_photo_result(self, result, parent):
count = 0
for photo in result.getiterator('photo'):
self.appendPhoto(photo, parent)
count += 1
self.info("initialized photo set %s with %d images" % (parent.get_name(), count))
def append_flickr_photoset_result(self, result, parent):
photoset_count = 0
for photoset in result.getiterator('photoset'):
photoset = self.appendPhotoset(photoset, parent)
d = self.flickr_photoset(photoset,per_page=self.limit)
d.addCallback(self.append_flickr_photo_result, photoset)
photoset_count += 1
def append_flickr_contact_result(self, result, parent):
contact_count = 0
for contact in result.getiterator('contact'):
contact = self.appendContact(contact, parent)
d = self.flickr_photosets(user_id=contact.nsid)
d.addCallback(self.append_flickr_photoset_result, contact)
contact_count += 1
def len(self):
return len(self.store)
def get_by_id(self,id):
if isinstance(id, basestring) and id.startswith('upload.'):
self.info("get_by_id looking for %s", id)
try:
item = self.uploads[id]
self.info('get_by_id found %r' % item)
return item
except:
return None
if isinstance(id, basestring):
id = id.split('@',1)
id = id[0]
try:
id = int(id)
except ValueError:
id = 0
try:
return self.store[id]
except:
return None
def getnextID(self):
ret = self.next_id
self.next_id += 1
return ret
def got_error(self,error):
self.warning("trouble refreshing Flickr data %r", error)
self.debug("%r", error.getTraceback())
def update_flickr_result(self,result, parent, element='photo'):
""" - is in in the store, but not in the update,
remove it from the store
- the photo is already in the store, skip it
- if in the update, but not in the store,
append it to the store
"""
old_ones = {}
new_ones = {}
for child in parent.get_children():
old_ones[child.get_flickr_id()] = child
for photo in result.findall(element):
new_ones[photo.get('id')] = photo
for id,child in old_ones.items():
if new_ones.has_key(id):
self.debug(id, "already there")
del new_ones[id]
elif child.id != UNSORTED_CONTAINER_ID:
self.debug(child.get_flickr_id(), "needs removal")
del old_ones[id]
self.remove(child.get_id())
self.info("refresh pass 1:", "old", len(old_ones), "new", len(new_ones), "store", len(self.store))
for photo in new_ones.values():
if element == 'photo':
self.appendPhoto(photo, parent)
elif element == 'photoset':
self.appendPhotoset(photo, parent)
self.debug("refresh pass 2:", "old", len(old_ones), "new", len(new_ones), "store", len(self.store))
if len(new_ones) > 0:
self.info("updated %s with %d new %ss" % (parent.get_name(), len(new_ones), element))
if element == 'photoset':
""" now we need to check the childs of all photosets
something that should be reworked imho
"""
for child in parent.get_children():
if child.id == UNSORTED_CONTAINER_ID:
continue
d = self.flickr_photoset(child,per_page=self.limit)
d.addCallback(self.update_flickr_result, child)
d.addErrback(self.got_error)
def refresh_store(self):
self.debug("refresh_store")
d = self.flickr_interestingness()
d.addCallback(self.update_flickr_result, self.most_wanted)
d.addErrback(self.got_error)
d = self.flickr_recent()
d.addCallback(self.update_flickr_result, self.recent)
d.addErrback(self.got_error)
if self.flickr_authtoken != None:
d= self.flickr_photosets()
d.addCallback(self.update_flickr_result, self.photosets, 'photoset')
d.addErrback(self.got_error)
d = self.flickr_notInSet()
d.addCallback(self.update_flickr_result, self.notinset)
d.addErrback(self.got_error)
d = self.flickr_favorites()
d.addCallback(self.update_flickr_result, self.favorites)
d.addErrback(self.got_error)
def flickr_call(self, method, **kwargs):
def got_result(result,method):
self.debug('flickr_call %r result %r' % (method,result))
result = parse_xml(result, encoding='utf-8')
return result
def got_error(error,method):
self.warning("connection to Flickr %r service failed! %r" % (method, error))
self.debug("%r", error.getTraceback())
return error
args = {}
args.update(kwargs)
args['api_key'] = self.flickr_api_key
if 'api_sig' in args:
args['method'] = method
self.debug('flickr_call %s %r',method,args)
d = self.flickr.callRemote(method, args)
d.addCallback(got_result,method)
d.addErrback(got_error,method)
return d
def flickr_test_echo(self):
d = self.flickr_call('flickr.test.echo')
return d
def flickr_test_login(self):
d = self.flickr_call('flickr.test.login',signed=True)
return d
def flickr_auth_getFrob(self):
api_sig = self.flickr_create_api_signature(method='flickr.auth.getFrob')
d = self.flickr_call('flickr.auth.getFrob',api_sig=api_sig)
return d
def flickr_auth_getToken(self,frob):
api_sig = self.flickr_create_api_signature(frob=frob,method='flickr.auth.getToken')
d = self.flickr_call('flickr.auth.getToken',frob=frob,api_sig=api_sig)
return d
def flickr_photos_getInfo(self, photo_id=None, secret=None):
if secret:
d = self.flickr_call('flickr.photos.getInfo', photo_id=photo_id, secret=secret)
else:
d = self.flickr_call('flickr.photos.getInfo', photo_id=photo_id)
return d
def flickr_photos_getSizes(self, photo_id=None):
if self.flickr_authtoken != None:
api_sig = self.flickr_create_api_signature(auth_token=self.flickr_authtoken,method='flickr.photos.getSizes', photo_id=photo_id)
d = self.flickr_call('flickr.photos.getSizes', auth_token=self.flickr_authtoken, photo_id=photo_id,api_sig=api_sig)
else:
api_sig = self.flickr_create_api_signature(method='flickr.photos.getSizes', photo_id=photo_id)
d = self.flickr_call('flickr.photos.getSizes',photo_id=photo_id,api_sig=api_sig)
return d
def flickr_interestingness(self, date=None, per_page=100):
if date == None:
date = time.strftime( "%Y-%m-%d", time.localtime(time.time()-86400))
if per_page > 500:
per_page = 500
d = self.flickr_call('flickr.interestingness.getList',extras='date_taken',per_page=per_page)
return d
def flickr_recent(self, date=None, per_page=100):
if date == None:
date = time.strftime( "%Y-%m-%d", time.localtime(time.time()-86400))
if per_page > 500:
per_page = 500
d = self.flickr_call('flickr.photos.getRecent',extras='date_taken',per_page=per_page)
return d
def flickr_notInSet(self, date=None, per_page=100):
api_sig = self.flickr_create_api_signature(auth_token=self.flickr_authtoken,extras='date_taken',method='flickr.photos.getNotInSet')
d = self.flickr_call('flickr.photos.getNotInSet',
auth_token=self.flickr_authtoken,
extras='date_taken',
api_sig=api_sig)
return d
def flickr_photosets(self,user_id=None,date=None,per_page=100):
if user_id != None:
api_sig = self.flickr_create_api_signature(auth_token=self.flickr_authtoken,method='flickr.photosets.getList',user_id=user_id)
d = self.flickr_call('flickr.photosets.getList',
user_id=user_id,
auth_token=self.flickr_authtoken,
api_sig=api_sig)
else:
api_sig = self.flickr_create_api_signature(auth_token=self.flickr_authtoken,method='flickr.photosets.getList')
d = self.flickr_call('flickr.photosets.getList',
auth_token=self.flickr_authtoken,
api_sig=api_sig)
return d
def flickr_photoset(self, photoset, date=None, per_page=100):
api_sig = self.flickr_create_api_signature(auth_token=self.flickr_authtoken,extras='date_taken',method='flickr.photosets.getPhotos',photoset_id=photoset.obj.get('id'))
d = self.flickr_call('flickr.photosets.getPhotos',
photoset_id=photoset.obj.get('id'),
extras='date_taken',
auth_token=self.flickr_authtoken,
api_sig=api_sig)
return d
def flickr_favorites(self, date=None, per_page=100):
api_sig = self.flickr_create_api_signature(auth_token=self.flickr_authtoken,extras='date_taken',method='flickr.favorites.getList')
d = self.flickr_call('flickr.favorites.getList',
auth_token=self.flickr_authtoken,
extras='date_taken',
api_sig=api_sig)
return d
def flickr_contacts(self, date=None, per_page=100):
api_sig = self.flickr_create_api_signature(auth_token=self.flickr_authtoken,method='flickr.contacts.getList')
d = self.flickr_call('flickr.contacts.getList',
auth_token=self.flickr_authtoken,
api_sig=api_sig)
return d
def flickr_contact_recents(self, contact, date=None, per_page=100):
api_sig = self.flickr_create_api_signature(auth_token=self.flickr_authtoken,method='flickr.photos.getContactsPhotos',photoset_id=photoset.obj.get('id'))
d = self.flickr_call('flickr.photos.getContactsPhotos',
photoset_id=photoset.obj.get('id'),
auth_token=self.flickr_authtoken,
api_sig=api_sig)
return d
def flickr_create_api_signature(self,**fields):
api_sig = self.flickr_api_secret + 'api_key' + self.flickr_api_key
for key in sorted(fields.keys()):
api_sig += key + str(fields[key])
return md5(api_sig)
def flickr_authenticate_app(self):
def got_error(error):
print error
def got_auth_token(result):
print "got_auth_token", result
result = result.getroot()
token = result.find('token').text
print 'token', token
self.flickr_authtoken = token
self.server.coherence.store_plugin_config(self.server.uuid, {'authtoken':token})
def get_auth_token(result,frob):
d =self.flickr_auth_getToken(frob)
d.addCallback(got_auth_token)
d.addErrback(got_error)
return d
def got_frob(result):
print "flickr", result
result = result.getroot()
frob = result.text
print frob
from twisted.internet import threads
d = threads.deferToThread(FlickrAuthenticate,self.flickr_api_key,self.flickr_api_secret,frob,self.flickr_userid,self.flickr_password,self.flickr_permissions)
d.addCallback(get_auth_token, frob)
d.addErrback(got_error)
d = self.flickr_auth_getFrob()
d.addCallback(got_frob)
d.addErrback(got_error)
return d
def soap_flickr_test_echo(self, value):
client = SOAPProxy("http://api.flickr.com/services/soap/",
namespace=("x","urn:flickr"),
envelope_attrib=[("xmlns:s", "http://www.w3.org/2003/05/soap-envelope"),
("xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance"),
("xmlns:xsd", "http://www.w3.org/1999/XMLSchema")],
soapaction="FlickrRequest")
d = client.callRemote( "FlickrRequest",
method='flickr.test.echo',
name=value,
api_key='837718c8a622c699edab0ea55fcec224')
def got_results(result):
print result
d.addCallback(got_results)
return d
def upnp_init(self):
self.current_connection_id = None
if self.server:
self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_SM;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_MED;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_LRG;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,'
'http-get:*:image/jpeg:*,'
'http-get:*:image/gif:*,'
'http-get:*:image/png:*',
default=True)
self.store[ROOT_CONTAINER_ID] = FlickrItem( ROOT_CONTAINER_ID, 'Flickr', None,
'directory', self.urlbase,
Container,store=self,update=True, proxy=self.proxy)
self.store[INTERESTINGNESS_CONTAINER_ID] = FlickrItem(INTERESTINGNESS_CONTAINER_ID, 'Most Wanted',
self.store[ROOT_CONTAINER_ID],
'directory', self.urlbase,
PhotoAlbum,store=self,update=True, proxy=self.proxy)
self.store[RECENT_CONTAINER_ID] = FlickrItem(RECENT_CONTAINER_ID, 'Recent',
self.store[ROOT_CONTAINER_ID],
'directory', self.urlbase,
PhotoAlbum,store=self,update=True, proxy=self.proxy)
self.most_wanted = self.store[INTERESTINGNESS_CONTAINER_ID]
d = self.flickr_interestingness(per_page=self.limit)
d.addCallback(self.append_flickr_result, self.most_wanted)
self.recent = self.store[RECENT_CONTAINER_ID]
d = self.flickr_recent(per_page=self.limit)
d.addCallback(self.append_flickr_photo_result, self.recent)
if self.flickr_authtoken != None:
self.store[GALLERY_CONTAINER_ID] = FlickrItem(GALLERY_CONTAINER_ID, 'Gallery',
self.store[ROOT_CONTAINER_ID],
'directory', self.urlbase,
PhotoAlbum,store=self,update=True, proxy=self.proxy)
self.photosets = self.store[GALLERY_CONTAINER_ID]
d = self.flickr_photosets()
d.addCallback(self.append_flickr_photoset_result, self.photosets)
self.store[UNSORTED_CONTAINER_ID] = FlickrItem(UNSORTED_CONTAINER_ID, 'Unsorted - Not in set',
self.store[GALLERY_CONTAINER_ID],
'directory', self.urlbase,
PhotoAlbum,store=self,update=True, proxy=self.proxy)
self.notinset = self.store[UNSORTED_CONTAINER_ID]
d = self.flickr_notInSet(per_page=self.limit)
d.addCallback(self.append_flickr_photo_result, self.notinset)
self.store[FAVORITES_CONTAINER_ID] = FlickrItem(FAVORITES_CONTAINER_ID, 'Favorites',
self.store[ROOT_CONTAINER_ID],
'directory', self.urlbase,
PhotoAlbum,store=self,update=True, proxy=self.proxy)
self.favorites = self.store[FAVORITES_CONTAINER_ID]
d = self.flickr_favorites(per_page=self.limit)
d.addCallback(self.append_flickr_photo_result, self.favorites)
self.store[CONTACTS_CONTAINER_ID] = FlickrItem(CONTACTS_CONTAINER_ID, 'Friends & Family',
self.store[ROOT_CONTAINER_ID],
'directory', self.urlbase,
PhotoAlbum,store=self,update=True, proxy=self.proxy)
self.contacts = self.store[CONTACTS_CONTAINER_ID]
d = self.flickr_contacts()
d.addCallback(self.append_flickr_contact_result, self.contacts)
def upnp_ImportResource(self, *args, **kwargs):
print 'upnp_ImportResource', args, kwargs
SourceURI = kwargs['SourceURI']
DestinationURI = kwargs['DestinationURI']
if DestinationURI.endswith('?import'):
id = DestinationURI.split('/')[-1]
id = id[:-7] # remove the ?import
else:
return failure.Failure(errorCode(718))
item = self.get_by_id(id)
if item == None:
return failure.Failure(errorCode(718))
def gotPage(result):
try:
import cStringIO as StringIO
except ImportError:
import StringIO
self.backend_import(item,StringIO.StringIO(result[0]))
def gotError(error, url):
self.warning("error requesting", url)
self.info(error)
return failure.Failure(errorCode(718))
d = getPage(SourceURI)
d.addCallbacks(gotPage, gotError, None, None, [SourceURI], None)
transfer_id = 0 #FIXME
return {'TransferID': transfer_id}
def upnp_CreateObject(self, *args, **kwargs):
print "upnp_CreateObject", args, kwargs
ContainerID = kwargs['ContainerID']
Elements = kwargs['Elements']
parent_item = self.get_by_id(ContainerID)
if parent_item == None:
return failure.Failure(errorCode(710))
if parent_item.item.restricted:
return failure.Failure(errorCode(713))
if len(Elements) == 0:
return failure.Failure(errorCode(712))
elt = DIDLElement.fromString(Elements)
if elt.numItems() != 1:
return failure.Failure(errorCode(712))
item = elt.getItems()[0]
if(item.id != '' or
item.parentID != ContainerID or
item.restricted == True or
item.title == ''):
return failure.Failure(errorCode(712))
if item.upnp_class.startswith('object.container'):
if len(item.res) != 0:
return failure.Failure(errorCode(712))
return failure.Failure(errorCode(712))
### FIXME
new_item = self.get_by_id(new_id)
didl = DIDLElement()
didl.addItem(new_item.item)
return {'ObjectID': id, 'Result': didl.toString()}
if item.upnp_class.startswith('object.item.imageItem'):
new_id = self.getnextID()
new_id = 'upload.'+str(new_id)
title = item.title or 'unknown'
mimetype = 'image/jpeg'
self.uploads[new_id] = FlickrItem( new_id, title, self.store[UNSORTED_CONTAINER_ID], mimetype, self.urlbase,
ImageItem,store=self,update=False, proxy=self.proxy)
new_item = self.uploads[new_id]
for res in new_item.item.res:
res.importUri = new_item.url+'?import'
res.data = None
didl = DIDLElement()
didl.addItem(new_item.item)
r = {'ObjectID': new_id, 'Result': didl.toString()}
print r
return r
return failure.Failure(errorCode(712))
# encode_multipart_form code is inspired by http://www.voidspace.org.uk/python/cgi.shtml#upload
def encode_multipart_form(self,fields):
boundary = mimetools.choose_boundary()
body = []
for k, v in fields.items():
body.append("--" + boundary.encode("utf-8"))
header = 'Content-Disposition: form-data; name="%s";' % k
if isinstance(v, FilePath):
header += 'filename="%s";' % v.basename()
body.append(header)
header = "Content-Type: application/octet-stream"
body.append(header)
body.append("")
body.append(v.getContent())
elif hasattr(v,'read'):
header += 'filename="%s";' % 'unknown'
body.append(header)
header = "Content-Type: application/octet-stream"
body.append(header)
body.append("")
body.append(v.read())
else:
body.append(header)
body.append("")
body.append(str(v).encode('utf-8'))
body.append("--" + boundary.encode("utf-8"))
content_type = 'multipart/form-data; boundary=%s' % boundary
return (content_type, '\r\n'.join(body))
def flickr_upload(self,image,**kwargs):
fields = {}
for k,v in kwargs.items():
if v != None:
fields[k] = v
#fields['api_key'] = self.flickr_api_key
fields['auth_token'] = self.flickr_authtoken
fields['api_sig'] = self.flickr_create_api_signature(**fields)
fields['api_key'] = self.flickr_api_key
fields['photo'] = image
(content_type, formdata) = self.encode_multipart_form(fields)
headers= {"Content-Type": content_type,
"Content-Length": str(len(formdata))}
d= getPage("http://api.flickr.com/services/upload/",
method="POST",
headers=headers,
postdata=formdata)
def got_something(result):
print "got_something", result
result = parse_xml(result[0], encoding='utf-8')
result = result.getroot()
if(result.attrib['stat'] == 'ok' and
result.find('photoid') != None):
photoid = result.find('photoid').text
return photoid
else:
error = result.find('err')
return failure.Failure(Exception(error.attrib['msg']))
d.addBoth(got_something)
return d
def backend_import(self,item,data):
""" we expect a FlickrItem
and the actual image data as a FilePath
or something with a read() method.
like the content attribute of a Request
"""
d = self.flickr_upload(data,title=item.get_name())
def got_photoid(id,item):
d = self.flickr_photos_getInfo(photo_id=id)
def add_it(obj,parent):
print "add_it", obj, obj.getroot(), parent
root = obj.getroot()
self.appendPhoto(obj.getroot(),parent)
return 200
d.addCallback(add_it,item.parent)
d.addErrback(got_fail)
return d
def got_fail(err):
print err
return err
d.addCallback(got_photoid, item)
d.addErrback(got_fail)
#FIXME we should return the deferred here
return d
def main():
log.init(None, 'debug')
f = FlickrStore(None,userid='x',password='xx',
permissions='xxx',
authtoken='xxx-x')
def got_flickr_result(result):
print "flickr", result
for photo in result.getiterator('photo'):
title = photo.get('title').encode('utf-8')
if len(title) == 0:
title = u'untitled'
for k,item in photo.items():
print k, item
url = "http://farm%s.static.flickr.com/%s/%s_%s.jpg" % (
photo.get('farm').encode('utf-8'),
photo.get('server').encode('utf-8'),
photo.get('id').encode('utf-8'),
photo.get('secret').encode('utf-8'))
#orginal_url = "http://farm%s.static.flickr.com/%s/%s_%s_o.jpg" % (
# photo.get('farm').encode('utf-8'),
# photo.get('server').encode('utf-8'),
# photo.get('id').encode('utf-8'),
# photo.get('originalsecret').encode('utf-8'))
print photo.get('id').encode('utf-8'), title, url
def got_upnp_result(result):
print "upnp", result
def got_error(error):
print error
#f.flickr_upload(FilePath('/tmp/image.jpg'),title='test')
#d = f.flickr_test_echo()
#d = f.flickr_interestingness()
#d.addCallback(got_flickr_result)
#f.upnp_init()
#print f.store
#r = f.upnp_Browse(BrowseFlag='BrowseDirectChildren',
# RequestedCount=0,
# StartingIndex=0,
# ObjectID=0,
# SortCriteria='*',
# Filter='')
#got_upnp_result(r)
if __name__ == '__main__':
from twisted.internet import reactor
reactor.callWhenRunning(main)
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~backends~light.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <[email protected]>
import coherence.extern.louie as louie
from coherence.upnp.core.utils import generalise_boolean
from coherence.backend import Backend
class SimpleLight(Backend):
""" this is a backend for a simple light
that only can be switched on or off
therefore we need to inform Coherence
about the state, and a method to change it
everything else is done by Coherence
"""
implements = ['BinaryLight']
logCategory = 'simple_light'
def __init__(self, server, **kwargs):
self.name = kwargs.get('name','SimpleLight')
self.server = server
self.state = 0 # we start switched off
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
def upnp_init(self):
if self.server:
self.server.switch_power_server.set_variable(0, 'Target', self.state)
self.server.switch_power_server.set_variable(0, 'Status', self.state)
def upnp_SetTarget(self,**kwargs):
self.info('upnp_SetTarget %r', kwargs)
self.state = int(generalise_boolean(kwargs['NewTargetValue']))
if self.server:
self.server.switch_power_server.set_variable(0, 'Target', self.state)
self.server.switch_power_server.set_variable(0, 'Status', self.state)
print "we have been switched to state", self.state
return {}
class BetterLight(Backend):
implements = ['DimmableLight']
logCategory = 'better_light'
def __init__(self, server, **kwargs):
self.name = kwargs.get('name','BetterLight')
self.server = server
self.state = 0 # we start switched off
self.loadlevel = 50 # we start with 50% brightness
louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
def upnp_init(self):
if self.server:
self.server.switch_power_server.set_variable(0, 'Target', self.state)
self.server.switch_power_server.set_variable(0, 'Status', self.state)
self.server.dimming_server.set_variable(0, 'LoadLevelTarget', self.loadlevel)
self.server.dimming_server.set_variable(0, 'LoadLevelStatus', self.loadlevel)
def upnp_SetTarget(self,**kwargs):
self.info('upnp_SetTarget %r', kwargs)
self.state = int(generalise_boolean(kwargs['NewTargetValue']))
if self.server:
self.server.switch_power_server.set_variable(0, 'Target', self.state)
self.server.switch_power_server.set_variable(0, 'Status', self.state)
print "we have been switched to state", self.state
return {}
def upnp_SetLoadLevelTarget(self,**kwargs):
self.info('SetLoadLevelTarget %r', kwargs)
self.loadlevel = int(kwargs['NewLoadlevelTarget'])
self.loadlevel = min(max(0,self.loadlevel),100)
if self.server:
self.server.dimming_server.set_variable(0, 'LoadLevelTarget', self.loadlevel)
self.server.dimming_server.set_variable(0, 'LoadLevelStatus', self.loadlevel)
print "we have been dimmed to level", self.loadlevel
return {}
if __name__ == '__main__':
from coherence.base import Coherence
def main():
config = {}
config['logmode'] = 'warning'
c = Coherence(config)
f = c.add_plugin('SimpleLight')
f = c.add_plugin('BetterLight')
from twisted.internet import reactor
reactor.callWhenRunning(main)
reactor.run()
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~core~event.py | # Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006,2007,2008,2009 Frank Scholz <[email protected]>
import time
from urlparse import urlsplit
from twisted.internet import reactor, defer
from twisted.web import resource, server
from twisted.web.http import datetimeToString
from twisted.internet.protocol import Protocol, ClientCreator, _InstanceFactory
from twisted.python import failure
from coherence import log, SERVER_ID
from coherence.upnp.core import utils
import coherence.extern.louie as louie
global hostname, web_server_port
hostname = None
web_server_port = None
class EventServer(resource.Resource, log.Loggable):
logCategory = 'event_server'
def __init__(self, control_point):
self.coherence = control_point.coherence
self.control_point = control_point
self.coherence.add_web_resource('events',
self)
global hostname, web_server_port
hostname = self.coherence.hostname
web_server_port = self.coherence.web_server_port
self.info("EventServer ready...")
def render_NOTIFY(self, request):
self.info("EventServer received notify from %s, code: %d" % (request.client, request.code))
data = request.content.getvalue()
request.setResponseCode(200)
command = {'method': request.method, 'path': request.path}
headers = request.responseHeaders
louie.send('UPnP.Event.Server.message_received', None, command, headers, data)
if request.code != 200:
self.info("data:", data)
else:
self.debug("data:", data)
headers = request.getAllHeaders()
sid = headers['sid']
try:
tree = utils.parse_xml(data).getroot()
except (SyntaxError,AttributeError):
self.warning("malformed event notification from %r", request.client)
self.debug("data: %r", data)
request.setResponseCode(400)
return ""
event = Event(sid,tree,raw=data)
if len(event) != 0:
self.control_point.propagate(event)
return ""
class EventSubscriptionServer(resource.Resource, log.Loggable):
"""
This class ist the server part on the device side. It listens to subscribe
requests and registers the subscriber to send event messages to this device.
If an unsubscribe request is received, the subscription is cancelled and no
more event messages will be sent.
we receive a subscription request
{'callback': '<http://192.168.213.130:9083/BYvZMzfTSQkjHwzOThaP/ConnectionManager>',
'host': '192.168.213.107:30020',
'nt': 'upnp:event',
'content-length': '0',
'timeout': 'Second-300'}
modify the callback value
callback = callback[1:len(callback)-1]
and pack it into a subscriber dict
{'uuid:oAQbxiNlyYojCAdznJnC':
{'callback': '<http://192.168.213.130:9083/BYvZMzfTSQkjHwzOThaP/ConnectionManager>',
'created': 1162374189.257338,
'timeout': 'Second-300',
'sid': 'uuid:oAQbxiNlyYojCAdznJnC'}}
"""
logCategory = 'event_subscription_server'
def __init__(self, service):
resource.Resource.__init__(self)
log.Loggable.__init__(self)
self.service = service
self.subscribers = service.get_subscribers()
try:
self.backend_name = self.service.backend.name
except AttributeError:
self.backend_name = self.service.backend
def render_SUBSCRIBE(self, request):
self.info( "EventSubscriptionServer %s (%s) received subscribe request from %s, code: %d" % (
self.service.id,
self.backend_name,
request.client, request.code))
data = request.content.getvalue()
request.setResponseCode(200)
command = {'method': request.method, 'path': request.path}
headers = request.responseHeaders
louie.send('UPnP.Event.Client.message_received', None, command, headers, data)
if request.code != 200:
self.debug("data:", data)
else:
headers = request.getAllHeaders()
timeout = headers.get('timeout', 'Second-infinite')
try:
#print self.subscribers
#print headers['sid']
if self.subscribers.has_key(headers['sid']):
s = self.subscribers[headers['sid']]
s['timeout'] = timeout
s['created'] = time.time()
elif not headers.has_key('callback'):
request.setResponseCode(404)
request.setHeader('SERVER', SERVER_ID)
request.setHeader('CONTENT-LENGTH', str(0))
return ""
except:
if not headers.has_key('callback'):
request.setResponseCode(404)
request.setHeader('SERVER', SERVER_ID)
request.setHeader('CONTENT-LENGTH', str(0))
return ""
from .uuid import UUID
sid = UUID()
s = { 'sid' : str(sid),
'callback' : headers['callback'][1:len(headers['callback'])-1],
'seq' : 0}
s['timeout'] = timeout
s['created'] = time.time()
self.service.new_subscriber(s)
request.setHeader('SID', s['sid'])
#request.setHeader('Subscription-ID', sid) wrong example in the UPnP UUID spec?
request.setHeader('TIMEOUT', timeout)
request.setHeader('SERVER', SERVER_ID)
request.setHeader('CONTENT-LENGTH', str(0))
return ""
def render_UNSUBSCRIBE(self, request):
self.info( "EventSubscriptionServer %s (%s) received unsubscribe request from %s, code: %d" % (
self.service.id,
self.backend_name,
request.client, request.code))
data = request.content.getvalue()
request.setResponseCode(200)
command = {'method': request.method, 'path': request.path}
headers = request.responseHeaders
louie.send('UPnP.Event.Client.message_received', None, command, headers, data)
if request.code != 200:
self.debug("data:", data)
else:
headers = request.getAllHeaders()
try:
del self.subscribers[headers['sid']]
except:
""" XXX if not found set right error code """
pass
#print self.subscribers
return ""
class Event(dict, log.Loggable):
logCategory = 'event'
ns = "urn:schemas-upnp-org:event-1-0"
def __init__(self, sid,elements=None,raw=None):
dict.__init__(self)
self._sid = sid
self.raw = raw
if elements != None:
self.from_elements(elements)
def get_sid(self):
return self._sid
def from_elements(self,elements):
for prop in elements.findall('{%s}property' % self.ns):
self._update_event(prop)
if len(self) == 0:
self.warning("event notification without property elements")
self.debug("data: %r", self.raw)
for prop in elements.findall('property'):
self._update_event(prop)
def _update_event(self,prop):
for var in prop.getchildren():
tag = var.tag
idx = tag.find('}') + 1
value = var.text
if value == None:
value = ''
self.update({tag[idx:]: value})
class EventProtocol(Protocol, log.Loggable):
logCategory = 'event_protocol'
def __init__(self, service, action):
self.service = service
self.action = action
def teardown(self):
self.transport.loseConnection()
self.service.event_connection = None
def connectionMade(self):
self.timeout_checker = reactor.callLater(30, self.teardown)
def dataReceived(self, data):
try:
self.timeout_checker.cancel()
except:
pass
self.info("response received from the Service Events HTTP server ")
#self.debug(data)
cmd, headers = utils.parse_http_response(data)
self.debug("%r %r", cmd, headers)
if int(cmd[1]) != 200:
self.warning("response with error code %r received upon our %r request", cmd[1], self.action)
# XXX get around devices that return an error on our event subscribe request
self.service.process_event({})
else:
try:
self.service.set_sid(headers['sid'])
timeout = headers['timeout']
self.debug("%r %r", headers['sid'], headers['timeout'])
if timeout.endswith('infinite'):
self.service.set_timeout(time.time() + 4294967296) # FIXME: that's lame
elif timeout.startswith('Second-'):
timeout = int(timeout[len('Second-'):])
self.service.set_timeout(timeout)
except:
#print headers
pass
self.teardown()
def connectionLost( self, reason):
try:
self.timeout_checker.cancel()
except:
pass
self.debug( "connection closed %r from the Service Events HTTP server", reason)
def unsubscribe(service, action='unsubscribe'):
return subscribe(service, action)
def subscribe(service, action='subscribe'):
"""
send a subscribe/renewal/unsubscribe request to a service
return the device response
"""
log_category = "event_protocol"
log.info(log_category, "event.subscribe, action: %r", action)
_,host_port,path,_,_ = urlsplit(service.get_base_url())
if host_port.find(':') != -1:
host,port = tuple(host_port.split(':'))
port = int(port)
else:
host = host_port
port = 80
def send_request(p, action):
log.info(log_category, "event.subscribe.send_request %r, action: %r %r",
p, action, service.get_event_sub_url())
_,_,event_path,_,_ = urlsplit(service.get_event_sub_url())
if action == 'subscribe':
timeout = service.timeout
if timeout == 0:
timeout = 1800
request = ["SUBSCRIBE %s HTTP/1.1" % event_path,
"HOST: %s:%d" % (host, port),
"TIMEOUT: Second-%d" % timeout,
]
service.event_connection = p
else:
request = ["UNSUBSCRIBE %s HTTP/1.1" % event_path,
"HOST: %s:%d" % (host, port),
]
if service.get_sid():
request.append("SID: %s" % service.get_sid())
else:
# XXX use address and port set in the coherence instance
#ip_address = p.transport.getHost().host
global hostname, web_server_port
#print hostname, web_server_port
url = 'http://%s:%d/events' % (hostname, web_server_port)
request.append("CALLBACK: <%s>" % url)
request.append("NT: upnp:event")
request.append('Date: %s' % datetimeToString())
request.append( "Content-Length: 0")
request.append( "")
request.append( "")
request = '\r\n'.join(request)
log.debug(log_category, "event.subscribe.send_request %r %r", request, p)
try:
p.transport.writeSomeData(request)
except AttributeError:
log.info(log_category, "transport for event %r already gone", action)
# print "event.subscribe.send_request", d
#return d
def got_error(failure, action):
log.info(log_category, "error on %s request with %s" % (action,service.get_base_url()))
log.debug(log_category, failure)
def teardown_connection(c, d):
log.info(log_category, "event.subscribe.teardown_connection")
del d
del c
def prepare_connection( service, action):
log.info(log_category, "event.subscribe.prepare_connection action: %r %r",
action, service.event_connection)
if service.event_connection == None:
c = ClientCreator(reactor, EventProtocol, service=service, action=action)
log.info(log_category, "event.subscribe.prepare_connection: %r %r",
host, port)
d = c.connectTCP(host, port)
d.addCallback(send_request, action=action)
d.addErrback(got_error, action)
#reactor.callLater(3, teardown_connection, c, d)
else:
d = defer.Deferred()
d.addCallback(send_request, action=action)
d.callback(service.event_connection)
#send_request(service.event_connection, action)
return d
""" FIXME:
we need to find a way to be sure that our unsubscribe calls get through
on shutdown
reactor.addSystemEventTrigger( 'before', 'shutdown', prepare_connection, service, action)
"""
return prepare_connection(service, action)
#print "event.subscribe finished"
class NotificationProtocol(Protocol, log.Loggable):
logCategory = "notification_protocol"
def connectionMade(self):
self.timeout_checker = reactor.callLater(30, lambda : self.transport.loseConnection())
def dataReceived(self, data):
try:
self.timeout_checker.cancel()
except:
pass
cmd, headers = utils.parse_http_response(data)
self.debug( "notification response received %r %r", cmd, headers)
try:
if int(cmd[1]) != 200:
self.warning("response with error code %r received upon our notification", cmd[1])
except:
self.debug("response without error code received upon our notification")
self.transport.loseConnection()
def connectionLost( self, reason):
try:
self.timeout_checker.cancel()
except:
pass
self.debug("connection closed %r", reason)
def send_notification(s, xml):
"""
send a notification a subscriber
return its response
"""
log_category = "notification_protocol"
_,host_port,path,_,_ = urlsplit(s['callback'])
if path == '':
path = '/'
if host_port.find(':') != -1:
host,port = tuple(host_port.split(':'))
port = int(port)
else:
host = host_port
port = 80
def send_request(p,port_item):
request = ['NOTIFY %s HTTP/1.1' % path,
'HOST: %s:%d' % (host, port),
'SEQ: %d' % s['seq'],
'CONTENT-TYPE: text/xml;charset="utf-8"',
'SID: %s' % s['sid'],
'NTS: upnp:propchange',
'NT: upnp:event',
'Content-Length: %d' % len(xml),
'',
xml]
request = '\r\n'.join(request)
log.info(log_category, "send_notification.send_request to %r %r",
s['sid'], s['callback'])
log.debug(log_category, "request: %r", request)
s['seq'] += 1
if s['seq'] > 0xffffffff:
s['seq'] = 1
p.transport.write(request)
port_item.disconnect()
#return p.transport.write(request)
def got_error(failure,port_item):
port_item.disconnect()
log.info(log_category, "error sending notification to %r %r",
s['sid'], s['callback'])
log.debug(log_category, failure)
#c = ClientCreator(reactor, NotificationProtocol)
#d = c.connectTCP(host, port)
d = defer.Deferred()
f = _InstanceFactory(reactor, NotificationProtocol(), d)
port_item = reactor.connectTCP(host, port, f, timeout=30, bindAddress=None)
d.addCallback(send_request, port_item)
d.addErrback(got_error, port_item)
return d,port_item
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~extern~config.py | #
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007,2008 Frank Scholz <[email protected]>
from coherence.extern.et import ET, indent
class ConfigMixin(object):
def nodes_to_dict(self,node):
if node.tag.endswith('list'):
return ConfigList(node)
else:
return ConfigDict(node)
class ConfigList(list,ConfigMixin):
def __init__(self,node):
self.name = node.tag
list.__init__(self)
self.from_element(node)
def to_element(self):
root = ET.Element(self.name)
for v in self:
if isinstance(v, (dict,list)):
root.append(v.to_element())
return root
def from_element(self,node):
for n in node:
if n.get('active','yes') == 'yes':
if len(n) == 0:
a = {}
for attr,value in n.items():
if attr == 'active':
continue
a[attr] = value
if len(a):
self.append(a)
else:
self.append(self.nodes_to_dict(n))
class ConfigDict(dict,ConfigMixin):
def __init__(self,node):
self.name = node.tag
dict.__init__(self)
self.from_element(node)
def to_element(self):
root = ET.Element(self.name)
for key, value in self.items():
if isinstance(value, (dict,list)):
root.append(value.to_element())
else:
s = ET.SubElement(root,key)
if isinstance(value, basestring):
s.text = value
else:
s.text = str(value)
return root
def from_element(self, node):
for attr,value in node.items():
if attr == 'active':
continue
self[attr] = value
for n in node:
if n.get('active','yes') == 'yes':
if len(n) == 0:
if n.text is not None and len(n.text)>0:
self[n.get('name',n.tag)] = n.text
for attr,value in n.items():
if attr == 'active':
continue
self[attr] = value
else:
tag = n.tag
#if tag.endswith('list'):
# tag = tag[:-4]
self[n.get('name',tag)] = self.nodes_to_dict(n)
#def __setitem__(self, key, value):
# self.config[key] = value
#def __getitem__(self, key):
# """ fetch an item """
# value = self.config.get(key, None)
# return value
#def __delitem__(self, key):
# del self.config[key]
#def get(self, key, default=None):
# try:
# return self[key]
# except KeyError:
# return default
#def items(self):
# """ """
# return self.config.items()
#def keys(self):
# """ """
# return self.config.keys()
#def values(self):
# """ """
# return self.config.values()
#def __repr__(self):
# return "%r" % self.config
class Config(ConfigDict):
"""
an incomplete XML file to dict and vice versa mapper
- nodes with an attribute 'active' set to 'no' are ignored
and not transferred into the dict
- nodes with tags ending with 'list' are transferrend into
an item with the key = 'tag' and a list with the subnodes
as the value
at the moment we parse the xml file and create dicts or lists out
of the nodes, but maybe it is much easier to keep the xml structure
as it is and simulate the dict/list access behavior on it?
"""
def __init__(self, file):
self.file = file
dict.__init__(self)
try:
xml = ET.parse(file)
except (SyntaxError, IOError):
raise
except Exception, msg:
raise SyntaxError(msg)
xmlroot = xml.getroot()
self.name = xmlroot.tag
self.from_element(xmlroot)
def save(self,file=None):
if file == None:
file = self.file
e = ET.Element(self.name)
for key, value in self.items():
if isinstance(value, (dict,list)):
e.append(value.to_element())
else:
s = ET.SubElement(e,key)
if isinstance(value, basestring):
s.text = value
else:
s.text = str(value)
indent(e)
db = ET.ElementTree(e)
db.write(file, encoding='utf-8')
if __name__ == '__main__':
import sys
config = Config(sys.argv[1])
print config
config['serverport'] = 55555
config['test'] = 'test'
config['logging']['level'] = 'info'
del config['controlpoint']
#del config['logging']['level']
print config
config.save('/tmp/t')
| [] |
2024-01-10 | opendreambox/python-coherence | coherence~extern~youtubedl~youtubedl.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Ricardo Garcia Gonzalez
# Author: Danny Colligan
# Author: Jean-Michel Sizun (integration within coherence framework)
# License: Public domain code
import htmlentitydefs
import httplib
import locale
import math
import netrc
import os
import os.path
import re
import socket
import string
import sys
import time
from urllib import urlencode, unquote, unquote_plus
from coherence.upnp.core.utils import getPage
std_headers = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
'Accept-Language': 'en-us,en;q=0.5',
}
simple_title_chars = string.ascii_letters.decode('ascii') + string.digits.decode('ascii')
def preferredencoding():
"""Get preferred encoding.
Returns the best encoding scheme for the system, based on
locale.getpreferredencoding() and some further tweaks.
"""
try:
pref = locale.getpreferredencoding()
# Mac OSX systems have this problem sometimes
if pref == '':
return 'UTF-8'
return pref
except:
sys.stderr.write('WARNING: problem obtaining preferred encoding. Falling back to UTF-8.\n')
return 'UTF-8'
class DownloadError(Exception):
"""Download Error exception.
This exception may be thrown by FileDownloader objects if they are not
configured to continue on errors. They will contain the appropriate
error message.
"""
pass
class SameFileError(Exception):
"""Same File exception.
This exception will be thrown by FileDownloader objects if they detect
multiple files would have to be downloaded to the same file on disk.
"""
pass
class PostProcessingError(Exception):
"""Post Processing exception.
This exception may be raised by PostProcessor's .run() method to
indicate an error in the postprocessing task.
"""
pass
class UnavailableFormatError(Exception):
"""Unavailable Format exception.
This exception will be thrown when a video is requested
in a format that is not available for that video.
"""
pass
class ContentTooShortError(Exception):
"""Content Too Short exception.
This exception may be raised by FileDownloader objects when a file they
download is too small for what the server announced first, indicating
the connection was probably interrupted.
"""
# Both in bytes
downloaded = None
expected = None
def __init__(self, downloaded, expected):
self.downloaded = downloaded
self.expected = expected
class FileDownloader(object):
"""File Downloader class.
File downloader objects are the ones responsible of downloading the
actual video file and writing it to disk if the user has requested
it, among some other tasks. In most cases there should be one per
program. As, given a video URL, the downloader doesn't know how to
extract all the needed information, task that InfoExtractors do, it
has to pass the URL to one of them.
For this, file downloader objects have a method that allows
InfoExtractors to be registered in a given order. When it is passed
a URL, the file downloader handles it to the first InfoExtractor it
finds that reports being able to handle it. The InfoExtractor extracts
all the information about the video or videos the URL refers to, and
asks the FileDownloader to process the video information, possibly
downloading the video.
File downloaders accept a lot of parameters. In order not to saturate
the object constructor with arguments, it receives a dictionary of
options instead. These options are available through the params
attribute for the InfoExtractors to use. The FileDownloader also
registers itself as the downloader in charge for the InfoExtractors
that are added to it, so this is a "mutual registration".
Available options:
username: Username for authentication purposes.
password: Password for authentication purposes.
usenetrc: Use netrc for authentication instead.
quiet: Do not print messages to stdout.
forceurl: Force printing final URL.
forcetitle: Force printing title.
simulate: Do not download the video files.
format: Video format code.
outtmpl: Template for output names.
ignoreerrors: Do not stop on download errors.
ratelimit: Download speed limit, in bytes/sec.
nooverwrites: Prevent overwriting files.
continuedl: Try to continue downloads if possible.
"""
params = None
_ies = []
_pps = []
_download_retcode = None
def __init__(self, params):
"""Create a FileDownloader object with the given options."""
self._ies = []
self._pps = []
self._download_retcode = 0
self.params = params
@staticmethod
def pmkdir(filename):
"""Create directory components in filename. Similar to Unix "mkdir -p"."""
components = filename.split(os.sep)
aggregate = [os.sep.join(components[0:x]) for x in xrange(1, len(components))]
aggregate = ['%s%s' % (x, os.sep) for x in aggregate] # Finish names with separator
for dir in aggregate:
if not os.path.exists(dir):
os.mkdir(dir)
@staticmethod
def format_bytes(bytes):
if bytes is None:
return 'N/A'
if type(bytes) is str:
bytes = float(bytes)
if bytes == 0.0:
exponent = 0
else:
exponent = long(math.log(bytes, 1024.0))
suffix = 'bkMGTPEZY'[exponent]
converted = float(bytes) / float(1024**exponent)
return '%.2f%s' % (converted, suffix)
@staticmethod
def calc_percent(byte_counter, data_len):
if data_len is None:
return '---.-%'
return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
@staticmethod
def calc_eta(start, now, total, current):
if total is None:
return '--:--'
dif = now - start
if current == 0 or dif < 0.001: # One millisecond
return '--:--'
rate = float(current) / dif
eta = long((float(total) - float(current)) / rate)
(eta_mins, eta_secs) = divmod(eta, 60)
if eta_mins > 99:
return '--:--'
return '%02d:%02d' % (eta_mins, eta_secs)
@staticmethod
def calc_speed(start, now, bytes):
dif = now - start
if bytes == 0 or dif < 0.001: # One millisecond
return '%10s' % '---b/s'
return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
@staticmethod
def best_block_size(elapsed_time, bytes):
new_min = max(bytes / 2.0, 1.0)
new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
if elapsed_time < 0.001:
return long(new_max)
rate = bytes / elapsed_time
if rate > new_max:
return long(new_max)
if rate < new_min:
return long(new_min)
return long(rate)
@staticmethod
def parse_bytes(bytestr):
"""Parse a string indicating a byte quantity into a long integer."""
matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
if matchobj is None:
return None
number = float(matchobj.group(1))
multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
return long(round(number * multiplier))
@staticmethod
def verify_url(url):
"""Verify a URL is valid and data could be downloaded. Return real data URL."""
request = urllib2.Request(url, None, std_headers)
data = urllib2.urlopen(request)
data.read(1)
url = data.geturl()
data.close()
return url
def add_info_extractor(self, ie):
"""Add an InfoExtractor object to the end of the list."""
self._ies.append(ie)
ie.set_downloader(self)
def add_post_processor(self, pp):
"""Add a PostProcessor object to the end of the chain."""
self._pps.append(pp)
pp.set_downloader(self)
def to_stdout(self, message, skip_eol=False):
"""Print message to stdout if not in quiet mode."""
if not self.params.get('quiet', False):
print (u'%s%s' % (message, [u'\n', u''][skip_eol])).encode(preferredencoding()),
sys.stdout.flush()
def to_stderr(self, message):
"""Print message to stderr."""
print >>sys.stderr, message.encode(preferredencoding())
def fixed_template(self):
"""Checks if the output template is fixed."""
return (re.search(ur'(?u)%\(.+?\)s', self.params['outtmpl']) is None)
def trouble(self, message=None):
"""Determine action to take when a download problem appears.
Depending on if the downloader has been configured to ignore
download errors or not, this method may throw an exception or
not when errors are found, after printing the message.
"""
if message is not None:
self.to_stderr(message)
if not self.params.get('ignoreerrors', False):
raise DownloadError(message)
self._download_retcode = 1
def slow_down(self, start_time, byte_counter):
"""Sleep if the download speed is over the rate limit."""
rate_limit = self.params.get('ratelimit', None)
if rate_limit is None or byte_counter == 0:
return
now = time.time()
elapsed = now - start_time
if elapsed <= 0.0:
return
speed = float(byte_counter) / elapsed
if speed > rate_limit:
time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
def report_destination(self, filename):
"""Report destination filename."""
self.to_stdout(u'[download] Destination: %s' % filename)
def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
"""Report download progress."""
self.to_stdout(u'\r[download] %s of %s at %s ETA %s' %
(percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
def report_resuming_byte(self, resume_len):
"""Report attemtp to resume at given byte."""
self.to_stdout(u'[download] Resuming download at byte %s' % resume_len)
def report_file_already_downloaded(self, file_name):
"""Report file has already been fully downloaded."""
self.to_stdout(u'[download] %s has already been downloaded' % file_name)
def report_unable_to_resume(self):
"""Report it was impossible to resume download."""
self.to_stdout(u'[download] Unable to resume')
def report_finish(self):
"""Report download finished."""
self.to_stdout(u'')
def process_info(self, info_dict):
"""Process a single dictionary returned by an InfoExtractor."""
# Do nothing else if in simulate mode
if self.params.get('simulate', False):
try:
info_dict['url'] = self.verify_url(info_dict['url'])
except (OSError, IOError, urllib2.URLError, httplib.HTTPException, socket.error), err:
raise UnavailableFormatError
# Forced printings
if self.params.get('forcetitle', False):
print info_dict['title'].encode(preferredencoding())
if self.params.get('forceurl', False):
print info_dict['url'].encode(preferredencoding())
return
try:
template_dict = dict(info_dict)
template_dict['epoch'] = unicode(long(time.time()))
filename = self.params['outtmpl'] % template_dict
except (ValueError, KeyError), err:
self.trouble('ERROR: invalid output template or system charset: %s' % str(err))
if self.params['nooverwrites'] and os.path.exists(filename):
self.to_stderr(u'WARNING: file exists: %s; skipping' % filename)
return
try:
self.pmkdir(filename)
except (OSError, IOError), err:
self.trouble('ERROR: unable to create directories: %s' % str(err))
return
try:
success = self._do_download(filename, info_dict['url'])
except (OSError, IOError), err:
raise UnavailableFormatError
except (urllib2.URLError, httplib.HTTPException, socket.error), err:
self.trouble('ERROR: unable to download video data: %s' % str(err))
return
except (ContentTooShortError, ), err:
self.trouble('ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
return
if success:
try:
self.post_process(filename, info_dict)
except (PostProcessingError), err:
self.trouble('ERROR: postprocessing: %s' % str(err))
return
def download(self, url_list):
"""Download a given list of URLs."""
if len(url_list) > 1 and self.fixed_template():
raise SameFileError(self.params['outtmpl'])
for url in url_list:
suitable_found = False
for ie in self._ies:
# Go to next InfoExtractor if not suitable
if not ie.suitable(url):
continue
# Suitable InfoExtractor found
suitable_found = True
# Extract information from URL and process it
ie.extract(url)
# Suitable InfoExtractor had been found; go to next URL
break
if not suitable_found:
self.trouble('ERROR: no suitable InfoExtractor: %s' % url)
return self._download_retcode
def get_real_urls(self, url_list):
"""Download a given list of URLs."""
if len(url_list) > 1 and self.fixed_template():
raise SameFileError(self._params['outtmpl'])
for url in url_list:
suitable_found = False
for ie in self._ies:
if not ie.suitable(url):
continue
# Suitable InfoExtractor found
suitable_found = True
def got_all_results(all_results):
results = [x for x in all_results if x is not None]
if len(results) != len(all_results):
retcode = self.trouble()
if len(results) > 1 and self.fixed_template():
raise SameFileError(self._params['outtmpl'])
real_urls = []
for result in results:
real_urls.append(result['url'])
return real_urls
d = ie.extract(url)
d.addCallback(got_all_results)
return d
return []
def post_process(self, filename, ie_info):
"""Run the postprocessing chain on the given file."""
info = dict(ie_info)
info['filepath'] = filename
for pp in self._pps:
info = pp.run(info)
if info is None:
break
# _do_download REMOVED
class InfoExtractor(object):
"""Information Extractor class.
Information extractors are the classes that, given a URL, extract
information from the video (or videos) the URL refers to. This
information includes the real video URL, the video title and simplified
title, author and others. The information is stored in a dictionary
which is then passed to the FileDownloader. The FileDownloader
processes this information possibly downloading the video to the file
system, among other possible outcomes. The dictionaries must include
the following fields:
id: Video identifier.
url: Final video URL.
uploader: Nickname of the video uploader.
title: Literal title.
stitle: Simplified title.
ext: Video filename extension.
Subclasses of this one should re-define the _real_initialize() and
_real_extract() methods, as well as the suitable() static method.
Probably, they should also be instantiated and added to the main
downloader.
"""
_ready = False
_downloader = None
def __init__(self, downloader=None):
"""Constructor. Receives an optional downloader."""
self._ready = False
self.set_downloader(downloader)
@staticmethod
def suitable(url):
"""Receives a URL and returns True if suitable for this IE."""
return False
def initialize(self):
"""Initializes an instance (authentication, etc)."""
if not self._ready:
self._real_initialize()
self._ready = True
def extract(self, url):
"""Extracts URL information and returns it in list of dicts."""
self.initialize()
return self._real_extract(url)
def set_downloader(self, downloader):
"""Sets the downloader for this IE."""
self._downloader = downloader
def to_stdout(self, message):
"""Print message to stdout if downloader is not in quiet mode."""
if self._downloader is None or not self._downloader.get_params().get('quiet', False):
print message
def to_stderr(self, message):
"""Print message to stderr."""
print >>sys.stderr, message
def _real_initialize(self):
"""Real initialization process. Redefine in subclasses."""
pass
def _real_extract(self, url):
"""Real extraction process. Redefine in subclasses."""
pass
class YoutubeIE(InfoExtractor):
"""Information extractor for youtube.com."""
_VALID_URL = r'^((?:http://)?(?:\w+\.)?youtube\.com/(?:(?:v/)|(?:(?:watch(?:\.php)?)?\?(?:.+&)?v=)))?([0-9A-Za-z_-]+)(?(1).+)?$'
_LANG_URL = r'http://uk.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
_LOGIN_URL = 'http://www.youtube.com/signup?next=/&gl=US&hl=en'
_AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
_NETRC_MACHINE = 'youtube'
_available_formats = ['22', '35', '18', '5', '17', '13', None] # listed in order of priority for -b flag
_video_extensions = {
'13': '3gp',
'17': 'mp4',
'18': 'mp4',
'22': 'mp4',
}
@staticmethod
def suitable(url):
return (re.match(YoutubeIE._VALID_URL, url) is not None)
@staticmethod
def htmlentity_transform(matchobj):
"""Transforms an HTML entity to a Unicode character."""
entity = matchobj.group(1)
# Known non-numeric HTML entity
if entity in htmlentitydefs.name2codepoint:
return unichr(htmlentitydefs.name2codepoint[entity])
# Unicode character
mobj = re.match(ur'(?u)#(x?\d+)', entity)
if mobj is not None:
numstr = mobj.group(1)
if numstr.startswith(u'x'):
base = 16
numstr = u'0%s' % numstr
else:
base = 10
return unichr(long(numstr, base))
# Unknown entity in name, return its literal representation
return (u'&%s;' % entity)
def report_lang(self):
"""Report attempt to set language."""
self._downloader.to_stdout(u'[youtube] Setting language')
def report_login(self):
"""Report attempt to log in."""
self._downloader.to_stdout(u'[youtube] Logging in')
def report_age_confirmation(self):
"""Report attempt to confirm age."""
self._downloader.to_stdout(u'[youtube] Confirming age')
def report_video_info_webpage_download(self, video_id):
"""Report attempt to download video info webpage."""
self._downloader.to_stdout(u'[youtube] %s: Downloading video info webpage' % video_id)
def report_information_extraction(self, video_id):
"""Report attempt to extract video information."""
self._downloader.to_stdout(u'[youtube] %s: Extracting video information' % video_id)
def report_unavailable_format(self, video_id, format):
"""Report extracted video URL."""
self._downloader.to_stdout(u'[youtube] %s: Format %s not available' % (video_id, format))
def report_video_url(self, video_id, video_real_url):
"""Report extracted video URL."""
self._downloader.to_stdout(u'[youtube] %s: URL: %s' % (video_id, video_real_url))
def _real_initialize(self):
if self._downloader is None:
return
username = None
password = None
downloader_params = self._downloader.params
# Attempt to use provided username and password or .netrc data
if downloader_params.get('username', None) is not None:
username = downloader_params['username']
password = downloader_params['password']
elif downloader_params.get('usenetrc', False):
try:
info = netrc.netrc().authenticators(self._NETRC_MACHINE)
if info is not None:
username = info[0]
password = info[2]
else:
raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
except (IOError, netrc.NetrcParseError), err:
self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
return
def gotAgeConfirmedPage(result):
print "Age confirmed in Youtube"
def gotLoggedInPage(result):
data,headers = result
if re.search(r'(?i)<form[^>]* name="loginForm"', data) is not None:
print 'WARNING: unable to log in: bad username or password'
return
print "logged in in Youtube"
# Confirm age
age_form = {
'next_url': '/',
'action_confirm': 'Confirm',
}
postdata = urlencode(age_form)
d = getPage(self._AGE_URL, postdata=postdata, headers=std_headers)
d.addCallback(gotAgeConfirmedPage)
def gotLoginError(error):
print "Unable to login to Youtube : %s:%s @ %s" % (username, password, self._LOGIN_URL)
print "Error: %s" % error
return
def gotLanguageSet(result):
data,headers = result
# No authentication to be performed
if username is None:
return
# Log in
login_form = {
'current_form': 'loginForm',
'next': '/',
'action_login': 'Log In',
'username': username,
'password': password,
}
postdata = urlencode(login_form)
d = getPage(self._LOGIN_URL, method='POST', postdata=postdata, headers=std_headers)
d.addCallbacks(gotLoggedInPage, gotLoginError)
def gotLanguageSetError(error):
print "Unable to process Youtube request: %s" % self._LANG_URL
print "Error: %s" % error
return
# Set language (will lead to log in, and then age confirmation)
d = getPage(self._LANG_URL, headers=std_headers)
d.addCallbacks(gotLanguageSet, gotLanguageSetError)
def _real_extract(self, url):
# Extract video id from URL
mobj = re.match(self._VALID_URL, url)
if mobj is None:
self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
return
video_id = mobj.group(2)
# Downloader parameters
best_quality = False
format_param = None
video_extension = None
quality_index = 0
if self._downloader is not None:
params = self._downloader.params
format_param = params.get('format', None)
if format_param == '0':
format_param = self._available_formats[quality_index]
best_quality = True
video_extension = self._video_extensions.get(format_param, 'flv')
# video info
video_info_url = 'http://www.youtube.com/get_video_info?&video_id=%s&el=detailpage&ps=default&eurl=&gl=US&hl=en' % video_id
if format_param is not None:
video_info_url = '%s&fmt=%s' % (video_info_url, format_param)
def gotPage(result, format_param, video_extension):
video_info_webpage,headers = result
# check format
if (format_param == '22'):
print "Check if HD video exists..."
mobj = re.search(r'var isHDAvailable = true;', video_info_webpage)
if mobj is None:
print "No HD video -> switch back to SD"
format_param = '18'
else:
print "...HD video OK!"
# "t" param
mobj = re.search(r'(?m)&token=([^&]+)(?:&|$)', video_info_webpage)
if mobj is None:
# Attempt to see if YouTube has issued an error message
mobj = re.search(r'(?m)&reason=([^&]+)(?:&|$)', video_info_webpage)
if mobj is None:
self.to_stderr(u'ERROR: unable to extract "t" parameter')
print video_info_webpage
return [None]
else:
reason = unquote_plus(mobj.group(1))
self.to_stderr(u'ERROR: YouTube said: %s' % reason.decode('utf-8'))
token = unquote(mobj.group(1))
video_real_url = 'http://www.youtube.com/get_video?video_id=%s&t=%s&eurl=&el=detailpage&ps=default&gl=US&hl=en' % (video_id, token)
if format_param is not None:
video_real_url = '%s&fmt=%s' % (video_real_url, format_param)
# uploader
mobj = re.search(r'(?m)&author=([^&]+)(?:&|$)', video_info_webpage)
if mobj is None:
self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
return
video_uploader = unquote(mobj.group(1))
# title
mobj = re.search(r'(?m)&title=([^&]+)(?:&|$)', video_info_webpage)
if mobj is None:
self._downloader.trouble(u'ERROR: unable to extract video title')
return
video_title = unquote(mobj.group(1))
video_title = video_title.decode('utf-8')
video_title = re.sub(ur'(?u)&(.+?);', self.htmlentity_transform, video_title)
video_title = video_title.replace(os.sep, u'%')
# simplified title
simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
simple_title = simple_title.strip(ur'_')
# Return information
return [{
'id': video_id.decode('utf-8'),
'url': video_real_url.decode('utf-8'),
'uploader': video_uploader.decode('utf-8'),
'title': video_title,
'stitle': simple_title,
'ext': video_extension.decode('utf-8'),
}]
def gotError(error):
print "Unable to process Youtube request: %s" % url
print "Error: %s" % error
return [None]
d = getPage(video_info_url, headers=std_headers)
d.addCallback(gotPage, format_param, video_extension)
d.addErrback(gotError)
return d
class MetacafeIE(InfoExtractor):
"""Information Extractor for metacafe.com."""
_VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
_DISCLAIMER = 'http://www.metacafe.com/family_filter/'
_FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
_youtube_ie = None
def __init__(self, youtube_ie, downloader=None):
InfoExtractor.__init__(self, downloader)
self._youtube_ie = youtube_ie
@staticmethod
def suitable(url):
return (re.match(MetacafeIE._VALID_URL, url) is not None)
def report_disclaimer(self):
"""Report disclaimer retrieval."""
self._downloader.to_stdout(u'[metacafe] Retrieving disclaimer')
def report_age_confirmation(self):
"""Report attempt to confirm age."""
self._downloader.to_stdout(u'[metacafe] Confirming age')
def report_download_webpage(self, video_id):
"""Report webpage download."""
self._downloader.to_stdout(u'[metacafe] %s: Downloading webpage' % video_id)
def report_extraction(self, video_id):
"""Report information extraction."""
self._downloader.to_stdout(u'[metacafe] %s: Extracting information' % video_id)
def _real_initialize(self):
# Retrieve disclaimer
request = urllib2.Request(self._DISCLAIMER, None, std_headers)
try:
self.report_disclaimer()
disclaimer = urllib2.urlopen(request).read()
except (urllib2.URLError, httplib.HTTPException, socket.error), err:
self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % str(err))
return
# Confirm age
disclaimer_form = {
'filters': '0',
'submit': "Continue - I'm over 18",
}
request = urllib2.Request(self._FILTER_POST, urllib.urlencode(disclaimer_form), std_headers)
try:
self.report_age_confirmation()
disclaimer = urllib2.urlopen(request).read()
except (urllib2.URLError, httplib.HTTPException, socket.error), err:
self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
return
def _real_extract(self, url):
# Extract id and simplified title from URL
mobj = re.match(self._VALID_URL, url)
if mobj is None:
self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
return
video_id = mobj.group(1)
# Check if video comes from YouTube
mobj2 = re.match(r'^yt-(.*)$', video_id)
if mobj2 is not None:
self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % mobj2.group(1))
return
simple_title = mobj.group(2).decode('utf-8')
video_extension = 'flv'
# Retrieve video webpage to extract further information
request = urllib2.Request('http://www.metacafe.com/watch/%s/' % video_id)
try:
self.report_download_webpage(video_id)
webpage = urllib2.urlopen(request).read()
except (urllib2.URLError, httplib.HTTPException, socket.error), err:
self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
return
# Extract URL, uploader and title from webpage
self.report_extraction(video_id)
mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
if mobj is None:
self._downloader.trouble(u'ERROR: unable to extract media URL')
return
mediaURL = urllib.unquote(mobj.group(1))
#mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
#if mobj is None:
# self._downloader.trouble(u'ERROR: unable to extract gdaKey')
# return
#gdaKey = mobj.group(1)
#
#video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
video_url = mediaURL
mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
if mobj is None:
self._downloader.trouble(u'ERROR: unable to extract title')
return
video_title = mobj.group(1).decode('utf-8')
mobj = re.search(r'(?ms)<li id="ChnlUsr">.*?Submitter:.*?<a .*?>(.*?)<', webpage)
if mobj is None:
self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
return
video_uploader = mobj.group(1)
try:
# Process video information
self._downloader.process_info({
'id': video_id.decode('utf-8'),
'url': video_url.decode('utf-8'),
'uploader': video_uploader.decode('utf-8'),
'title': video_title,
'stitle': simple_title,
'ext': video_extension.decode('utf-8'),
})
except UnavailableFormatError:
self._downloader.trouble(u'ERROR: format not available for video')
class YoutubeSearchIE(InfoExtractor):
"""Information Extractor for YouTube search queries."""
_VALID_QUERY = r'ytsearch(\d+|all)?:[\s\S]+'
_TEMPLATE_URL = 'http://www.youtube.com/results?search_query=%s&page=%s&gl=US&hl=en'
_VIDEO_INDICATOR = r'href="/watch\?v=.+?"'
_MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*</a>'
_youtube_ie = None
_max_youtube_results = 1000
def __init__(self, youtube_ie, downloader=None):
InfoExtractor.__init__(self, downloader)
self._youtube_ie = youtube_ie
@staticmethod
def suitable(url):
return (re.match(YoutubeSearchIE._VALID_QUERY, url) is not None)
def report_download_page(self, query, pagenum):
"""Report attempt to download playlist page with given number."""
self._downloader.to_stdout(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
def _real_initialize(self):
self._youtube_ie.initialize()
def _real_extract(self, query):
mobj = re.match(self._VALID_QUERY, query)
if mobj is None:
self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
return
prefix, query = query.split(':')
prefix = prefix[8:]
if prefix == '':
self._download_n_results(query, 1)
return
elif prefix == 'all':
self._download_n_results(query, self._max_youtube_results)
return
else:
try:
n = long(prefix)
if n <= 0:
self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
return
elif n > self._max_youtube_results:
self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
n = self._max_youtube_results
self._download_n_results(query, n)
return
except ValueError: # parsing prefix as integer fails
self._download_n_results(query, 1)
return
def _download_n_results(self, query, n):
"""Downloads a specified number of results for a query"""
video_ids = []
already_seen = set()
pagenum = 1
while True:
self.report_download_page(query, pagenum)
result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
request = urllib2.Request(result_url, None, std_headers)
try:
page = urllib2.urlopen(request).read()
except (urllib2.URLError, httplib.HTTPException, socket.error), err:
self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
return
# Extract video identifiers
for mobj in re.finditer(self._VIDEO_INDICATOR, page):
video_id = page[mobj.span()[0]:mobj.span()[1]].split('=')[2][:-1]
if video_id not in already_seen:
video_ids.append(video_id)
already_seen.add(video_id)
if len(video_ids) == n:
# Specified n videos reached
for id in video_ids:
self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
return
if re.search(self._MORE_PAGES_INDICATOR, page) is None:
for id in video_ids:
self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
return
pagenum = pagenum + 1
class YoutubePlaylistIE(InfoExtractor):
"""Information Extractor for YouTube playlists."""
_VALID_URL = r'(?:http://)?(?:\w+\.)?youtube.com/(?:view_play_list|my_playlists)\?.*?p=([^&]+).*'
_TEMPLATE_URL = 'http://www.youtube.com/view_play_list?p=%s&page=%s&gl=US&hl=en'
_VIDEO_INDICATOR = r'/watch\?v=(.+?)&'
_MORE_PAGES_INDICATOR = r'/view_play_list?p=%s&page=%s'
_youtube_ie = None
def __init__(self, youtube_ie, downloader=None):
InfoExtractor.__init__(self, downloader)
self._youtube_ie = youtube_ie
@staticmethod
def suitable(url):
return (re.match(YoutubePlaylistIE._VALID_URL, url) is not None)
def report_download_page(self, playlist_id, pagenum):
"""Report attempt to download playlist page with given number."""
self.to_stdout(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
def _real_initialize(self):
self._youtube_ie.initialize()
def _real_extract(self, url):
# Extract playlist id
mobj = re.match(self._VALID_URL, url)
if mobj is None:
self._downloader.trouble(u'ERROR: invalid url: %s' % url)
return
# Download playlist pages
playlist_id = mobj.group(1)
video_ids = []
pagenum = 1
while True:
self.report_download_page(playlist_id, pagenum)
request = urllib2.Request(self._TEMPLATE_URL % (playlist_id, pagenum), None, std_headers)
try:
page = urllib2.urlopen(request).read()
except (urllib2.URLError, httplib.HTTPException, socket.error), err:
self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
return
# Extract video identifiers
ids_in_page = []
for mobj in re.finditer(self._VIDEO_INDICATOR, page):
if mobj.group(1) not in ids_in_page:
ids_in_page.append(mobj.group(1))
video_ids.extend(ids_in_page)
if (self._MORE_PAGES_INDICATOR % (playlist_id.upper(), pagenum + 1)) not in page:
break
pagenum = pagenum + 1
for id in video_ids:
self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
return
class PostProcessor(object):
"""Post Processor class.
PostProcessor objects can be added to downloaders with their
add_post_processor() method. When the downloader has finished a
successful download, it will take its internal chain of PostProcessors
and start calling the run() method on each one of them, first with
an initial argument and then with the returned value of the previous
PostProcessor.
The chain will be stopped if one of them ever returns None or the end
of the chain is reached.
PostProcessor objects follow a "mutual registration" process similar
to InfoExtractor objects.
"""
_downloader = None
def __init__(self, downloader=None):
self._downloader = downloader
def to_stdout(self, message):
"""Print message to stdout if downloader is not in quiet mode."""
if self._downloader is None or not self._downloader.get_params().get('quiet', False):
print message
def to_stderr(self, message):
"""Print message to stderr."""
print >>sys.stderr, message
def set_downloader(self, downloader):
"""Sets the downloader for this PP."""
self._downloader = downloader
def run(self, information):
"""Run the PostProcessor.
The "information" argument is a dictionary like the ones
composed by InfoExtractors. The only difference is that this
one has an extra field called "filepath" that points to the
downloaded file.
When this method returns None, the postprocessing chain is
stopped. However, this method may return an information
dictionary that will be passed to the next postprocessing
object in the chain. It can be the one it received after
changing some fields.
In addition, this method may raise a PostProcessingError
exception that will be taken into account by the downloader
it was called from.
"""
return information # by default, do nothing
### MAIN PROGRAM ###
if __name__ == '__main__':
try:
# Modules needed only when running the main program
import getpass
import optparse
# General configuration
urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler()))
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPCookieProcessor()))
socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
# Parse command line
parser = optparse.OptionParser(
usage='Usage: %prog [options] url...',
version='2009.09.13',
conflict_handler='resolve',
)
parser.add_option('-h', '--help',
action='help', help='print this help text and exit')
parser.add_option('-v', '--version',
action='version', help='print program version and exit')
parser.add_option('-i', '--ignore-errors',
action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
parser.add_option('-r', '--rate-limit',
dest='ratelimit', metavar='L', help='download rate limit (e.g. 50k or 44.6m)')
authentication = optparse.OptionGroup(parser, 'Authentication Options')
authentication.add_option('-u', '--username',
dest='username', metavar='UN', help='account username')
authentication.add_option('-p', '--password',
dest='password', metavar='PW', help='account password')
authentication.add_option('-n', '--netrc',
action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
parser.add_option_group(authentication)
video_format = optparse.OptionGroup(parser, 'Video Format Options')
video_format.add_option('-f', '--format',
action='store', dest='format', metavar='FMT', help='video format code')
video_format.add_option('-b', '--best-quality',
action='store_const', dest='format', help='download the best quality video possible', const='0')
video_format.add_option('-m', '--mobile-version',
action='store_const', dest='format', help='alias for -f 17', const='17')
video_format.add_option('-d', '--high-def',
action='store_const', dest='format', help='alias for -f 22', const='22')
parser.add_option_group(video_format)
verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
verbosity.add_option('-q', '--quiet',
action='store_true', dest='quiet', help='activates quiet mode', default=False)
verbosity.add_option('-s', '--simulate',
action='store_true', dest='simulate', help='do not download video', default=False)
verbosity.add_option('-g', '--get-url',
action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
verbosity.add_option('-e', '--get-title',
action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
parser.add_option_group(verbosity)
filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
filesystem.add_option('-t', '--title',
action='store_true', dest='usetitle', help='use title in file name', default=False)
filesystem.add_option('-l', '--literal',
action='store_true', dest='useliteral', help='use literal title in file name', default=False)
filesystem.add_option('-o', '--output',
dest='outtmpl', metavar='TPL', help='output filename template')
filesystem.add_option('-a', '--batch-file',
dest='batchfile', metavar='F', help='file containing URLs to download')
filesystem.add_option('-w', '--no-overwrites',
action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
filesystem.add_option('-c', '--continue',
action='store_true', dest='continue_dl', help='resume partially downloaded files', default=False)
parser.add_option_group(filesystem)
(opts, args) = parser.parse_args()
# Batch file verification
batchurls = []
if opts.batchfile is not None:
try:
batchurls = open(opts.batchfile, 'r').readlines()
batchurls = [x.strip() for x in batchurls]
batchurls = [x for x in batchurls if len(x) > 0]
except IOError:
sys.exit(u'ERROR: batch file could not be read')
all_urls = batchurls + args
# Conflicting, missing and erroneous options
if len(all_urls) < 1:
parser.error(u'you must provide at least one URL')
if opts.usenetrc and (opts.username is not None or opts.password is not None):
parser.error(u'using .netrc conflicts with giving username/password')
if opts.password is not None and opts.username is None:
parser.error(u'account username missing')
if opts.outtmpl is not None and (opts.useliteral or opts.usetitle):
parser.error(u'using output template conflicts with using title or literal title')
if opts.usetitle and opts.useliteral:
parser.error(u'using title conflicts with using literal title')
if opts.username is not None and opts.password is None:
opts.password = getpass.getpass(u'Type account password and press return:')
if opts.ratelimit is not None:
numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
if numeric_limit is None:
parser.error(u'invalid rate limit specified')
opts.ratelimit = numeric_limit
# Information extractors
youtube_ie = YoutubeIE()
metacafe_ie = MetacafeIE(youtube_ie)
youtube_pl_ie = YoutubePlaylistIE(youtube_ie)
youtube_search_ie = YoutubeSearchIE(youtube_ie)
# File downloader
fd = FileDownloader({
'usenetrc': opts.usenetrc,
'username': opts.username,
'password': opts.password,
'quiet': (opts.quiet or opts.geturl or opts.gettitle),
'forceurl': opts.geturl,
'forcetitle': opts.gettitle,
'simulate': (opts.simulate or opts.geturl or opts.gettitle),
'format': opts.format,
'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(preferredencoding()))
or (opts.usetitle and u'%(stitle)s-%(id)s.%(ext)s')
or (opts.useliteral and u'%(title)s-%(id)s.%(ext)s')
or u'%(id)s.%(ext)s'),
'ignoreerrors': opts.ignoreerrors,
'ratelimit': opts.ratelimit,
'nooverwrites': opts.nooverwrites,
'continuedl': opts.continue_dl,
})
fd.add_info_extractor(youtube_search_ie)
fd.add_info_extractor(youtube_pl_ie)
fd.add_info_extractor(metacafe_ie)
fd.add_info_extractor(youtube_ie)
retcode = fd.download(all_urls)
sys.exit(retcode)
except DownloadError:
sys.exit(1)
except SameFileError:
sys.exit(u'ERROR: fixed output name but more than one file to download')
except KeyboardInterrupt:
sys.exit(u'\nERROR: Interrupted by user')
| [
"http://www.youtube.com/results?search_query=%s&page=%s&gl=US&hl=en",
"http://www.youtube.com/view_play_list?p=%s&page=%s&gl=US&hl=en"
] |
2024-01-10 | opendreambox/python-coherence | coherence~upnp~devices~basics.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008 Frank Scholz <[email protected]>
import os.path
from twisted.python import util
from twisted.web import resource, static
from twisted.internet import reactor
from coherence import __version__
from coherence.extern.et import ET, indent
import coherence.extern.louie as louie
from coherence import log
class DeviceHttpRoot(resource.Resource, log.Loggable):
logCategory = 'basicdevice'
def __init__(self, server):
resource.Resource.__init__(self)
self.server = server
def getChildWithDefault(self, path, request):
self.info('DeviceHttpRoot %s getChildWithDefault ' % self.server.device_type, path, request.uri, request.client)
self.info( request.getAllHeaders())
if self.children.has_key(path):
return self.children[path]
if request.uri == '/':
return self
return self.getChild(path, request)
def getChild(self, name, request):
self.info('DeviceHttpRoot %s getChild %s ' % (name, request))
ch = None
if ch is None:
p = util.sibpath(__file__, name)
if os.path.exists(p):
ch = static.File(p)
self.info('DeviceHttpRoot ch ', ch)
return ch
def listchilds(self, uri):
cl = ''
for c in self.children:
cl += '<li><a href=%s/%s>%s</a></li>' % (uri,c,c)
return cl
def render(self,request):
return '<html><p>root of the %s %s</p><p><ul>%s</ul></p></html>'% (self.server.backend.name,
self.server.device_type,
self.listchilds(request.uri))
class RootDeviceXML(static.Data):
def __init__(self, hostname, uuid, urlbase,
xmlns='urn:schemas-upnp-org:device-1-0',
device_uri_base='urn:schemas-upnp-org:device',
device_type='BasicDevice',
version=2,
friendly_name='Coherence UPnP BasicDevice',
manufacturer='beebits.net',
manufacturer_url='http://coherence.beebits.net',
model_description='Coherence UPnP BasicDevice',
model_name='Coherence UPnP BasicDevice',
model_number=__version__,
model_url='http://coherence.beebits.net',
serial_number='0000001',
presentation_url='',
services=[],
devices=[],
icons=[],
dlna_caps=[],
sec_dmc10=False):
uuid = str(uuid)
root = ET.Element('root')
root.attrib['xmlns']=xmlns
device_type_uri = ':'.join((device_uri_base,device_type, str(version)))
e = ET.SubElement(root, 'specVersion')
ET.SubElement( e, 'major').text = '1'
ET.SubElement( e, 'minor').text = '0'
sec_ns = 'xmlns:sec'
sec_ns_val = 'http://www.sec.co.kr'
root.attrib[sec_ns] = sec_ns_val
#ET.SubElement(root, 'URLBase').text = urlbase + uuid[5:] + '/'
d = ET.SubElement(root, 'device')
x1 = ET.SubElement(d, 'dlna:X_DLNADOC')
x1.attrib['xmlns:dlna']='urn:schemas-dlna-org:device-1-0'
x2 = ET.SubElement(d, 'dlna:X_DLNADOC')
x2.attrib['xmlns:dlna']='urn:schemas-dlna-org:device-1-0'
dt = None
if device_type == 'MediaServer':
dt = "DMS"
if sec_dmc10:
sec_ns = 'xmlns:sec'
sec_ns_val = 'http://www.sec.co.kr'
sec_text = 'smi,DCM10,getMediaInfo.sec,getCaptionInfo.sec'
sec = ET.SubElement(d, 'sec:ProductCap')
sec.attrib[sec_ns]= sec_ns_val
sec.text = sec_text
sec = ET.SubElement(d, 'sec:X_ProductCap')
sec.attrib[sec_ns]= sec_ns_val
sec.text = sec_text
elif device_type == 'MediaRenderer':
dt = "DMR"
if dt:
x1.text = '%s-1.50' %(dt)
x2.text = 'M-%s-1.50' %(dt)
if len(dlna_caps) > 0:
if isinstance(dlna_caps, basestring):
dlna_caps = [dlna_caps]
for cap in dlna_caps:
x = ET.SubElement(d, 'dlna:X_DLNACAP')
x.attrib['xmlns:dlna']='urn:schemas-dlna-org:device-1-0'
x.text = cap
ET.SubElement( d, 'deviceType').text = device_type_uri
ET.SubElement( d, 'friendlyName').text = friendly_name
ET.SubElement( d, 'manufacturer').text = manufacturer
ET.SubElement( d, 'manufacturerURL').text = manufacturer_url
ET.SubElement( d, 'modelDescription').text = model_description
ET.SubElement( d, 'modelName').text = model_name
ET.SubElement(d, 'modelNumber').text = model_number
ET.SubElement( d, 'modelURL').text = model_url
ET.SubElement( d, 'serialNumber').text = serial_number
ET.SubElement( d, 'UDN').text = uuid
ET.SubElement( d, 'UPC').text = ''
ET.SubElement( d, 'presentationURL').text = presentation_url
if len(services):
e = ET.SubElement(d, 'serviceList')
for service in services:
id = service.get_id()
s = ET.SubElement(e, 'service')
try:
namespace = service.namespace
except:
namespace = 'schemas-upnp-org'
if( hasattr(service,'version') and
service.version < version):
v = service.version
else:
v = version
ET.SubElement(s, 'serviceType').text = 'urn:%s:service:%s:%d' % (namespace, id, int(v))
try:
namespace = service.id_namespace
except:
namespace = 'upnp-org'
ET.SubElement(s, 'serviceId').text = 'urn:%s:serviceId:%s' % (namespace,id)
ET.SubElement(s, 'SCPDURL').text = '/' + uuid[5:] + '/' + id + '/' + service.scpd_url
ET.SubElement(s, 'controlURL').text = '/' + uuid[5:] + '/' + id + '/' + service.control_url
ET.SubElement(s, 'eventSubURL').text = '/' + uuid[5:] + '/' + id + '/' + service.subscription_url
if len(devices):
e = ET.SubElement( d, 'deviceList')
if len(icons):
e = ET.SubElement(d, 'iconList')
for icon in icons:
icon_path = ''
if icon.has_key('url'):
if icon['url'].startswith('file://'):
icon_path = icon['url'][7:]
elif icon['url'] == '.face':
icon_path = os.path.join(os.path.expanduser('~'), ".face")
else:
from pkg_resources import resource_filename
icon_path = os.path.abspath(resource_filename(__name__, os.path.join('..','..','..','misc','device-icons',icon['url'])))
if os.path.exists(icon_path) == True:
i = ET.SubElement(e, 'icon')
for k,v in icon.items():
if k == 'url':
if v.startswith('file://'):
ET.SubElement(i, k).text = '/'+uuid[5:]+'/'+os.path.basename(v)
continue
elif v == '.face':
ET.SubElement(i, k).text = '/'+uuid[5:]+'/'+'face-icon.png'
continue
else:
ET.SubElement(i, k).text = '/'+uuid[5:]+'/'+os.path.basename(v)
continue
ET.SubElement(i, k).text = str(v)
#if self.has_level(LOG_DEBUG):
# indent( root)
self.xml = """<?xml version="1.0" encoding="utf-8"?>""" + ET.tostring( root, encoding='utf-8')
static.Data.__init__(self, self.xml, 'text/xml')
class BasicDeviceMixin(object):
device_type = 'Coherence UPnP BasicDevice'
def __init__(self, coherence, backend, **kwargs):
self.coherence = coherence
if not hasattr(self,'version'):
self.version = int(kwargs.get('version',self.coherence.config.get('version',2)))
try:
self.uuid = kwargs['uuid']
if not self.uuid.startswith('uuid:'):
self.uuid = 'uuid:' + self.uuid
except KeyError:
from coherence.upnp.core.uuid import UUID
self.uuid = UUID()
self.manufacturer = kwargs.get('manufacturer', 'beebits.net')
self.manufacturer_url = kwargs.get('manufacturer_url', 'http://coherence.beebits.net')
self.model_description = kwargs.get('model_description', 'Coherence UPnP %s' % self.device_type)
self.model_name = kwargs.get('model_name', 'Coherence UPnP %s' % self.device_type)
self.model_number = kwargs.get('model_number', __version__)
self.model_url = kwargs.get('model_url', 'http://coherence.beebits.net')
self.backend = None
urlbase = self.coherence.urlbase
if urlbase[-1] != '/':
urlbase += '/'
self.urlbase = urlbase + str(self.uuid)[5:]
kwargs['urlbase'] = self.urlbase
self.icons = kwargs.get('iconlist', kwargs.get('icons', []))
if len(self.icons) == 0:
if kwargs.has_key('icon'):
if isinstance(kwargs['icon'],dict):
self.icons.append(kwargs['icon'])
else:
self.icons = kwargs['icon']
louie.connect( self.init_complete, 'Coherence.UPnP.Backend.init_completed', louie.Any)
louie.connect( self.init_failed, 'Coherence.UPnP.Backend.init_failed', louie.Any)
reactor.callLater(0.2, self.fire, backend, **kwargs)
def init_failed(self, backend, msg):
if self.backend != backend:
return
self.warning('backend not installed, %s activation aborted - %s' % (self.device_type,msg.getErrorMessage()))
self.debug(msg)
try:
del self.coherence.active_backends[str(self.uuid)]
except KeyError:
pass
def register(self):
s = self.coherence.ssdp_server
uuid = str(self.uuid)
host = self.coherence.hostname
self.msg('%s register' % self.device_type)
# we need to do this after the children are there, since we send notifies
s.register('local',
'%s::upnp:rootdevice' % uuid,
'upnp:rootdevice',
self.coherence.urlbase + uuid[5:] + '/' + 'description-%d.xml' % self.version,
host=host)
s.register('local',
uuid,
uuid,
self.coherence.urlbase + uuid[5:] + '/' + 'description-%d.xml' % self.version,
host=host)
version = self.version
while version > 0:
if version == self.version:
silent = False
else:
silent = True
s.register('local',
'%s::urn:schemas-upnp-org:device:%s:%d' % (uuid, self.device_type, version),
'urn:schemas-upnp-org:device:%s:%d' % (self.device_type, version),
self.coherence.urlbase + uuid[5:] + '/' + 'description-%d.xml' % version,
silent=silent,
host=host)
version -= 1
for service in self._services:
device_version = self.version
service_version = self.version
if hasattr(service,'version'):
service_version = service.version
silent = False
while service_version > 0:
try:
namespace = service.namespace
except:
namespace = 'schemas-upnp-org'
device_description_tmpl = 'description-%d.xml' % device_version
if hasattr(service,'device_description_tmpl'):
device_description_tmpl = service.device_description_tmpl
s.register('local',
'%s::urn:%s:service:%s:%d' % (uuid,namespace,service.id, service_version),
'urn:%s:service:%s:%d' % (namespace,service.id, service_version),
self.coherence.urlbase + uuid[5:] + '/' + device_description_tmpl,
silent=silent,
host=host)
silent = True
service_version -= 1
device_version -= 1
def unregister(self):
if self.backend != None and hasattr(self.backend,'release'):
self.backend.release()
if not hasattr(self,'_services'):
""" seems we never made it to actually
completing that device
"""
return
for service in self._services:
try:
service.check_subscribers_loop.stop()
except:
pass
if hasattr(service,'check_moderated_loop') and service.check_moderated_loop != None:
try:
service.check_moderated_loop.stop()
except:
pass
if hasattr(service,'release'):
service.release()
if hasattr(service,'_release'):
service._release()
s = self.coherence.ssdp_server
uuid = str(self.uuid)
self.coherence.remove_web_resource(uuid[5:])
version = self.version
while version > 0:
s.doByebye('%s::urn:schemas-upnp-org:device:%s:%d' % (uuid, self.device_type, version))
for service in self._services:
if hasattr(service,'version') and service.version < version:
continue
try:
namespace = service.namespace
except AttributeError:
namespace = 'schemas-upnp-org'
s.doByebye('%s::urn:%s:service:%s:%d' % (uuid,namespace,service.id, version))
version -= 1
s.doByebye(uuid)
s.doByebye('%s::upnp:rootdevice' % uuid) | [] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.