mygpoclient-1.7/ 0000775 0001751 0001751 00000000000 12105163324 013324 5 ustar thp thp 0000000 0000000 mygpoclient-1.7/makefile 0000664 0001751 0001751 00000002071 12105163114 015021 0 ustar thp thp 0000000 0000000
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
test:
nosetests --cover-erase --with-coverage --with-doctest \
--cover-package=mygpoclient
docs:
epydoc -n 'gpodder.net API Client Library' -o docs/ mygpoclient -v --exclude='.*_test'
clean:
find -name '*.pyc' -exec rm '{}' \;
rm -f .coverage
rm -rf docs/ build/
distclean: clean
rm -f MANIFEST
rm -rf dist/
.PHONY: test docs clean distclean
mygpoclient-1.7/AUTHORS 0000664 0001751 0001751 00000000215 12105161231 014365 0 ustar thp thp 0000000 0000000 Thomas Perl
Stefan Kögl
David Sepashvili
Stefan Derkits
mygpoclient-1.7/mygpoclient/ 0000775 0001751 0001751 00000000000 12105163324 015656 5 ustar thp thp 0000000 0000000 mygpoclient-1.7/mygpoclient/http_test.py 0000664 0001751 0001751 00000015241 12105161764 020257 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from mygpoclient import http
import unittest
import multiprocessing
import BaseHTTPServer
def http_server(port, username, password, response):
storage = {}
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
def _checks(self):
if not self._check_auth():
return False
elif not self._check_errors():
return False
else:
return True
def _check_auth(self):
if self.path.startswith('/auth'):
authorization = self.headers.get('authorization', None)
if authorization is not None:
auth_type, credentials = authorization.split(None, 1)
if auth_type.lower() == 'basic':
auth_user, auth_pass = credentials.decode('base64').split(':', 1)
if username == auth_user and password == auth_pass:
return True
self.send_response(401)
self.send_header('WWW-Authenticate', 'Basic realm="Fake HTTP Server"')
self.end_headers()
self.wfile.close()
return False
return True
def _check_errors(self):
if self.path.startswith('/badrequest'):
self.send_response(400)
self.end_headers()
self.wfile.close()
return False
elif self.path.startswith('/notfound'):
self.send_response(404)
self.end_headers()
self.wfile.close()
return False
elif self.path.startswith('/invaliderror'):
self.send_response(444)
self.end_headers()
self.wfile.close()
return False
return True
def do_POST(self):
if not self._checks():
return
input_data = self.rfile.read(int(self.headers.get('content-length')))
self.send_response(200)
self.end_headers()
self.wfile.write(input_data.encode('rot13'))
self.wfile.close()
def do_PUT(self):
if not self._checks():
return
input_data = self.rfile.read(int(self.headers.get('content-length')))
storage[self.path] = input_data
self.send_response(200)
self.end_headers()
self.wfile.write('PUT OK')
self.wfile.close()
def do_GET(self):
if not self._checks():
return
self.send_response(200)
self.end_headers()
if self.path in storage:
self.wfile.write(storage[self.path])
else:
self.wfile.write(response)
self.wfile.close()
def log_request(*args):
pass
BaseHTTPServer.HTTPServer(('127.0.0.1', port), Handler).serve_forever()
class Test_HttpClient(unittest.TestCase):
USERNAME = 'john'
PASSWORD = 'secret'
PORT = 9876
URI_BASE = 'http://localhost:%(PORT)d' % locals()
RESPONSE = 'Test_GET-HTTP-Response-Content'
DUMMYDATA = 'fq28cnyp3ya8ltcy;ny2t8ay;iweuycowtc'
def setUp(self):
self.server_process = multiprocessing.Process(target=http_server,
args=(self.PORT, self.USERNAME, self.PASSWORD, self.RESPONSE))
self.server_process.start()
import time
time.sleep(.1)
def tearDown(self):
self.server_process.terminate()
import time
time.sleep(.1)
def test_UnknownResponse(self):
client = http.HttpClient()
path = self.URI_BASE+'/invaliderror'
self.assertRaises(http.UnknownResponse, client.GET, path)
def test_NotFound(self):
client = http.HttpClient()
path = self.URI_BASE+'/notfound'
self.assertRaises(http.NotFound, client.GET, path)
def test_Unauthorized(self):
client = http.HttpClient('invalid-username', 'invalid-password')
path = self.URI_BASE+'/auth'
self.assertRaises(http.Unauthorized, client.GET, path)
def test_BadRequest(self):
client = http.HttpClient()
path = self.URI_BASE+'/badrequest'
self.assertRaises(http.BadRequest, client.GET, path)
def test_GET(self):
client = http.HttpClient()
path = self.URI_BASE+'/noauth'
self.assertEquals(client.GET(path), self.RESPONSE)
def test_authenticated_GET(self):
client = http.HttpClient(self.USERNAME, self.PASSWORD)
path = self.URI_BASE+'/auth'
self.assertEquals(client.GET(path), self.RESPONSE)
def test_unauthenticated_GET(self):
client = http.HttpClient()
path = self.URI_BASE+'/auth'
self.assertRaises(http.Unauthorized, client.GET, path)
def test_POST(self):
client = http.HttpClient()
path = self.URI_BASE+'/noauth'
self.assertEquals(client.POST(path, self.DUMMYDATA), self.DUMMYDATA.encode('rot13'))
def test_authenticated_POST(self):
client = http.HttpClient(self.USERNAME, self.PASSWORD)
path = self.URI_BASE+'/auth'
self.assertEquals(client.POST(path, self.DUMMYDATA), self.DUMMYDATA.encode('rot13'))
def test_unauthenticated_POST(self):
client = http.HttpClient()
path = self.URI_BASE+'/auth'
self.assertRaises(http.Unauthorized, client.POST, path, self.DUMMYDATA)
def test_PUT(self):
client = http.HttpClient()
path = self.URI_BASE+'/noauth'
self.assertEquals(client.PUT(path, self.DUMMYDATA), 'PUT OK')
def test_GET_after_PUT(self):
client = http.HttpClient()
for i in range(10):
path = self.URI_BASE + '/file.%(i)d.txt' % locals()
client.PUT(path, self.RESPONSE + str(i))
self.assertEquals(client.GET(path), self.RESPONSE + str(i))
mygpoclient-1.7/mygpoclient/simple_test.py 0000664 0001751 0001751 00000013113 12105162624 020561 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from mygpoclient import simple
from mygpoclient import testing
import unittest
class Test_Podcast(unittest.TestCase):
def test_podcastFromDict_raisesValueError_missingKey(self):
self.assertRaises(ValueError,
simple.Podcast.from_dict, {'url': 'a', 'title': 'b'})
class Test_SimpleClient(unittest.TestCase):
USERNAME = 'a'
PASSWORD = 'b'
DEVICE_NAME = 'x'
SUBSCRIPTIONS = [
'http://lugradio.org/episodes.rss',
'http://feeds2.feedburner.com/LinuxOutlaws',
]
SUBSCRIPTIONS_JSON = """
["http://lugradio.org/episodes.rss",
"http://feeds2.feedburner.com/LinuxOutlaws"]
"""
SUGGESTIONS = [
simple.Podcast('http://feeds.feedburner.com/linuxoutlaws',
'Linux Outlaws',
'Open source talk with a serious attitude',
'http://linuxoutlaws.com/podcast',
1736, 1736,
'http://www.gpodder.net/podcast/11092',
'http://linuxoutlaws.com/files/albumart-itunes.jpg'),
simple.Podcast('http://feeds.twit.tv/floss_video_large',
'FLOSS Weekly Video (large)',
'We are not talking dentistry here; FLOSS all about Free Libre Open Source Software. Join hosts Randal Schwartz and Leo Laporte every Saturday as they talk with the most interesting and important people in the Open Source and Free Software community.',
'http://syndication.mediafly.com/redirect/show/d581e9b773784df7a56f37e1138c037c',
50, 50,
'http://www.gpodder.net/podcast/31991',
'http://static.mediafly.com/publisher/images/06cecab60c784f9d9866f5dcb73227c3/icon-150x150.png'),
]
SUGGESTIONS_JSON = """
[{
"website": "http://linuxoutlaws.com/podcast",
"description": "Open source talk with a serious attitude",
"title": "Linux Outlaws",
"url": "http://feeds.feedburner.com/linuxoutlaws",
"subscribers_last_week": 1736,
"subscribers": 1736,
"mygpo_link": "http://www.gpodder.net/podcast/11092",
"logo_url": "http://linuxoutlaws.com/files/albumart-itunes.jpg"
},
{
"website": "http://syndication.mediafly.com/redirect/show/d581e9b773784df7a56f37e1138c037c",
"description": "We are not talking dentistry here; FLOSS all about Free Libre Open Source Software. Join hosts Randal Schwartz and Leo Laporte every Saturday as they talk with the most interesting and important people in the Open Source and Free Software community.",
"title": "FLOSS Weekly Video (large)",
"url": "http://feeds.twit.tv/floss_video_large",
"subscribers_last_week": 50,
"subscribers": 50,
"mygpo_link": "http://www.gpodder.net/podcast/31991",
"logo_url": "http://static.mediafly.com/publisher/images/06cecab60c784f9d9866f5dcb73227c3/icon-150x150.png"
}]
"""
def setUp(self):
self.fake_client = testing.FakeJsonClient()
self.client = simple.SimpleClient(self.USERNAME, self.PASSWORD,
client_class=self.fake_client)
def test_putSubscriptions(self):
self.fake_client.response_value = ''
result = self.client.put_subscriptions(self.DEVICE_NAME, self.SUBSCRIPTIONS)
self.assertEquals(result, True)
self.assertEquals(len(self.fake_client.requests), 1)
def test_getSubscriptions(self):
self.fake_client.response_value = self.SUBSCRIPTIONS_JSON
subscriptions = self.client.get_subscriptions(self.DEVICE_NAME)
self.assertEquals(subscriptions, self.SUBSCRIPTIONS)
self.assertEquals(len(self.fake_client.requests), 1)
def test_getSuggestions(self):
self.fake_client.response_value = self.SUGGESTIONS_JSON
suggestions = self.client.get_suggestions(50)
self.assertEquals(suggestions, self.SUGGESTIONS)
self.assertEquals(len(self.fake_client.requests), 1)
class Test_MissingCredentials(unittest.TestCase):
DEVICE_NAME = 'unit-test-device'
def test_getSubscriptions_UserAndPassAreNone(self):
client = simple.SimpleClient(None, None, client_class=testing.FakeJsonClient())
self.assertRaises(simple.MissingCredentials, client.get_subscriptions, (self.DEVICE_NAME,))
def test_getSubscriptions_EmptyUserAndPass(self):
client = simple.SimpleClient('', '', client_class=testing.FakeJsonClient())
self.assertRaises(simple.MissingCredentials, client.get_subscriptions, (self.DEVICE_NAME,))
def test_getSubscriptions_EmptyPassword(self):
client = simple.SimpleClient('user', '', client_class=testing.FakeJsonClient())
self.assertRaises(simple.MissingCredentials, client.get_subscriptions, (self.DEVICE_NAME,))
def test_getSubscriptions_EmptyUsername(self):
client = simple.SimpleClient('', 'pass', client_class=testing.FakeJsonClient())
self.assertRaises(simple.MissingCredentials, client.get_subscriptions, (self.DEVICE_NAME,))
mygpoclient-1.7/mygpoclient/api.py 0000664 0001751 0001751 00000037402 12105161764 017015 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import mygpoclient
from mygpoclient import util
from mygpoclient import simple
from mygpoclient import public
# Additional error types for the advanced API client
class InvalidResponse(Exception): pass
class UpdateResult(object):
"""Container for subscription update results
Attributes:
update_urls - A list of (old_url, new_url) tuples
since - A timestamp value for use in future requests
"""
def __init__(self, update_urls, since):
self.update_urls = update_urls
self.since = since
class SubscriptionChanges(object):
"""Container for subscription changes
Attributes:
add - A list of URLs that have been added
remove - A list of URLs that have been removed
since - A timestamp value for use in future requests
"""
def __init__(self, add, remove, since):
self.add = add
self.remove = remove
self.since = since
class EpisodeActionChanges(object):
"""Container for added episode actions
Attributes:
actions - A list of EpisodeAction objects
since - A timestamp value for use in future requests
"""
def __init__(self, actions, since):
self.actions = actions
self.since = since
class PodcastDevice(object):
"""This class encapsulates a podcast device
Attributes:
device_id - The ID used to refer to this device
caption - A user-defined "name" for this device
type - A valid type of podcast device (see VALID_TYPES)
subscriptions - The number of podcasts this device is subscribed to
"""
VALID_TYPES = ('desktop', 'laptop', 'mobile', 'server', 'other')
def __init__(self, device_id, caption, type, subscriptions):
# Check if the device type is valid
if type not in self.VALID_TYPES:
raise ValueError('Invalid device type "%s" (see VALID_TYPES)' % type)
# Check if subsciptions is a numeric value
try:
int(subscriptions)
except:
raise ValueError('Subscription must be a numeric value but was %s' % subscriptions)
self.device_id = device_id
self.caption = caption
self.type = type
self.subscriptions = int(subscriptions)
def __str__(self):
"""String representation of this device
>>> device = PodcastDevice('mygpo', 'My Device', 'mobile', 10)
>>> print device
PodcastDevice('mygpo', 'My Device', 'mobile', 10)
"""
return '%s(%r, %r, %r, %r)' % (self.__class__.__name__,
self.device_id, self.caption, self.type, self.subscriptions)
@classmethod
def from_dictionary(cls, d):
return cls(d['id'], d['caption'], d['type'], d['subscriptions'])
class EpisodeAction(object):
"""This class encapsulates an episode action
The mandatory attributes are:
podcast - The feed URL of the podcast
episode - The enclosure URL or GUID of the episode
action - One of 'download', 'play', 'delete' or 'new'
The optional attributes are:
device - The device_id on which the action has taken place
timestamp - When the action took place (in XML time format)
started - The start time of a play event in seconds
position - The current position of a play event in seconds
total - The total time of the episode (for play events)
The attribute "position" is only valid for "play" action types.
"""
VALID_ACTIONS = ('download', 'play', 'delete', 'new', 'flattr')
def __init__(self, podcast, episode, action,
device=None, timestamp=None,
started=None, position=None, total=None):
# Check if the action is valid
if action not in self.VALID_ACTIONS:
raise ValueError('Invalid action type "%s" (see VALID_ACTIONS)' % action)
# Disallow play-only attributes for non-play actions
if action != 'play':
if started is not None:
raise ValueError('Started can only be set for the "play" action')
elif position is not None:
raise ValueError('Position can only be set for the "play" action')
elif total is not None:
raise ValueError('Total can only be set for the "play" action')
# Check the format of the timestamp value
if timestamp is not None:
if util.iso8601_to_datetime(timestamp) is None:
raise ValueError('Timestamp has to be in ISO 8601 format but was %s' % timestamp)
# Check if we have a "position" value if we have started or total
if position is None and (started is not None or total is not None):
raise ValueError('Started or total set, but no position given')
# Check that "started" is a number if it's set
if started is not None:
try:
started = int(started)
except ValueError:
raise ValueError('Started must be an integer value (seconds) but was %s' % started)
# Check that "position" is a number if it's set
if position is not None:
try:
position = int(position)
except ValueError:
raise ValueError('Position must be an integer value (seconds) but was %s' % position)
# Check that "total" is a number if it's set
if total is not None:
try:
total = int(total)
except ValueError:
raise ValueError('Total must be an integer value (seconds) but was %s' % total)
self.podcast = podcast
self.episode = episode
self.action = action
self.device = device
self.timestamp = timestamp
self.started = started
self.position = position
self.total = total
@classmethod
def from_dictionary(cls, d):
return cls(d['podcast'], d['episode'], d['action'],
d.get('device'), d.get('timestamp'),
d.get('started'), d.get('position'), d.get('total'))
def to_dictionary(self):
d = {}
for mandatory in ('podcast', 'episode', 'action'):
value = getattr(self, mandatory)
d[mandatory] = value
for optional in ('device', 'timestamp',
'started', 'position', 'total'):
value = getattr(self, optional)
if value is not None:
d[optional] = value
return d
class MygPodderClient(simple.SimpleClient):
"""gpodder.net API Client
This is the API client that implements both the Simple and
Advanced API of gpodder.net. See the SimpleClient class
for a smaller class that only implements the Simple API.
"""
@simple.needs_credentials
def get_subscriptions(self, device):
# Overloaded to accept PodcastDevice objects as arguments
device = getattr(device, 'device_id', device)
return simple.SimpleClient.get_subscriptions(self, device)
@simple.needs_credentials
def put_subscriptions(self, device, urls):
# Overloaded to accept PodcastDevice objects as arguments
device = getattr(device, 'device_id', device)
return simple.SimpleClient.put_subscriptions(self, device, urls)
@simple.needs_credentials
def update_subscriptions(self, device_id, add_urls=[], remove_urls=[]):
"""Update the subscription list for a given device.
Returns a UpdateResult object that contains a list of (sanitized)
URLs and a "since" value that can be used for future calls to
pull_subscriptions.
For every (old_url, new_url) tuple in the updated_urls list of
the resulting object, the client should rewrite the URL in its
subscription list so that new_url is used instead of old_url.
"""
uri = self._locator.add_remove_subscriptions_uri(device_id)
if not all(isinstance(x, basestring) for x in add_urls):
raise ValueError('add_urls must be a list of strings but was %s' % add_urls)
if not all(isinstance(x, basestring) for x in remove_urls):
raise ValueError('remove_urls must be a list of strings but was %s' % remove_urls)
data = {'add': add_urls, 'remove': remove_urls}
response = self._client.POST(uri, data)
if response is None:
raise InvalidResponse('Got empty response')
if 'timestamp' not in response:
raise InvalidResponse('Response does not contain timestamp')
try:
since = int(response['timestamp'])
except ValueError:
raise InvalidResponse('Invalid value %s for timestamp in response' % response['timestamp'])
if 'update_urls' not in response:
raise InvalidResponse('Response does not contain update_urls')
try:
update_urls = [(a, b) for a, b in response['update_urls']]
except:
raise InvalidResponse('Invalid format of update_urls in response: %s' % response['update_urls'])
if not all(isinstance(a, basestring) and isinstance(b, basestring) \
for a, b in update_urls):
raise InvalidResponse('Invalid format of update_urls in response: %s' % update_urls)
return UpdateResult(update_urls, since)
@simple.needs_credentials
def pull_subscriptions(self, device_id, since=None):
"""Downloads subscriptions since the time of the last update
The "since" parameter should be a timestamp that has been
retrieved previously by a call to update_subscriptions or
pull_subscriptions.
Returns a SubscriptionChanges object with two lists (one for
added and one for removed podcast URLs) and a "since" value
that can be used for future calls to this method.
"""
uri = self._locator.subscription_updates_uri(device_id, since)
data = self._client.GET(uri)
if data is None:
raise InvalidResponse('Got empty response')
if 'add' not in data:
raise InvalidResponse('List of added podcasts not in response')
if 'remove' not in data:
raise InvalidResponse('List of removed podcasts not in response')
if 'timestamp' not in data:
raise InvalidResponse('Timestamp missing from response')
if not all(isinstance(x, basestring) for x in data['add']):
raise InvalidResponse('Invalid value(s) in list of added podcasts: %s' % data['add'])
if not all(isinstance(x, basestring) for x in data['remove']):
raise InvalidResponse('Invalid value(s) in list of removed podcasts: %s' % data['remove'])
try:
since = int(data['timestamp'])
except ValueError:
raise InvalidResponse('Timestamp has invalid format in response: %s' % data['timestamp'])
return SubscriptionChanges(data['add'], data['remove'], since)
@simple.needs_credentials
def upload_episode_actions(self, actions=[]):
"""Uploads a list of EpisodeAction objects to the server
Returns the timestamp that can be used for retrieving changes.
"""
uri = self._locator.upload_episode_actions_uri()
actions = [action.to_dictionary() for action in actions]
response = self._client.POST(uri, actions)
if response is None:
raise InvalidResponse('Got empty response')
if 'timestamp' not in response:
raise InvalidResponse('Response does not contain timestamp')
try:
since = int(response['timestamp'])
except ValueError:
raise InvalidResponse('Invalid value %s for timestamp in response' % response['timestamp'])
return since
@simple.needs_credentials
def download_episode_actions(self, since=None,
podcast=None, device_id=None):
"""Downloads a list of EpisodeAction objects from the server
Returns a EpisodeActionChanges object with the list of
new actions and a "since" timestamp that can be used for
future calls to this method when retrieving episodes.
"""
uri = self._locator.download_episode_actions_uri(since,
podcast, device_id)
data = self._client.GET(uri)
if data is None:
raise InvalidResponse('Got empty response')
if 'actions' not in data:
raise InvalidResponse('Response does not contain actions')
if 'timestamp' not in data:
raise InvalidResponse('Response does not contain timestamp')
try:
since = int(data['timestamp'])
except ValueError:
raise InvalidResponse('Invalid value for timestamp: ' +
data['timestamp'])
dicts = data['actions']
try:
actions = [EpisodeAction.from_dictionary(d) for d in dicts]
except KeyError:
raise InvalidResponse('Missing keys in action list response')
return EpisodeActionChanges(actions, since)
@simple.needs_credentials
def update_device_settings(self, device_id, caption=None, type=None):
"""Update the description of a device on the server
This changes the caption and/or type of a given device
on the server. If the device does not exist, it is
created with the given settings.
The parameters caption and type are both optional and
when set to a value other than None will be used to
update the device settings.
Returns True if the request succeeded, False otherwise.
"""
uri = self._locator.device_settings_uri(device_id)
data = {}
if caption is not None:
data['caption'] = caption
if type is not None:
data['type'] = type
return (self._client.POST(uri, data) is None)
@simple.needs_credentials
def get_devices(self):
"""Returns a list of this user's PodcastDevice objects
The resulting list can be used to display a selection
list to the user or to determine device IDs to pull
the subscription list from.
"""
uri = self._locator.device_list_uri()
dicts = self._client.GET(uri)
if dicts is None:
raise InvalidResponse('No response received')
try:
return [PodcastDevice.from_dictionary(d) for d in dicts]
except KeyError:
raise InvalidResponse('Missing keys in device list response')
def get_favorite_episodes(self):
"""Returns a List of Episode Objects containing the Users
favorite Episodes"""
uri = self._locator.favorite_episodes_uri()
return [public.Episode.from_dict(d) for d in self._client.GET(uri)]
def get_settings(self, type, scope_param1=None, scope_param2=None):
"""Returns a Dictionary with the set settings for the type & specified scope"""
uri = self._locator.settings_uri(type, scope_param1, scope_param2)
return self._client.GET(uri)
def set_settings(self, type, scope_param1, scope_param2, set={}, remove=[]):
"""Returns a Dictionary with the set settings for the type & specified scope"""
uri = self._locator.settings_uri(type, scope_param1, scope_param2)
data = {}
data["set"] = set
data["remove"] = remove
return self._client.POST(uri, data)
mygpoclient-1.7/mygpoclient/json.py 0000664 0001751 0001751 00000005525 12105161764 017216 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
# Fix gPodder bug 900 (so "import json" doesn't import this module)
from __future__ import absolute_import
import mygpoclient
try:
# Prefer the usage of the simplejson module, as it
# is most likely newer if it's installed as module
# than the built-in json module (and is mandatory
# in Python versions before 2.6, anyway).
import simplejson as json
except ImportError:
# Python 2.6 ships the "json" module by default
import json
from mygpoclient import http
# Additional exceptions for JSON-related errors
class JsonException(Exception): pass
class JsonClient(http.HttpClient):
"""A HttpClient with built-in JSON support
This client will automatically marshal and unmarshal data for
JSON-related web services so that code using this class will
not need to care about (de-)serialization of data structures.
"""
def __init__(self, username=None, password=None):
http.HttpClient.__init__(self, username, password)
@staticmethod
def encode(data):
"""Encodes a object into its JSON string repesentation
>>> JsonClient.encode(None)
''
>>> JsonClient.encode([1,2,3])
'[1, 2, 3]'
>>> JsonClient.encode(42)
'42'
"""
if data is None:
return ''
else:
return json.dumps(data)
@staticmethod
def decode(data):
"""Decodes a response string to a Python object
>>> JsonClient.decode('')
>>> JsonClient.decode('[1,2,3]')
[1, 2, 3]
>>> JsonClient.decode('42')
42
"""
if data == '':
return None
else:
try:
return json.loads(data)
except ValueError, ve:
raise JsonException('Value error while parsing response: ' + data)
@staticmethod
def _prepare_request(method, uri, data):
data = JsonClient.encode(data)
return http.HttpClient._prepare_request(method, uri, data)
@staticmethod
def _process_response(response):
data = http.HttpClient._process_response(response)
return JsonClient.decode(data)
mygpoclient-1.7/mygpoclient/simple.py 0000664 0001751 0001751 00000012544 12105161764 017535 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from functools import wraps
import mygpoclient
from mygpoclient import locator
from mygpoclient import json
class MissingCredentials(Exception):
""" Raised when instantiating a SimpleClient without credentials """
def needs_credentials(f):
""" apply to all methods that initiate requests that require credentials """
@wraps(f)
def _wrapper(self, *args, **kwargs):
if not self.username or not self.password:
raise MissingCredentials
return f(self, *args, **kwargs)
return _wrapper
class Podcast(object):
"""Container class for a podcast
Encapsulates the metadata for a podcast.
Attributes:
url - The URL of the podcast feed
title - The title of the podcast
description - The description of the podcast
"""
REQUIRED_FIELDS = ('url', 'title', 'description', 'website', 'subscribers',
'subscribers_last_week', 'mygpo_link', 'logo_url')
def __init__(self, url, title, description, website, subscribers, subscribers_last_week, mygpo_link, logo_url):
self.url = url
self.title = title
self.description = description
self.website = website
self.subscribers = subscribers
self.subscribers_last_week = subscribers_last_week
self.mygpo_link = mygpo_link
self.logo_url = logo_url
@classmethod
def from_dict(cls, d):
for key in cls.REQUIRED_FIELDS:
if key not in d:
raise ValueError('Missing keys for toplist podcast')
return cls(*(d.get(k) for k in cls.REQUIRED_FIELDS))
def __eq__(self, other):
"""Test two Podcast objects for equality
>>> Podcast('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') == Podcast('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
True
>>> Podcast('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') == Podcast('s', 't', 'u', 'v', 'w', 'x', 'y', 'z')
False
>>> Podcast('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') == 'a'
False
"""
if not isinstance(other, self.__class__):
return False
return all(getattr(self, k) == getattr(other, k) \
for k in self.REQUIRED_FIELDS)
class SimpleClient(object):
"""Client for the gpodder.net Simple API
This is the API client implementation that provides a
pythonic interface to the gpodder.net Simple API.
"""
FORMAT = 'json'
def __init__(self, username, password, host=mygpoclient.HOST,
client_class=json.JsonClient):
"""Creates a new Simple API client
Username and password must be specified and are
the user's login data for the webservice.
The parameter host is optional and defaults to
the main webservice.
The parameter client_class is optional and should
not need to be changed in normal use cases. If it
is changed, it should provide the same interface
as the json.JsonClient class in mygpoclient.
"""
self.username = username
self.password = password
self._locator = locator.Locator(username, host)
self._client = client_class(username, password)
@needs_credentials
def get_subscriptions(self, device_id):
"""Get a list of subscriptions for a device
Returns a list of URLs (one per subscription) for
the given device_id that reflects the current list
of subscriptions.
Raises http.NotFound if the device does not exist.
"""
uri = self._locator.subscriptions_uri(device_id, self.FORMAT)
return self._client.GET(uri)
@needs_credentials
def put_subscriptions(self, device_id, urls):
"""Update a device's subscription list
Sets the server-side subscription list for the device
"device_id" to be equivalent to the URLs in the list of
strings "urls".
The device will be created if it does not yet exist.
Returns True if the update was successful, False otherwise.
"""
uri = self._locator.subscriptions_uri(device_id, self.FORMAT)
return (self._client.PUT(uri, urls) == None)
@needs_credentials
def get_suggestions(self, count=10):
"""Get podcast suggestions for the user
Returns a list of Podcast objects that are
to be suggested to the user.
The parameter count is optional and if
specified has to be a value between 1
and 100 (with 10 being the default), and
determines how much search results are
returned (at maximum).
"""
uri = self._locator.suggestions_uri(count, self.FORMAT)
return [Podcast.from_dict(x) for x in self._client.GET(uri)]
mygpoclient-1.7/mygpoclient/util.py 0000664 0001751 0001751 00000005122 12105161764 017213 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import mygpoclient
import datetime
def join(*args):
"""Join separate URL parts to a ful URL"""
return '/'.join(args)
def iso8601_to_datetime(s):
"""Convert a ISO8601-formatted string to datetime
>>> iso8601_to_datetime('2009-12-29T19:25:33')
datetime.datetime(2009, 12, 29, 19, 25, 33)
>>> iso8601_to_datetime('2009-12-29T19:25:33Z')
datetime.datetime(2009, 12, 29, 19, 25, 33)
>>> iso8601_to_datetime('xXxXxXxXxxxxXxxxXxx')
>>>
"""
for format in ('%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%SZ'):
try:
return datetime.datetime.strptime(s, format)
except ValueError:
continue
return None
def datetime_to_iso8601(dt):
"""Convert a datetime to a ISO8601-formatted string
>>> datetime_to_iso8601(datetime.datetime(2009, 12, 29, 19, 25, 33))
'2009-12-29T19:25:33'
"""
return dt.strftime('%Y-%m-%dT%H:%M:%S')
def position_to_seconds(s):
"""Convert a position string to its amount of seconds
>>> position_to_seconds('00:00:01')
1
>>> position_to_seconds('00:01:00')
60
>>> position_to_seconds('01:00:00')
3600
>>> position_to_seconds('02:59:59')
10799
>>> position_to_seconds('100:00:00')
360000
"""
hours, minutes, seconds = (int(x) for x in s.split(':', 2))
return (((hours*60)+minutes)*60)+seconds
def seconds_to_position(seconds):
"""Convert the amount of seconds to a position string
>>> seconds_to_position(1)
'00:00:01'
>>> seconds_to_position(60)
'00:01:00'
>>> seconds_to_position(60*60)
'01:00:00'
>>> seconds_to_position(59 + 60*59 + 60*60*2)
'02:59:59'
>>> seconds_to_position(60*60*100)
'100:00:00'
"""
minutes = int(seconds/60)
seconds = seconds % 60
hours = int(minutes/60)
minutes = minutes % 60
return '%02d:%02d:%02d' % (hours, minutes, seconds)
mygpoclient-1.7/mygpoclient/public.py 0000664 0001751 0001751 00000015551 12105161764 017523 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import mygpoclient
from mygpoclient import locator
from mygpoclient import json
from mygpoclient import simple
class Tag(object):
"""Container class for a tag in the top tag list
Attributes:
tag - The name of the tag
usage - Usage of the tag
"""
REQUIRED_KEYS = ('tag', 'usage')
def __init__(self, tag, usage):
self.tag = tag
self.usage = usage
@classmethod
def from_dict(cls, d):
for key in cls.REQUIRED_KEYS:
if key not in d:
raise ValueError('Missing keys for tag')
return cls(*(d.get(k) for k in cls.REQUIRED_KEYS))
def __eq__(self, other):
"""Test two tag objects for equality
>>> Tag('u', 123) == Tag('u', 123)
True
>>> Tag('u', 123) == Tag('a', 345)
False
>>> Tag('u', 123) == 'x'
False
"""
if not isinstance(other, self.__class__):
return False
return all(getattr(self, k) == getattr(other, k) \
for k in self.REQUIRED_KEYS)
class Episode(object):
"""Container Class for Episodes
Attributes:
title -
url -
podcast_title -
podcast_url -
description -
website -
released -
mygpo_link -
"""
REQUIRED_KEYS = ('title', 'url', 'podcast_title', 'podcast_url',
'description', 'website', 'released', 'mygpo_link')
def __init__(self, title, url, podcast_title, podcast_url, description, website, released, mygpo_link):
self.title = title
self.url = url
self.podcast_title = podcast_title
self.podcast_url = podcast_url
self.description = description
self.website = website
self.released = released
self.mygpo_link = mygpo_link
@classmethod
def from_dict(cls, d):
for key in cls.REQUIRED_KEYS:
if key not in d:
raise ValueError('Missing keys for episode')
return cls(*(d.get(k) for k in cls.REQUIRED_KEYS))
def __eq__(self, other):
"""Test two Episode objects for equality
>>> Episode('a','b','c','d','e','f','g','h') == Episode('a','b','c','d','e','f','g','h')
True
>>> Episode('a','b','c','d','e','f','g','h') == Episode('s','t','u','v','w','x','y','z')
False
>>> Episode('a','b','c','d','e','f','g','h') == 'x'
False
"""
if not isinstance(other, self.__class__):
return False
return all(getattr(self, k) == getattr(other, k) \
for k in self.REQUIRED_KEYS)
class PublicClient(object):
"""Client for the gpodder.net "anonymous" API
This is the API client implementation that provides a
pythonic interface to the parts of the gpodder.net
Simple API that don't need user authentication.
"""
FORMAT = 'json'
def __init__(self, host=mygpoclient.HOST, client_class=json.JsonClient):
"""Creates a new Public API client
The parameter host is optional and defaults to
the main webservice.
The parameter client_class is optional and should
not need to be changed in normal use cases. If it
is changed, it should provide the same interface
as the json.JsonClient class in mygpoclient.
"""
self._locator = locator.Locator(None, host)
self._client = client_class(None, None)
def get_toplist(self, count=mygpoclient.TOPLIST_DEFAULT):
"""Get a list of most-subscribed podcasts
Returns a list of simple.Podcast objects.
The parameter "count" is optional and describes
the amount of podcasts that are returned. The
default value is 50, the minimum value is 1 and
the maximum value is 100.
"""
uri = self._locator.toplist_uri(count, self.FORMAT)
return [simple.Podcast.from_dict(x) for x in self._client.GET(uri)]
def search_podcasts(self, query):
"""Search for podcasts on the webservice
Returns a list of simple.Podcast objects.
The parameter "query" specifies the search
query as a string.
"""
uri = self._locator.search_uri(query, self.FORMAT)
return [simple.Podcast.from_dict(x) for x in self._client.GET(uri)]
def get_podcasts_of_a_tag(self, tag, count=mygpoclient.TOPLIST_DEFAULT):
"""Get a list of most-subscribed podcasts of a Tag
Returns a list of simple.Podcast objects.
The parameter "tag" specifies the tag as a String
The parameter "count" is optional and describes
the amount of podcasts that are returned. The
default value is 50, the minimum value is 1 and
the maximum value is 100.
"""
uri = self._locator.podcasts_of_a_tag_uri(tag, count)
return [simple.Podcast.from_dict(x) for x in self._client.GET(uri)]
def get_toptags(self, count=mygpoclient.TOPLIST_DEFAULT):
"""Get a list of most-used tags
Returns a list of Tag objects.
The parameter "count" is optional and describes
the amount of podcasts that are returned. The
default value is 50, the minimum value is 1 and
the maximum value is 100.
"""
uri = self._locator.toptags_uri(count)
return [Tag.from_dict(x) for x in self._client.GET(uri)]
def get_podcast_data(self, podcast_uri):
"""Get Metadata for the specified Podcast
Returns a simple.Podcast object.
The parameter "podcast_uri" specifies the URL of the Podcast.
"""
uri = self._locator.podcast_data_uri(podcast_uri)
return simple.Podcast.from_dict(self._client.GET(uri))
def get_episode_data(self, podcast_uri, episode_uri):
"""Get Metadata for the specified Episode
Returns a Episode object.
The parameter "podcast_uri" specifies the URL of the Podcast,
which this Episode belongs to
The parameter "episode_uri" specifies the URL of the Episode
"""
uri = self._locator.episode_data_uri(podcast_uri, episode_uri)
return Episode.from_dict(self._client.GET(uri))
mygpoclient-1.7/mygpoclient/feeds.py 0000664 0001751 0001751 00000012366 12105161764 017334 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# mygpo-feedservice Client
# Copyright (C) 2011 Stefan Kögl
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from __future__ import absolute_import
import urllib, urlparse, time
from datetime import datetime
from email import utils
import mygpoclient.json
try:
# Prefer the usage of the simplejson module, as it
# is most likely newer if it's installed as module
# than the built-in json module (and is mandatory
# in Python versions before 2.6, anyway).
import simplejson as json
except ImportError:
# Python 2.6 ships the "json" module by default
import json
BASE_URL='http://mygpo-feedservice.appspot.com'
class FeedServiceResponse(list):
"""
Encapsulates the relevant data of a mygpo-feedservice response
"""
def __init__(self, feeds, last_modified, feed_urls):
super(FeedServiceResponse, self).__init__(feeds)
self.last_modified = last_modified
self.feed_urls = feed_urls
self.indexed_feeds = {}
for feed in feeds:
for url in feed['urls']:
self.indexed_feeds[url] = feed
def get_feeds(self):
"""
Returns the parsed feeds in order of the initial request
"""
return (self.get_feed(url) for url in self.feed_urls)
def get_feed(self, url):
"""
Returns the parsed feed for the given URL
"""
return self.indexed_feeds.get(url, None)
class FeedserviceClient(mygpoclient.json.JsonClient):
"""A special-cased JsonClient for mygpo-feedservice"""
def __init__(self, username=None, password=None, base_url=BASE_URL):
self._base_url = base_url
super(FeedserviceClient, self).__init__(username, password)
def _prepare_request(self, method, uri, data):
"""Sets headers required by mygpo-feedservice
Expects a dict with keys feed_urls and (optionally) last_modified"""
# send URLs as POST data to avoid any length
# restrictions for the query parameters
post_data = [('url', feed_url) for feed_url in data['feed_urls']]
post_data = urllib.urlencode(post_data)
# call _prepare_request directly from HttpClient, because
# JsonClient would JSON-encode our POST-data
request = mygpoclient.http.HttpClient._prepare_request(method, uri, post_data)
request.add_header('Accept', 'application/json')
request.add_header('Accept-Encoding', 'gzip')
last_modified = data.get('last_modified', None)
if last_modified is not None:
request.add_header('If-Modified-Since', self.format_header_date(last_modified))
return request
def _process_response(self, response):
""" Extract Last-modified header and passes response body
to JsonClient for decoding"""
last_modified = self.parse_header_date(response.headers['last-modified'])
feeds = super(FeedserviceClient, self)._process_response(response)
return feeds, last_modified
def parse_feeds(self, feed_urls, last_modified=None, strip_html=False,
use_cache=True, inline_logo=False, scale_logo=None,
logo_format=None):
"""
Passes the given feed-urls to mygpo-feedservice to be parsed
and returns the response
"""
url = self.build_url(strip_html=strip_html, use_cache=use_cache,
inline_logo=inline_logo, scale_logo=scale_logo,
logo_format=logo_format)
request_data = dict(feed_urls=feed_urls, last_modified=last_modified)
feeds, last_modified = self.POST(url, request_data)
return FeedServiceResponse(feeds, last_modified, feed_urls)
def build_url(self, **kwargs):
"""
Parameter such as strip_html, scale_logo, etc are pased as kwargs
"""
query_url = urlparse.urljoin(self._base_url, 'parse')
args = kwargs.items()
args = filter(lambda (k, v): v is not None, args)
# boolean flags are represented as 1 and 0 in the query-string
args = map(lambda (k, v): (k, int(v) if isinstance(v, bool) else v), args)
args = urllib.urlencode(dict(args))
url = '%s?%s' % (query_url, args)
return url
@staticmethod
def parse_header_date(date_str):
"""
Parses dates in RFC2822 format to datetime objects
"""
if not date_str:
return None
ts = time.mktime(utils.parsedate(date_str))
return datetime.utcfromtimestamp(ts)
@staticmethod
def format_header_date(datetime_obj):
"""
Formats the given datetime object for use in HTTP headers
"""
return utils.formatdate(time.mktime(datetime_obj.timetuple()))
mygpoclient-1.7/mygpoclient/locator_test.py 0000664 0001751 0001751 00000006727 12105161764 020754 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from mygpoclient import locator
import unittest
class Test_Exceptions(unittest.TestCase):
def setUp(self):
self.locator = locator.Locator('jane')
def test_subscriptions_uri_exceptions(self):
"""Test if unsupported formats raise a ValueError"""
self.assertRaises(ValueError,
self.locator.subscriptions_uri, 'gpodder', 'html')
def test_toplist_uri_exceptions(self):
"""Test if unsupported formats raise a ValueError"""
self.assertRaises(ValueError,
self.locator.toplist_uri, 10, 'html')
def test_suggestions_uri_exceptions(self):
"""Test if unsupported formats raise a ValueError"""
self.assertRaises(ValueError,
self.locator.suggestions_uri, 20, 'jpeg')
def test_search_uri_exception(self):
"""Test if unsupported formats raise a ValueError"""
self.assertRaises(ValueError,
self.locator.search_uri, 30, 'mp3')
def test_subscription_updates_uri_exceptions(self):
"""Test if wrong "since" values raise a ValueError"""
self.assertRaises(ValueError,
self.locator.subscription_updates_uri, 'ipod', 'anytime')
def test_download_episode_actions_uri_exceptions(self):
"""Test if using both "podcast" and "device_id" raises a ValueError"""
self.assertRaises(ValueError,
self.locator.download_episode_actions_uri,
podcast='http://example.org/episodes.rss',
device_id='gpodder')
def test_device_settings_uri_exception(self):
"""Test if using no parameter for a device Setting raises a ValueError"""
self.assertRaises(ValueError,
self.locator.settings_uri, type='device',
scope_param1=None, scope_param2=None)
def test_podcast_settings_uri_exception(self):
"""Test if using no parameter for a podcast Setting raises a ValueError"""
self.assertRaises(ValueError,
self.locator.settings_uri, type='podcast',
scope_param1=None, scope_param2=None)
def test_episode_settings_uri_exception(self):
"""Test if only using one parameter for a episode Setting raises a ValueError"""
self.assertRaises(ValueError,
self.locator.settings_uri, type='episode',
scope_param1='http://www.podcast.com', scope_param2=None)
def test_unsupported_settings_uri_exception2(self):
"""Test if unsupported setting type raises a ValueError"""
self.assertRaises(ValueError,
self.locator.settings_uri, type='foobar',
scope_param1=None, scope_param2=None)
mygpoclient-1.7/mygpoclient/testing.py 0000664 0001751 0001751 00000003372 12105161764 017720 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from mygpoclient import json
class FakeJsonClient(object):
"""Fake implementation of a JsonClient used for testing
Set the response using response_value and check the list
of requests this object got using the requests list.
"""
def __init__(self):
self.requests = []
self.response_value = ''
def __call__(self, *args, **kwargs):
"""Fake a constructor for an existing object
>>> fake_class = FakeJsonClient()
>>> fake_object = fake_class('username', 'password')
>>> fake_object == fake_class
True
"""
return self
def _request(self, method, uri, data):
self.requests.append((method, uri, data))
data = json.JsonClient.encode(data)
return json.JsonClient.decode(self.response_value)
def GET(self, uri):
return self._request('GET', uri, None)
def POST(self, uri, data):
return self._request('POST', uri, data)
def PUT(self, uri, data):
return self._request('PUT', uri, data)
mygpoclient-1.7/mygpoclient/locator.py 0000664 0001751 0001751 00000031101 12105161764 017675 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import mygpoclient
import os
import urllib
from mygpoclient import util
class Locator(object):
"""URI Locator for API endpoints
This helper class abstracts the URIs for the gpodder.net
webservice and provides a nice facility for generating API
URIs and checking parameters.
"""
SIMPLE_FORMATS = ('opml', 'json', 'txt')
SETTINGS_TYPES = ('account', 'device', 'podcast', 'episode')
def __init__(self, username, host=mygpoclient.HOST,
version=mygpoclient.VERSION):
self._username = username
self._simple_base = 'http://%(host)s' % locals()
self._base = 'http://%(host)s/api/%(version)s' % locals()
def _convert_since(self, since):
"""Convert "since" into a numeric value
This is internally used for value-checking.
"""
try:
return int(since)
except ValueError:
raise ValueError('since must be a numeric value (or None)')
def subscriptions_uri(self, device_id, format='opml'):
"""Get the Simple API URI for a subscription list
>>> locator = Locator('john')
>>> locator.subscriptions_uri('n800')
'http://gpodder.net/subscriptions/john/n800.opml'
>>> locator.subscriptions_uri('ipod', 'txt')
'http://gpodder.net/subscriptions/john/ipod.txt'
"""
if format not in self.SIMPLE_FORMATS:
raise ValueError('Unsupported file format')
filename = '%(device_id)s.%(format)s' % locals()
return util.join(self._simple_base,
'subscriptions', self._username, filename)
def toplist_uri(self, count=50, format='opml'):
"""Get the Simple API URI for the toplist
>>> locator = Locator(None)
>>> locator.toplist_uri()
'http://gpodder.net/toplist/50.opml'
>>> locator.toplist_uri(70)
'http://gpodder.net/toplist/70.opml'
>>> locator.toplist_uri(10, 'json')
'http://gpodder.net/toplist/10.json'
"""
if format not in self.SIMPLE_FORMATS:
raise ValueError('Unsupported file format')
filename = 'toplist/%(count)d.%(format)s' % locals()
return util.join(self._simple_base, filename)
def suggestions_uri(self, count=10, format='opml'):
"""Get the Simple API URI for user suggestions
>>> locator = Locator('john')
>>> locator.suggestions_uri()
'http://gpodder.net/suggestions/10.opml'
>>> locator.suggestions_uri(50)
'http://gpodder.net/suggestions/50.opml'
>>> locator.suggestions_uri(70, 'json')
'http://gpodder.net/suggestions/70.json'
"""
if format not in self.SIMPLE_FORMATS:
raise ValueError('Unsupported file format')
filename = 'suggestions/%(count)d.%(format)s' % locals()
return util.join(self._simple_base, filename)
def search_uri(self, query, format='opml'):
"""Get the Simple API URI for podcast search
>>> locator = Locator(None)
>>> locator.search_uri('outlaws')
'http://gpodder.net/search.opml?q=outlaws'
>>> locator.search_uri(':something?', 'txt')
'http://gpodder.net/search.txt?q=%3Asomething%3F'
>>> locator.search_uri('software engineering', 'json')
'http://gpodder.net/search.json?q=software+engineering'
"""
if format not in self.SIMPLE_FORMATS:
raise ValueError('Unsupported file format')
query = urllib.quote_plus(query)
filename = 'search.%(format)s?q=%(query)s' % locals()
return util.join(self._simple_base, filename)
def add_remove_subscriptions_uri(self, device_id):
"""Get the Advanced API URI for uploading list diffs
>>> locator = Locator('bill')
>>> locator.add_remove_subscriptions_uri('n810')
'http://gpodder.net/api/2/subscriptions/bill/n810.json'
"""
filename = '%(device_id)s.json' % locals()
return util.join(self._base,
'subscriptions', self._username, filename)
def subscription_updates_uri(self, device_id, since=None):
"""Get the Advanced API URI for downloading list diffs
The parameter "since" is optional and should be a numeric
value (otherwise a ValueError is raised).
>>> locator = Locator('jen')
>>> locator.subscription_updates_uri('n900')
'http://gpodder.net/api/2/subscriptions/jen/n900.json'
>>> locator.subscription_updates_uri('n900', 1234)
'http://gpodder.net/api/2/subscriptions/jen/n900.json?since=1234'
"""
filename = '%(device_id)s.json' % locals()
if since is not None:
since = self._convert_since(since)
filename += '?since=%(since)d' % locals()
return util.join(self._base,
'subscriptions', self._username, filename)
def upload_episode_actions_uri(self):
"""Get the Advanced API URI for uploading episode actions
>>> locator = Locator('thp')
>>> locator.upload_episode_actions_uri()
'http://gpodder.net/api/2/episodes/thp.json'
"""
filename = self._username + '.json'
return util.join(self._base, 'episodes', filename)
def download_episode_actions_uri(self, since=None,
podcast=None, device_id=None):
"""Get the Advanced API URI for downloading episode actions
The parameter "since" is optional and should be a numeric
value (otherwise a ValueError is raised).
Both "podcast" and "device_id" are optional and exclusive:
"podcast" should be a podcast URL
"device_id" should be a device ID
>>> locator = Locator('steve')
>>> locator.download_episode_actions_uri()
'http://gpodder.net/api/2/episodes/steve.json'
>>> locator.download_episode_actions_uri(since=1337)
'http://gpodder.net/api/2/episodes/steve.json?since=1337'
>>> locator.download_episode_actions_uri(podcast='http://example.org/episodes.rss')
'http://gpodder.net/api/2/episodes/steve.json?podcast=http%3A//example.org/episodes.rss'
>>> locator.download_episode_actions_uri(since=2000, podcast='http://example.com/')
'http://gpodder.net/api/2/episodes/steve.json?since=2000&podcast=http%3A//example.com/'
>>> locator.download_episode_actions_uri(device_id='ipod')
'http://gpodder.net/api/2/episodes/steve.json?device=ipod'
>>> locator.download_episode_actions_uri(since=54321, device_id='ipod')
'http://gpodder.net/api/2/episodes/steve.json?since=54321&device=ipod'
"""
if podcast is not None and device_id is not None:
raise ValueError('must not specify both "podcast" and "device_id"')
filename = self._username + '.json'
params = []
if since is not None:
since = str(self._convert_since(since))
params.append(('since', since))
if podcast is not None:
params.append(('podcast', podcast))
if device_id is not None:
params.append(('device', device_id))
if params:
filename += '?' + '&'.join('%s=%s' % (key, urllib.quote(value)) for key, value in params)
return util.join(self._base, 'episodes', filename)
def device_settings_uri(self, device_id):
"""Get the Advanced API URI for setting per-device settings uploads
>>> locator = Locator('mike')
>>> locator.device_settings_uri('ipod')
'http://gpodder.net/api/2/devices/mike/ipod.json'
"""
filename = '%(device_id)s.json' % locals()
return util.join(self._base, 'devices', self._username, filename)
def device_list_uri(self):
"""Get the Advanced API URI for retrieving the device list
>>> locator = Locator('jeff')
>>> locator.device_list_uri()
'http://gpodder.net/api/2/devices/jeff.json'
"""
filename = self._username + '.json'
return util.join(self._base, 'devices', filename)
def toptags_uri(self, count=50):
"""Get the Advanced API URI for retrieving the top Tags
>>> locator = Locator(None)
>>> locator.toptags_uri()
'http://gpodder.net/api/2/tags/50.json'
>>> locator.toptags_uri(70)
'http://gpodder.net/api/2/tags/70.json'
"""
filename = '%(count)d.json' % locals()
return util.join(self._base, 'tags', filename)
def podcasts_of_a_tag_uri(self, tag, count=50):
"""Get the Advanced API URI for retrieving the top Podcasts of a Tag
>>> locator = Locator(None)
>>> locator.podcasts_of_a_tag_uri('linux')
'http://gpodder.net/api/2/tag/linux/50.json'
>>> locator.podcasts_of_a_tag_uri('linux',70)
'http://gpodder.net/api/2/tag/linux/70.json'
"""
filename = '%(tag)s/%(count)d.json' % locals()
return util.join(self._base, 'tag', filename)
def podcast_data_uri(self, podcast_url):
"""Get the Advanced API URI for retrieving Podcast Data
>>> locator = Locator(None)
>>> locator.podcast_data_uri('http://podcast.com')
'http://gpodder.net/api/2/data/podcast.json?url=http%3A//podcast.com'
"""
filename = 'podcast.json?url=%s' % urllib.quote(podcast_url)
return util.join(self._base, 'data', filename)
def episode_data_uri(self, podcast_url, episode_url):
"""Get the Advanced API URI for retrieving Episode Data
>>> locator = Locator(None)
>>> locator.episode_data_uri('http://podcast.com','http://podcast.com/foo')
'http://gpodder.net/api/2/data/episode.json?podcast=http%3A//podcast.com&url=http%3A//podcast.com/foo'
"""
filename = 'episode.json?podcast=%s&url=%s' % (urllib.quote(podcast_url), urllib.quote(episode_url))
return util.join(self._base, 'data', filename)
def favorite_episodes_uri(self):
"""Get the Advanced API URI for listing favorite episodes
>>> locator = Locator('mike')
>>> locator.favorite_episodes_uri()
'http://gpodder.net/api/2/favorites/mike.json'
"""
filename = self._username + '.json'
return util.join(self._base, 'favorites', filename)
def settings_uri(self, type, scope_param1, scope_param2):
"""Get the Advanced API URI for retrieving or saving Settings
Depending on the Type of setting scope_param2 or scope_param1 and scope_param2 are
not necessary.
>>> locator = Locator('joe')
>>> locator.settings_uri('account',None,None)
'http://gpodder.net/api/2/settings/joe/account.json'
>>> locator.settings_uri('device','foodevice',None)
'http://gpodder.net/api/2/settings/joe/device.json?device=foodevice'
>>> locator.settings_uri('podcast','http://podcast.com',None)
'http://gpodder.net/api/2/settings/joe/podcast.json?podcast=http%3A//podcast.com'
>>> locator.settings_uri('episode','http://podcast.com','http://podcast.com/foo')
'http://gpodder.net/api/2/settings/joe/episode.json?podcast=http%3A//podcast.com&episode=http%3A//podcast.com/foo'
"""
if type not in self.SETTINGS_TYPES:
raise ValueError('Unsupported Setting Type')
filename = self._username + '/%(type)s.json' % locals()
if type is 'device':
if scope_param1 is None:
raise ValueError('Devicename not specified')
filename += '?device=%(scope_param1)s' % locals()
if type is 'podcast':
if scope_param1 is None:
raise ValueError('Podcast URL not specified')
filename += '?podcast=%s' % urllib.quote(scope_param1)
if type is 'episode':
if (scope_param1 is None) or (scope_param2 is None):
raise ValueError('Podcast or Episode URL not specified')
filename += '?podcast=%s&episode=%s' % (urllib.quote(scope_param1), urllib.quote(scope_param2))
return util.join(self._base, 'settings' , filename)
mygpoclient-1.7/mygpoclient/http.py 0000664 0001751 0001751 00000011532 12105161764 017217 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import urllib2
import cookielib
import mygpoclient
class SimpleHttpPasswordManager(urllib2.HTTPPasswordMgr):
"""Simplified password manager for urllib2
This class always provides the username/password combination that
is passed to it as constructor argument, independent of the realm
or authuri that is used.
"""
# The maximum number of authentication retries
MAX_RETRIES = 3
def __init__(self, username, password):
self._username = username
self._password = password
self._count = 0
def find_user_password(self, realm, authuri):
self._count += 1
if self._count > self.MAX_RETRIES:
return (None, None)
return (self._username, self._password)
class HttpRequest(urllib2.Request):
"""Request object with customizable method
The default behaviour of urllib2.Request is unchanged:
>>> request = HttpRequest('http://example.org/')
>>> request.get_method()
'GET'
>>> request = HttpRequest('http://example.org/', data='X')
>>> request.get_method()
'POST'
However, it's possible to customize the method name:
>>> request = HttpRequest('http://example.org/', data='X')
>>> request.set_method('PUT')
>>> request.get_method()
'PUT'
"""
def set_method(self, method):
setattr(self, '_method', method)
def get_method(self):
if hasattr(self, '_method'):
return getattr(self, '_method')
else:
return urllib2.Request.get_method(self)
# Possible exceptions that will be raised by HttpClient
class Unauthorized(Exception): pass
class NotFound(Exception): pass
class BadRequest(Exception): pass
class UnknownResponse(Exception): pass
class HttpClient(object):
"""A comfortable HTTP client
This class hides the gory details of the underlying HTTP protocol
from the rest of the code by providing a simple interface for doing
requests and handling authentication.
"""
def __init__(self, username=None, password=None):
self._username = username
self._password = password
self._cookie_jar = cookielib.CookieJar()
cookie_handler = urllib2.HTTPCookieProcessor(self._cookie_jar)
if username is not None and password is not None:
password_manager = SimpleHttpPasswordManager(username, password)
auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
self._opener = urllib2.build_opener(auth_handler, cookie_handler)
else:
self._opener = urllib2.build_opener(cookie_handler)
@staticmethod
def _prepare_request(method, uri, data):
"""Prepares the HttpRequest object"""
request = HttpRequest(uri, data)
request.set_method(method)
request.add_header('User-agent', mygpoclient.user_agent)
return request
@staticmethod
def _process_response(response):
return response.read()
def _request(self, method, uri, data, **kwargs):
"""Request and exception handling
Carries out a request with a given method (GET, POST, PUT) on
a given URI with optional data (data only makes sense for POST
and PUT requests and should be None for GET requests).
"""
request = self._prepare_request(method, uri, data)
try:
response = self._opener.open(request)
except urllib2.HTTPError, http_error:
if http_error.code == 404:
raise NotFound()
elif http_error.code == 401:
raise Unauthorized()
elif http_error.code == 400:
raise BadRequest()
else:
raise UnknownResponse(http_error.code)
return self._process_response(response)
def GET(self, uri):
"""Convenience method for carrying out a GET request"""
return self._request('GET', uri, None)
def POST(self, uri, data):
"""Convenience method for carrying out a POST request"""
return self._request('POST', uri, data)
def PUT(self, uri, data):
"""Convenience method for carrying out a PUT request"""
return self._request('PUT', uri, data)
mygpoclient-1.7/mygpoclient/json_test.py 0000664 0001751 0001751 00000004417 12105161764 020254 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from StringIO import StringIO
import urllib2
from mygpoclient import http
from mygpoclient import json
import unittest
import minimock
class Test_JsonClient(unittest.TestCase):
USERNAME = 'john'
PASSWORD = 'secret'
def setUp(self):
self.mockopener = minimock.Mock('urllib2.OpenerDirector')
urllib2.build_opener = minimock.Mock('urllib2.build_opener')
urllib2.build_opener.mock_returns = self.mockopener
def tearDown(self):
minimock.restore()
def mock_setHttpResponse(self, value):
self.mockopener.open.mock_returns = StringIO(value)
def test_parseResponse_worksWithDictionary(self):
client = json.JsonClient(self.USERNAME, self.PASSWORD)
self.mock_setHttpResponse('{"a": "B", "c": "D"}')
items = list(sorted(client.GET('/').items()))
self.assertEquals(items, [('a', 'B'), ('c', 'D')])
def test_parseResponse_worksWithIntegerList(self):
client = json.JsonClient(self.USERNAME, self.PASSWORD)
self.mock_setHttpResponse('[1,2,3,6,7]')
self.assertEquals(client.GET('/'), [1,2,3,6,7])
def test_parseResponse_emptyString_returnsNone(self):
client = json.JsonClient(self.USERNAME, self.PASSWORD)
self.mock_setHttpResponse('')
self.assertEquals(client.GET('/'), None)
def test_invalidContent_raisesJsonException(self):
client = json.JsonClient(self.USERNAME, self.PASSWORD)
self.mock_setHttpResponse('this is not a valid json string')
self.assertRaises(json.JsonException, client.GET, '/')
mygpoclient-1.7/mygpoclient/api_test.py 0000664 0001751 0001751 00000064740 12105161764 020061 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import mygpoclient
from mygpoclient import api
from mygpoclient import testing
import unittest
# Example data for testing purposes
FEED_URL_1 = 'http://example.com/test.rss'
FEED_URL_2 = 'http://feeds.example.org/1/feed.atom'
FEED_URL_3 = 'http://example.co.uk/episodes.xml'
FEED_URL_4 = 'http://pod.cast/test.xml'
EPISODE_URL_1 = 'http://dl.example.net/episodes/one.mp3'
EPISODE_URL_2 = 'http://pod.cast.invalid/downloads/s02e04.ogg'
EPISODE_URL_3 = 'http://example.org/05-skylarking.m4v'
EPISODE_URL_4 = 'http://www.example.com/test/me_now.avi'
DEVICE_ID_1 = 'gpodder.on.my.phone'
DEVICE_ID_2 = '95dce59cf340123fa'
class Test_SubscriptionChanges(unittest.TestCase):
ADD = [
FEED_URL_1,
FEED_URL_3,
]
REMOVE = [
FEED_URL_2,
FEED_URL_4,
]
SINCE = 1262101867
def test_initSetsCorrectAttributes(self):
changes = api.SubscriptionChanges(self.ADD, self.REMOVE, self.SINCE)
self.assertEquals(changes.add, self.ADD)
self.assertEquals(changes.remove, self.REMOVE)
self.assertEquals(changes.since, self.SINCE)
class Test_EpisodeActionChanges(unittest.TestCase):
ACTIONS = [
api.EpisodeAction(FEED_URL_1, EPISODE_URL_1, 'download'),
api.EpisodeAction(FEED_URL_2, EPISODE_URL_3, 'play'),
api.EpisodeAction(FEED_URL_2, EPISODE_URL_4, 'delete'),
]
SINCE = 1262102013
def test_initSetsCorrectAttributes(self):
changes = api.EpisodeActionChanges(self.ACTIONS, self.SINCE)
self.assertEquals(changes.actions, self.ACTIONS)
self.assertEquals(changes.since, self.SINCE)
class Test_PodcastDevice(unittest.TestCase):
CAPTION = 'My Nice Device'
def test_initSetsCorrectAttributes(self):
device = api.PodcastDevice(DEVICE_ID_1, self.CAPTION, 'mobile', 42)
self.assertEquals(device.device_id, DEVICE_ID_1)
self.assertEquals(device.caption, self.CAPTION)
self.assertEquals(device.type, 'mobile')
self.assertEquals(device.subscriptions, 42)
def test_invalidDeviceType_raisesValueError(self):
self.assertRaises(ValueError,
api.PodcastDevice, DEVICE_ID_2, self.CAPTION,
'does-not-exist', 1337)
def test_nonNumericSubscriptions_raisesValueError(self):
self.assertRaises(ValueError,
api.PodcastDevice, DEVICE_ID_1, self.CAPTION,
'laptop', 'notanumber')
class Test_EpisodeAction(unittest.TestCase):
XML_TIMESTAMP = '2009-12-12T09:00:00'
VALID_STARTED = 100
VALID_POSITION = 123
VALID_TOTAL = 321
def test_initSetsCorrectAttributes(self):
action = api.EpisodeAction(FEED_URL_1, EPISODE_URL_1, 'play',
DEVICE_ID_1, self.XML_TIMESTAMP, self.VALID_STARTED,
self.VALID_POSITION, self.VALID_TOTAL)
self.assertEquals(action.podcast, FEED_URL_1)
self.assertEquals(action.episode, EPISODE_URL_1)
self.assertEquals(action.action, 'play')
self.assertEquals(action.device, DEVICE_ID_1)
self.assertEquals(action.timestamp, self.XML_TIMESTAMP)
self.assertEquals(action.started, self.VALID_STARTED)
self.assertEquals(action.position, self.VALID_POSITION)
self.assertEquals(action.total, self.VALID_TOTAL)
def test_invalidAction_raisesValueError(self):
self.assertRaises(ValueError,
api.EpisodeAction, FEED_URL_2, EPISODE_URL_3, 'invalidaction',
DEVICE_ID_2, self.XML_TIMESTAMP)
def test_startedIsSetWithNoPlayAction_raisesValueError(self):
self.assertRaises(ValueError,
api.EpisodeAction, FEED_URL_4, EPISODE_URL_2, 'download',
DEVICE_ID_1, self.XML_TIMESTAMP, self.VALID_STARTED)
def test_positionIsSetWithNoPlayAction_raisesValueError(self):
self.assertRaises(ValueError,
api.EpisodeAction, FEED_URL_4, EPISODE_URL_2, 'download',
DEVICE_ID_1, self.XML_TIMESTAMP, None, self.VALID_POSITION)
def test_totalIsSetWithNoPlayAction_raisesValueError(self):
self.assertRaises(ValueError,
api.EpisodeAction, FEED_URL_4, EPISODE_URL_2, 'download',
DEVICE_ID_1, self.XML_TIMESTAMP, None, None, self.VALID_TOTAL)
def test_invalidTimestampFormat_raisesValueError(self):
self.assertRaises(ValueError,
api.EpisodeAction, FEED_URL_3, EPISODE_URL_3, 'delete',
DEVICE_ID_2, 'today')
def test_onlyStartedSet_raisesValueError(self):
self.assertRaises(ValueError,
api.EpisodeAction, FEED_URL_1, EPISODE_URL_4, 'play',
DEVICE_ID_1, self.XML_TIMESTAMP, self.VALID_STARTED)
def test_invalidStartedFormat_raisesValueError(self):
self.assertRaises(ValueError,
api.EpisodeAction, FEED_URL_1, EPISODE_URL_4, 'play',
DEVICE_ID_1, self.XML_TIMESTAMP, '10 minutes into the show', self.VALID_POSITION)
def test_invalidPositionFormat_raisesValueError(self):
self.assertRaises(ValueError,
api.EpisodeAction, FEED_URL_1, EPISODE_URL_4, 'play',
DEVICE_ID_1, self.XML_TIMESTAMP, self.VALID_STARTED, '15 minutes later')
def test_invalidTotalFormat_raisesValueError(self):
self.assertRaises(ValueError,
api.EpisodeAction, FEED_URL_1, EPISODE_URL_4, 'play',
DEVICE_ID_1, self.XML_TIMESTAMP, None, self.VALID_POSITION, '30 minutes total')
def test_toDictionary_containsMandatoryAttributes(self):
action = api.EpisodeAction(FEED_URL_1, EPISODE_URL_1, 'play')
dictionary = action.to_dictionary()
self.assertEquals(len(dictionary.keys()), 3)
self.assert_('podcast' in dictionary)
self.assert_('episode' in dictionary)
self.assert_('action' in dictionary)
self.assertEquals(dictionary['podcast'], FEED_URL_1)
self.assertEquals(dictionary['episode'], EPISODE_URL_1)
self.assertEquals(dictionary['action'], 'play')
def test_toDictionary_containsAllAttributes(self):
action = api.EpisodeAction(FEED_URL_3, EPISODE_URL_4, 'play',
DEVICE_ID_1, self.XML_TIMESTAMP, self.VALID_STARTED,
self.VALID_POSITION, self.VALID_TOTAL)
dictionary = action.to_dictionary()
self.assertEquals(len(dictionary.keys()), 8)
self.assert_('podcast' in dictionary)
self.assert_('episode' in dictionary)
self.assert_('action' in dictionary)
self.assert_('device' in dictionary)
self.assert_('timestamp' in dictionary)
self.assert_('started' in dictionary)
self.assert_('position' in dictionary)
self.assert_('total' in dictionary)
self.assertEquals(dictionary['podcast'], FEED_URL_3)
self.assertEquals(dictionary['episode'], EPISODE_URL_4)
self.assertEquals(dictionary['action'], 'play')
self.assertEquals(dictionary['device'], DEVICE_ID_1)
self.assertEquals(dictionary['timestamp'], self.XML_TIMESTAMP)
self.assertEquals(dictionary['started'], self.VALID_STARTED)
self.assertEquals(dictionary['position'], self.VALID_POSITION)
self.assertEquals(dictionary['total'], self.VALID_TOTAL)
class Test_MygPodderClient(unittest.TestCase):
ADD = [
FEED_URL_1,
FEED_URL_3,
]
REMOVE = [
FEED_URL_2,
FEED_URL_4,
]
ADD_REMOVE_AS_JSON_UPLOAD = {
'add': [FEED_URL_1, FEED_URL_3],
'remove': [FEED_URL_2, FEED_URL_4],
}
ACTIONS = [
api.EpisodeAction(FEED_URL_1, EPISODE_URL_1, 'download'),
api.EpisodeAction(FEED_URL_2, EPISODE_URL_3, 'play'),
api.EpisodeAction(FEED_URL_2, EPISODE_URL_4, 'delete'),
]
ACTIONS_AS_JSON_UPLOAD = [
{'podcast': FEED_URL_1, 'episode': EPISODE_URL_1, 'action': 'download'},
{'podcast': FEED_URL_2, 'episode': EPISODE_URL_3, 'action': 'play'},
{'podcast': FEED_URL_2, 'episode': EPISODE_URL_4, 'action': 'delete'},
]
USERNAME = 'user01'
PASSWORD = 's3cret'
SINCE = 1262103016
def setUp(self):
self.fake_client = testing.FakeJsonClient()
self.client = api.MygPodderClient(self.USERNAME, self.PASSWORD,
client_class=self.fake_client)
def set_http_response_value(self, value):
self.fake_client.response_value = value
def assert_http_request_count(self, count):
self.assertEquals(len(self.fake_client.requests), count)
def has_put_json_data(self, data, required_method='PUT'):
"""Returns True if the FakeJsonClient has received the given data"""
for method, uri, sent in self.fake_client.requests:
if method == required_method:
self.assertEquals(sent, data)
return True
return False
def has_posted_json_data(self, data):
"""Same as has_put_json_data, but require a POST request"""
return self.has_put_json_data(data, required_method='POST')
def test_getSubscriptions_withPodcastDevice(self):
self.set_http_response_value('[]')
device = api.PodcastDevice('manatee', 'My Device', 'mobile', 20)
self.assertEquals(self.client.get_subscriptions(device), [])
self.assert_http_request_count(1)
def test_putSubscriptions_withPodcastDevice(self):
self.set_http_response_value('')
device = api.PodcastDevice('manatee', 'My Device', 'mobile', 20)
self.assertEquals(self.client.put_subscriptions(device, self.ADD), True)
self.assert_http_request_count(1)
self.assert_(self.has_put_json_data(self.ADD))
def test_updateSubscriptions_raisesValueError_onInvalidAddList(self):
self.assertRaises(ValueError,
self.client.update_subscriptions, DEVICE_ID_2,
[FEED_URL_1, 123, FEED_URL_3], self.REMOVE)
def test_updateSubscriptions_raisesValueError_onInvalidRemoveList(self):
self.assertRaises(ValueError,
self.client.update_subscriptions, DEVICE_ID_2,
self.ADD, [FEED_URL_2, FEED_URL_4, [1, 2, 3]])
def test_updateSubscriptions_raisesInvalidResponse_onEmptyResponse(self):
self.set_http_response_value('')
self.assertRaises(api.InvalidResponse,
self.client.update_subscriptions, DEVICE_ID_1,
self.ADD, self.REMOVE)
def test_updateSubscriptions_raisesInvalidResponse_onMissingTimestamp(self):
self.set_http_response_value('{}')
self.assertRaises(api.InvalidResponse,
self.client.update_subscriptions, DEVICE_ID_1,
self.ADD, self.REMOVE)
def test_updateSubscriptions_raisesInvalidResponse_onInvalidTimestamp(self):
self.set_http_response_value("""
{"timestamp": "not gonna happen"}
""")
self.assertRaises(api.InvalidResponse,
self.client.update_subscriptions, DEVICE_ID_1,
self.ADD, self.REMOVE)
def test_updateSubscriptions_raisesInvalidResponse_withoutUpdateUrls(self):
self.set_http_response_value("""
{"timestamp": 1262103016}
""")
self.assertRaises(api.InvalidResponse,
self.client.update_subscriptions, DEVICE_ID_1,
self.ADD, self.REMOVE)
def test_updateSubscriptions_raisesInvalidResponse_withNonStringList(self):
self.set_http_response_value("""
{"timestamp": 1262103016, "update_urls": [
["http://example.com/", 2],
[56, "http://example.org/"]
]}
""")
self.assertRaises(api.InvalidResponse,
self.client.update_subscriptions, DEVICE_ID_2,
self.ADD, self.REMOVE)
def test_updateSubscriptions_raisesInvalidResponse_withInvalidList(self):
self.set_http_response_value("""
{"timestamp": 1262103016, "update_urls": [
["test", "test2", "test3"],
["test", "test2"]
]}
""")
self.assertRaises(api.InvalidResponse,
self.client.update_subscriptions, DEVICE_ID_2,
self.ADD, self.REMOVE)
def test_updateSubscriptions_returnsUpdateResult(self):
self.set_http_response_value("""
{"timestamp": 1262103016, "update_urls": [
["http://test2.invalid/feed.rss",
"http://test2.invalid/feed.rss"],
["http://x.invalid/episodes.xml?format=2",
"http://x.invalid/episodes.xml"]
]}
""")
update_urls_expected = [
('http://test2.invalid/feed.rss',
'http://test2.invalid/feed.rss'),
('http://x.invalid/episodes.xml?format=2',
'http://x.invalid/episodes.xml'),
]
result = self.client.update_subscriptions(DEVICE_ID_1,
self.ADD, self.REMOVE)
# result is a UpdateResult object
self.assert_(hasattr(result, 'since'))
self.assert_(hasattr(result, 'update_urls'))
self.assertEquals(result.since, self.SINCE)
self.assertEquals(result.update_urls, update_urls_expected)
self.assert_http_request_count(1)
self.assert_(self.has_posted_json_data(self.ADD_REMOVE_AS_JSON_UPLOAD))
def test_pullSubscriptions_raisesInvalidResponse_onEmptyResponse(self):
self.set_http_response_value('')
self.assertRaises(api.InvalidResponse,
self.client.pull_subscriptions, DEVICE_ID_2)
def test_pullSubscriptions_raisesInvalidResponse_onMissingTimestamp(self):
self.set_http_response_value("""
{"add": [
"http://example.com/test.rss",
"http://feeds.example.org/1/feed.atom"
],
"remove": [
"http://example.co.uk/episodes.xml",
"http://pod.cast/test.xml"
]}
""")
self.assertRaises(api.InvalidResponse,
self.client.pull_subscriptions, DEVICE_ID_2)
def test_pullSubscriptions_raisesInvalidResponse_onMissingAddList(self):
self.set_http_response_value("""
{"remove": [
"http://example.co.uk/episodes.xml",
"http://pod.cast/test.xml"
],
"timestamp": 1262103016}
""")
self.assertRaises(api.InvalidResponse,
self.client.pull_subscriptions, DEVICE_ID_2)
def test_pullSubscriptions_raisesInvalidResponse_onMissingRemoveList(self):
self.set_http_response_value("""
{"add": [
"http://example.com/test.rss",
"http://feeds.example.org/1/feed.atom"
],
"timestamp": 1262103016}
""")
self.assertRaises(api.InvalidResponse,
self.client.pull_subscriptions, DEVICE_ID_2)
def test_pullSubscriptions_raisesInvalidResponse_onInvalidTimestamp(self):
self.set_http_response_value("""
{"add": [
"http://example.com/test.rss",
"http://feeds.example.org/1/feed.atom"
],
"remove": [
"http://example.co.uk/episodes.xml",
"http://pod.cast/test.xml"
],
"timestamp": "should not work"}
""")
self.assertRaises(api.InvalidResponse,
self.client.pull_subscriptions, DEVICE_ID_2)
def test_pullSubscriptions_raisesInvalidResponse_onInvalidAddList(self):
self.set_http_response_value("""
{"add": [
"http://example.com/test.rss",
1234,
"http://feeds.example.org/1/feed.atom"
],
"remove": [
"http://example.co.uk/episodes.xml",
"http://pod.cast/test.xml"
],
"timestamp": 1262103016}
""")
self.assertRaises(api.InvalidResponse,
self.client.pull_subscriptions, DEVICE_ID_2)
def test_pullSubscriptions_raisesInvalidResponse_onInvalidRemoveList(self):
self.set_http_response_value("""
{"add": [
"http://example.com/test.rss",
"http://feeds.example.org/1/feed.atom"
],
"remove": [
"http://example.co.uk/episodes.xml",
["should", "not", "work", "either"],
"http://pod.cast/test.xml"
],
"timestamp": 1262103016}
""")
self.assertRaises(api.InvalidResponse,
self.client.pull_subscriptions, DEVICE_ID_2)
def test_pullSubscriptions_returnsChangesListAndTimestamp(self):
self.set_http_response_value("""
{"add": [
"http://example.com/test.rss",
"http://feeds.example.org/1/feed.atom"
],
"remove": [
"http://example.co.uk/episodes.xml",
"http://pod.cast/test.xml"
],
"timestamp": 1262103016}
""")
changes = self.client.pull_subscriptions(DEVICE_ID_2)
self.assertEquals(changes.add, [FEED_URL_1, FEED_URL_2])
self.assertEquals(changes.remove, [FEED_URL_3, FEED_URL_4])
self.assertEquals(changes.since, self.SINCE)
self.assert_http_request_count(1)
def test_uploadEpisodeActions_raisesInvalidResponse_onEmptyResponse(self):
self.set_http_response_value('')
self.assertRaises(api.InvalidResponse,
self.client.upload_episode_actions, self.ACTIONS)
def test_uploadEpisodeActions_raisesInvalidResponse_onMissingTimestamp(self):
self.set_http_response_value('{}')
self.assertRaises(api.InvalidResponse,
self.client.upload_episode_actions, self.ACTIONS)
def test_uploadEpisodeActions_raisesInvalidResponse_onInvalidTimestamp(self):
self.set_http_response_value("""
{"timestamp": "just nothin'.."}
""")
self.assertRaises(api.InvalidResponse,
self.client.upload_episode_actions, self.ACTIONS)
def test_uploadEpisodeActions_returnsTimestamp(self):
self.set_http_response_value("""
{"timestamp": 1262103016}
""")
result = self.client.upload_episode_actions(self.ACTIONS)
self.assertEquals(result, self.SINCE)
self.assert_http_request_count(1)
self.assert_(self.has_posted_json_data(self.ACTIONS_AS_JSON_UPLOAD))
def test_downloadEpisodeActions_raisesInvalidResponse_onEmptyResponse(self):
self.set_http_response_value('')
self.assertRaises(api.InvalidResponse, self.client.download_episode_actions)
def test_downloadEpisodeActions_raisesInvalidResponse_onMissingActions(self):
self.set_http_response_value("""
{"timestamp": 1262103016}
""")
self.assertRaises(api.InvalidResponse, self.client.download_episode_actions)
def test_downloadEpisodeActions_raisesInvalidResponse_onMissingTimestamp(self):
self.set_http_response_value("""
{"actions": [
{"podcast": "a", "episode": "b", "action": "download"},
{"podcast": "x", "episode": "y", "action": "play"}
]}
""")
self.assertRaises(api.InvalidResponse, self.client.download_episode_actions)
def test_downloadEpisodeActions_raisesInvalidResponse_onInvalidTimestamp(self):
self.set_http_response_value("""
{"actions": [
{"podcast": "a", "episode": "b", "action": "download"},
{"podcast": "x", "episode": "y", "action": "play"}
], "timestamp": "right now"}
""")
self.assertRaises(api.InvalidResponse, self.client.download_episode_actions)
def test_downloadEpisodeActions_raisesInvalidResponse_onIncompleteActions(self):
self.set_http_response_value("""
{"actions": [
{"podcast": "a", "episode": "b", "action": "download"},
{"podcast": "x", "episode": "y"}
], "timestamp": 1262103016}
""")
self.assertRaises(api.InvalidResponse, self.client.download_episode_actions)
def test_downloadEpisodeActions_returnsActionList(self):
self.set_http_response_value("""
{"actions": [
{"podcast": "a", "episode": "b", "action": "download"},
{"podcast": "x", "episode": "y", "action": "play"}
], "timestamp": 1262103016}
""")
changes = self.client.download_episode_actions()
self.assertEquals(len(changes.actions), 2)
action1, action2 = changes.actions
self.assertEquals(action1.podcast, 'a')
self.assertEquals(action1.episode, 'b')
self.assertEquals(action1.action, 'download')
self.assertEquals(action2.podcast, 'x')
self.assertEquals(action2.episode, 'y')
self.assertEquals(action2.action, 'play')
self.assertEquals(changes.since, self.SINCE)
self.assert_http_request_count(1)
def test_updateDeviceSettings_withNothing(self):
self.set_http_response_value('')
result = self.client.update_device_settings(DEVICE_ID_1)
self.assertEquals(result, True)
self.assert_http_request_count(1)
self.assert_(self.has_posted_json_data({}))
def test_updateDeviceSettings_withCaption(self):
self.set_http_response_value('')
result = self.client.update_device_settings(DEVICE_ID_1,
caption='Poodonkis')
self.assertEquals(result, True)
self.assert_http_request_count(1)
self.assert_(self.has_posted_json_data({'caption': 'Poodonkis'}))
def test_updateDeviceSettings_withType(self):
self.set_http_response_value('')
result = self.client.update_device_settings(DEVICE_ID_1,
type='desktop')
self.assertEquals(result, True)
self.assert_http_request_count(1)
self.assert_(self.has_posted_json_data({'type': 'desktop'}))
def test_updateDeviceSettings_withCaptionAndType(self):
self.set_http_response_value('')
result = self.client.update_device_settings(DEVICE_ID_1,
'My Unit Testing Device', 'desktop')
self.assertEquals(result, True)
self.assert_http_request_count(1)
self.assert_(self.has_posted_json_data({
'caption': 'My Unit Testing Device',
'type': 'desktop'}))
def test_getDevices_raisesInvalidResponse_onEmptyResponse(self):
self.set_http_response_value('')
self.assertRaises(api.InvalidResponse, self.client.get_devices)
def test_getDevices_raisesInvalidResponse_onMissingKeys(self):
self.set_http_response_value("""
[
{"id": "gpodder.on.my.phone",
"type": "mobile",
"subscriptions": 42},
{"id": "95dce59cf340123fa",
"caption": "The Lappy",
"subscriptions": 4711}
]
""")
self.assertRaises(api.InvalidResponse, self.client.get_devices)
def test_getDevices_returnsDeviceList(self):
self.set_http_response_value("""
[
{"id": "gpodder.on.my.phone",
"caption": "Phone",
"type": "mobile",
"subscriptions": 42},
{"id": "95dce59cf340123fa",
"caption": "The Lappy",
"type": "laptop",
"subscriptions": 4711}
]
""")
devices = self.client.get_devices()
self.assertEquals(len(devices), 2)
device1, device2 = devices
self.assertEquals(device1.device_id, DEVICE_ID_1)
self.assertEquals(device1.caption, 'Phone')
self.assertEquals(device1.type, 'mobile')
self.assertEquals(device1.subscriptions, 42)
self.assertEquals(device2.device_id, DEVICE_ID_2)
self.assertEquals(device2.caption, 'The Lappy')
self.assertEquals(device2.type, 'laptop')
self.assertEquals(device2.subscriptions, 4711)
self.assert_http_request_count(1)
def test_getFavoriteEpisodes_returnsEpisodeList(self):
self.set_http_response_value("""
[
{"title": "TWiT 245: No Hitler For You",
"url": "http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3",
"podcast_title": "this WEEK in TECH - MP3 Edition",
"podcast_url": "http://leo.am/podcasts/twit",
"description": "[...]",
"website": "http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3",
"released": "2010-12-25T00:30:00",
"mygpo_link": "http://gpodder.net/episode/1046492"},
{"website": "http://feedproxy.google.com/~r/coverville/~3/5UK8-PZmmMQ/",
"podcast_title": "Coverville",
"description": "Bob Dylan turned 70 this week. Bob Dylan has done a lot of songs. A lot of people have covered Bob’s songs. Did I mention Bob Dylan turned 70 this week? All this adds up to a Cover Story. Let me play you it. 59 minutes | Featuring: Title Artist Album Original Artist 1 Blowin’ [...]",
"title": "Coverville 774: The Bob Dylan Cover Story VI",
"url": "http://feedproxy.google.com/~r/coverville/~5/iV_RxVU1Jek/Coverville-110527.mp3",
"podcast_url": "http://feeds.feedburner.com/coverville",
"released": "2011-05-28T01:08:59",
"mygpo_link": "http://gpodder.net/episode/5329203"}
]
""")
favorites = self.client.get_favorite_episodes()
self.assertEquals(len(favorites), 2)
episode1, episode2 = favorites
self.assertEquals(episode1.title, 'TWiT 245: No Hitler For You')
self.assertEquals(episode1.url, 'http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3')
self.assertEquals(episode1.podcast_title, 'this WEEK in TECH - MP3 Edition')
self.assertEquals(episode1.podcast_url, 'http://leo.am/podcasts/twit')
self.assertEquals(episode1.description, '[...]')
self.assertEquals(episode1.website, 'http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3')
self.assertEquals(episode1.released, '2010-12-25T00:30:00')
self.assertEquals(episode1.mygpo_link, 'http://gpodder.net/episode/1046492')
self.assertEquals(episode2.website, 'http://feedproxy.google.com/~r/coverville/~3/5UK8-PZmmMQ/')
mygpoclient-1.7/mygpoclient/public_test.py 0000664 0001751 0001751 00000023077 12105161764 020564 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
from mygpoclient import public
from mygpoclient import simple
from mygpoclient import testing
import unittest
class Test_Tag(unittest.TestCase):
def test_tagFromDict_raisesValueError_missingKey(self):
self.assertRaises(ValueError,public.Tag.from_dict, {'tag':'abcde'} )
class Test_Episode(unittest.TestCase):
def test_episodeFromDict_raisesValueError_missingKey(self):
self.assertRaises(ValueError,public.Episode.from_dict, {'title':'foobar','podcast_url':'http://www.podcast.com'})
class Test_PublicClient(unittest.TestCase):
TOPLIST_JSON = """
[{
"website": "http://linuxoutlaws.com/podcast",
"description": "Open source talk with a serious attitude",
"title": "Linux Outlaws",
"url": "http://feeds.feedburner.com/linuxoutlaws",
"subscribers_last_week": 1736,
"subscribers": 1736,
"mygpo_link": "http://www.gpodder.net/podcast/11092",
"logo_url": "http://linuxoutlaws.com/files/albumart-itunes.jpg"
},
{
"website": "http://syndication.mediafly.com/redirect/show/d581e9b773784df7a56f37e1138c037c",
"description": "We are not talking dentistry here; FLOSS all about Free Libre Open Source Software. Join hosts Randal Schwartz and Leo Laporte every Saturday as they talk with the most interesting and important people in the Open Source and Free Software community.",
"title": "FLOSS Weekly Video (large)",
"url": "http://feeds.twit.tv/floss_video_large",
"subscribers_last_week": 50,
"subscribers": 50,
"mygpo_link": "http://www.gpodder.net/podcast/31991",
"logo_url": "http://static.mediafly.com/publisher/images/06cecab60c784f9d9866f5dcb73227c3/icon-150x150.png"
}]
"""
TOPLIST = [
simple.Podcast('http://feeds.feedburner.com/linuxoutlaws',
'Linux Outlaws',
'Open source talk with a serious attitude',
'http://linuxoutlaws.com/podcast',
1736, 1736,
'http://www.gpodder.net/podcast/11092',
'http://linuxoutlaws.com/files/albumart-itunes.jpg'),
simple.Podcast('http://feeds.twit.tv/floss_video_large',
'FLOSS Weekly Video (large)',
'We are not talking dentistry here; FLOSS all about Free Libre Open Source Software. Join hosts Randal Schwartz and Leo Laporte every Saturday as they talk with the most interesting and important people in the Open Source and Free Software community.',
'http://syndication.mediafly.com/redirect/show/d581e9b773784df7a56f37e1138c037c',
50, 50,
'http://www.gpodder.net/podcast/31991',
'http://static.mediafly.com/publisher/images/06cecab60c784f9d9866f5dcb73227c3/icon-150x150.png'),
]
SEARCHRESULT_JSON = """
[{
"website": "http://linuxoutlaws.com/podcast",
"description": "Open source talk with a serious attitude",
"title": "Linux Outlaws",
"url": "http://feeds.feedburner.com/linuxoutlaws",
"subscribers_last_week": 1736,
"subscribers": 1736,
"mygpo_link": "http://www.gpodder.net/podcast/11092",
"logo_url": "http://linuxoutlaws.com/files/albumart-itunes.jpg"
},
{
"website": "http://syndication.mediafly.com/redirect/show/d581e9b773784df7a56f37e1138c037c",
"description": "We are not talking dentistry here; FLOSS all about Free Libre Open Source Software. Join hosts Randal Schwartz and Leo Laporte every Saturday as they talk with the most interesting and important people in the Open Source and Free Software community.",
"title": "FLOSS Weekly Video (large)",
"url": "http://feeds.twit.tv/floss_video_large",
"subscribers_last_week": 50,
"subscribers": 50,
"mygpo_link": "http://www.gpodder.net/podcast/31991",
"logo_url": "http://static.mediafly.com/publisher/images/06cecab60c784f9d9866f5dcb73227c3/icon-150x150.png"
}]
"""
SEARCHRESULT = [
simple.Podcast('http://feeds.feedburner.com/linuxoutlaws',
'Linux Outlaws',
'Open source talk with a serious attitude',
'http://linuxoutlaws.com/podcast',
1736, 1736,
'http://www.gpodder.net/podcast/11092',
'http://linuxoutlaws.com/files/albumart-itunes.jpg'),
simple.Podcast('http://feeds.twit.tv/floss_video_large',
'FLOSS Weekly Video (large)',
'We are not talking dentistry here; FLOSS all about Free Libre Open Source Software. Join hosts Randal Schwartz and Leo Laporte every Saturday as they talk with the most interesting and important people in the Open Source and Free Software community.',
'http://syndication.mediafly.com/redirect/show/d581e9b773784df7a56f37e1138c037c',
50, 50,
'http://www.gpodder.net/podcast/31991',
'http://static.mediafly.com/publisher/images/06cecab60c784f9d9866f5dcb73227c3/icon-150x150.png'),
]
TOPTAGS_JSON = """
[
{"tag": "Technology",
"usage": 530 },
{"tag": "Arts",
"usage": 400}
]
"""
TOPTAGS = [
public.Tag('Technology',530),
public.Tag('Arts',400)
]
PODCAST_JSON = """
{
"website": "http://linuxoutlaws.com/podcast",
"description": "Open source talk with a serious attitude",
"title": "Linux Outlaws",
"url": "http://feeds.feedburner.com/linuxoutlaws",
"subscribers_last_week": 1736,
"subscribers": 1736,
"mygpo_link": "http://www.gpodder.net/podcast/11092",
"logo_url": "http://linuxoutlaws.com/files/albumart-itunes.jpg"
}
"""
PODCAST = simple.Podcast('http://feeds.feedburner.com/linuxoutlaws',
'Linux Outlaws',
'Open source talk with a serious attitude',
'http://linuxoutlaws.com/podcast',
1736, 1736,
'http://www.gpodder.net/podcast/11092',
'http://linuxoutlaws.com/files/albumart-itunes.jpg')
EPISODE_JSON = """
{"title": "TWiT 245: No Hitler For You",
"url": "http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3",
"podcast_title": "this WEEK in TECH - MP3 Edition",
"podcast_url": "http://leo.am/podcasts/twit",
"description": "[...]",
"website": "http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3",
"released": "2010-12-25T00:30:00",
"mygpo_link": "http://gpodder.net/episode/1046492"}
"""
EPISODE = public.Episode('TWiT 245: No Hitler For You',
'http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3',
'this WEEK in TECH - MP3 Edition',
'http://leo.am/podcasts/twit',
'[...]',
'http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3',
'2010-12-25T00:30:00',
'http://gpodder.net/episode/1046492'
)
def setUp(self):
self.fake_client = testing.FakeJsonClient()
self.client = public.PublicClient(client_class=self.fake_client)
def test_getToplist(self):
self.fake_client.response_value = self.TOPLIST_JSON
result = self.client.get_toplist()
self.assertEquals(result, self.TOPLIST)
self.assertEquals(len(self.fake_client.requests), 1)
def test_searchPodcasts(self):
self.fake_client.response_value = self.SEARCHRESULT_JSON
result = self.client.search_podcasts('wicked')
self.assertEquals(result, self.SEARCHRESULT)
self.assertEquals(len(self.fake_client.requests), 1)
def test_getPodcastsOfATag(self):
self.fake_client.response_value = self.SEARCHRESULT_JSON
result = self.client.get_podcasts_of_a_tag('wicked')
self.assertEquals(result, self.SEARCHRESULT)
self.assertEquals(len(self.fake_client.requests), 1)
def test_getTopTags(self):
self.fake_client.response_value = self.TOPTAGS_JSON
result = self.client.get_toptags()
self.assertEquals(result, self.TOPTAGS)
self.assertEquals(len(self.fake_client.requests), 1)
def test_getPodcastData(self):
self.fake_client.response_value = self.PODCAST_JSON
result = self.client.get_podcast_data('http://feeds.feedburner.com/linuxoutlaws')
self.assertEquals(result, self.PODCAST)
self.assertEquals(len(self.fake_client.requests), 1)
def test_getEpisodeData(self):
self.fake_client.response_value = self.EPISODE_JSON
result = self.client.get_episode_data('http://leo.am/podcasts/twit','http://www.podtrac.com/pts/redirect.mp3/aolradio.podcast.aol.com/twit/twit0245.mp3')
self.assertEquals(result, self.EPISODE)
self.assertEquals(len(self.fake_client.requests), 1)
mygpoclient-1.7/mygpoclient/__init__.py 0000664 0001751 0001751 00000003611 12105161764 017776 0 ustar thp thp 0000000 0000000 # -*- coding: utf-8 -*-
# gpodder.net API Client
# Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
"""gpodder.net API Client Library
This is mygpoclient, the gpodder.net API Client Library for Python.
"""
__author__ = 'Thomas Perl '
__version__ = '1.7'
__website__ = 'http://thp.io/2010/mygpoclient/'
__license__ = 'GNU General Public License v3 or later'
# Default settings for the API client (server hostname and API version)
HOST = 'gpodder.net'
VERSION = 2
TOPLIST_DEFAULT = 50
# You can overwrite this value from your application if you want
user_agent = 'mygpoclient/%s (+%s)' % (__version__, __website__)
# Version checking
def require_version(minimum_required):
"""Require a minimum version of the library
Returns True if the minimum library version constraint is
satisfied, False otherwise. Use this to check for newer API
methods and changes in the public API as described in NEWS.
>>> require_version('1.0')
True
>>> require_version('1.2')
True
>>> require_version(__version__)
True
>>> require_version('99.99')
False
"""
this_version = [int(x) for x in __version__.split('.')]
minimum_required = [int(x) for x in minimum_required.split('.')]
return minimum_required <= this_version
mygpoclient-1.7/NEWS 0000664 0001751 0001751 00000002300 12105161231 014011 0 ustar thp thp 0000000 0000000 Sun, 25 Apr 2010 23:51:38 +0200
-------------------------------
You can use the "require_version" function in mygpoclient to require a minimum
version of the mygpoclient library. The "require_version" function has been
added in version 1.3, so you have to check (e.g. with hasattr) if mygpoclient
has got a "require_version" attribute. You can then do the version check like
this:
if not hasattr(mygpoclient, 'require_version') or \
not mygpoclient.require_version('1.3'):
# Show error message and tell user to upgrade to version 1.3
Fri, 23 Apr 2010 17:43:03 +0200
-------------------------------
The parameter signature for the EpisodeAction constructor has been updated.
It now contains not only the optional "position" argument, but two new
arguments as well. The order of these parameters is:
started
position
total
If one of "started" or "total" is set, "position" becomes mandatory. This
means that the following combinations are now possible:
None
position
position and started
position and total
position and started and total
Also, the format has been changed. Instead of having a "HH:MM:SS" timestamp
format, we now only accept integer values (the number of seconds).
mygpoclient-1.7/DEPENDENCIES 0000664 0001751 0001751 00000002075 12105161231 015074 0 ustar thp thp 0000000 0000000 ==============================================================================
HARD DEPENDENCIES
==============================================================================
If you have a Python version lower than Python 2.6 (which already includes
simplejson as the "json" module), you will need to install simplejson from
simplejson (python-simplejson)
http://code.google.com/p/simplejson/
==============================================================================
OPTIONAL DEPENDENCIES
==============================================================================
If you want to run the UNIT TESTS ("make test"), you also need
Nose (python-nose)
http://somethingaboutorange.com/mrl/projects/nose/
MiniMock (python-minimock)
http://pypi.python.org/pypi/MiniMock
Coverage (python-coverage)
http://www.nedbatchelder.com/code/modules/coverage.html
If you want to generate the API DOCS ("make docs"), you also need
Epydoc (python-epydoc)
http://epydoc.sourceforge.net/
mygpoclient-1.7/scripts/ 0000775 0001751 0001751 00000000000 12105163324 015013 5 ustar thp thp 0000000 0000000 mygpoclient-1.7/scripts/bpsync 0000775 0001751 0001751 00000004566 12105161231 016245 0 ustar thp thp 0000000 0000000 #!/usr/bin/python
# BashPodder <-> gpodder.net sync client
# Copyright (c) 2010-04-02 Thomas Perl
# Licensed under the same terms as the "mygpoclient" library
# See: http://thp.io/2010/mygpoclient/
import mygpoclient
from mygpoclient import simple
import os
import sys
class BPSync(object):
def __init__(self, filename, host=mygpoclient.HOST, device='bp'):
self.filename = filename
self.device = device
username = os.environ['MYGPO_USERNAME']
password = os.environ['MYGPO_PASSWORD']
host = os.environ.get('MYGPO_HOSTNAME', host)
self.client = simple.SimpleClient(username, password, host)
def put(self):
lines = open(self.filename).read().strip().splitlines()
podcasts = [line.strip() for line in lines if line.strip()]
self.client.put_subscriptions(self.device, podcasts)
def get(self):
podcasts = self.client.get_subscriptions(self.device)
open(self.filename, 'w').write('\n'.join(podcasts+['']))
def usage(s=None):
print >>sys.stderr, """
Usage: %s (put|get) [device-id]
e.g %s put ........ Upload bp.conf as device "bp"
%s get ........ Download subscriptions for device "bp"
%s get mydev .. Download subscriptions for device "mydev"
The following environment variables need to be set:
MYGPO_USERNAME .. Username for the web service
MYGPO_PASSWORD .. Password for the web service
The following environment variables are optional:
BPSYNC_BP_CONF .. Path to your bp.conf file
MYGPO_HOSTNAME .. Host of the web service to use
""" % ((os.path.basename(sys.argv[0]),)*4)
if s is not None:
print >>sys.stderr, s
sys.exit(1)
if __name__ == '__main__':
if len(sys.argv) not in (2, 3):
usage('Wrong parameter count')
if 'MYGPO_USERNAME' not in os.environ or \
'MYGPO_PASSWORD' not in os.environ:
usage('MYGPO_USERNAME or MYGPO_PASSWORD not set!')
filename = os.environ.get('BPSYNC_BP_CONF', 'bp.conf')
if not os.path.exists(filename):
usage('File not found: ' + filename)
command = sys.argv[1]
if len(sys.argv) == 3:
client = BPSync(filename, device=sys.argv[2])
else:
client = BPSync(filename)
if command == 'put':
client.put()
elif command == 'get':
client.get()
else:
usage('Unknown command')
mygpoclient-1.7/PKG-INFO 0000664 0001751 0001751 00000000621 12105163324 014420 0 ustar thp thp 0000000 0000000 Metadata-Version: 1.1
Name: mygpoclient
Version: 1.7
Summary: gpodder.net API Client Library
Home-page: http://thp.io/2010/mygpoclient/
Author: Thomas Perl
Author-email: thp@gpodder.org
License: GNU General Public License v3 or later
Download-URL: http://thp.io/2010/mygpoclient/mygpoclient-1.7.tar.gz
Description: This is mygpoclient, the gpodder.net API Client Library for Python.
Platform: UNKNOWN
mygpoclient-1.7/README 0000664 0001751 0001751 00000001756 12105161231 014210 0 ustar thp thp 0000000 0000000
-----------------------------------------------------------
The gpodder.net Client Library
-----------------------------------------------------------
This library provides an easy and structured way to access the
gpodder.net web services. In addition to subscription list
synchronization and storage, the advanced API support allows
to upload and download episode status changes.
See the mygpoclient homepage for up-to-date information:
http://thp.io/2010/mygpoclient/
The API specification for the gpodder.net webservice can
be found at
http://wiki.gpodder.org/wiki/Web_Services/API
The source of this library is managed in a Git repository at
https://github.com/gpodder/mygpoclient
If you have any questions, please don't hesitate to contact
the gPodder developers mailing list at
gpodder@freelists.org
You can report bugs and problems that you find by using our
Bugzilla installation at
http://bugs.gpodder.org/
Thank you for your interest in the mygpoclient library!
mygpoclient-1.7/COPYING 0000664 0001751 0001751 00000104513 12105161231 014356 0 ustar thp thp 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
mygpoclient-1.7/setup.py 0000664 0001751 0001751 00000002441 12105161231 015032 0 ustar thp thp 0000000 0000000 #!/usr/bin/env python
# Generic setup script for single-package Python projects
# by Thomas Perl
from distutils.core import setup
import re
import os
import glob
PACKAGE = 'mygpoclient'
SCRIPT_FILE = os.path.join(PACKAGE, '__init__.py')
main_py = open(SCRIPT_FILE).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", main_py))
docstrings = re.findall('"""(.*?)"""', main_py, re.DOTALL)
# List the packages that need to be installed/packaged
PACKAGES = (
PACKAGE,
)
SCRIPTS = glob.glob('scripts/*')
# Metadata fields extracted from SCRIPT_FILE
AUTHOR_EMAIL = metadata['author']
VERSION = metadata['version']
WEBSITE = metadata['website']
LICENSE = metadata['license']
DESCRIPTION = docstrings[0].strip()
if '\n\n' in DESCRIPTION:
DESCRIPTION, LONG_DESCRIPTION = DESCRIPTION.split('\n\n', 1)
else:
LONG_DESCRIPTION = None
# Extract name and e-mail ("Firstname Lastname ")
AUTHOR, EMAIL = re.match(r'(.*) <(.*)>', AUTHOR_EMAIL).groups()
setup(name=PACKAGE,
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
author=AUTHOR,
author_email=EMAIL,
license=LICENSE,
url=WEBSITE,
packages=PACKAGES,
scripts=SCRIPTS,
download_url=WEBSITE+PACKAGE+'-'+VERSION+'.tar.gz')