repo
string | commit
string | message
string | diff
string |
---|---|---|---|
adewale/Buzz-Chat-Bot
|
7623741c5c1275aa767b47bdad151b959e044b19
|
Don't show the access token. Show the user's email address for confirmation.
|
diff --git a/main.py b/main.py
index 18515ef..c422de6 100644
--- a/main.py
+++ b/main.py
@@ -1,127 +1,125 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
import oauth_handlers
import os
import settings
import xmpp
import pshb
import simple_buzz_wrapper
class ProfileViewingHandler(webapp.RequestHandler):
@login_required
def get(self):
user_token = oauth_handlers.UserToken.get_current_user_token()
buzz_wrapper = oauth_handlers.make_wrapper(user_token.email_address)
user_profile_data = buzz_wrapper.get_profile()
template_values = {'user_profile_data': user_profile_data, 'access_token': user_token.access_token_string}
path = os.path.join(os.path.dirname(__file__), 'profile.html')
self.response.out.write(template.render(path, template_values))
class FrontPageHandler(webapp.RequestHandler):
def get(self):
template_values = {'commands' : xmpp.XmppHandler.COMMAND_HELP_MSG_LIST,
'help_command' : xmpp.XmppHandler.HELP_CMD,
'jabber_id' : '%[email protected]' % settings.APP_NAME,
'admin_url' : settings.ADMIN_PROFILE_URL}
path = os.path.join(os.path.dirname(__file__), 'front_page.html')
self.response.out.write(template.render(path, template_values))
class PostsHandler(webapp.RequestHandler):
def _get_subscription(self):
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
return subscription
def get(self):
"""Show all the resources in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.debug("New content: %s" % self.request.body)
id = self.request.get('id')
logging.debug("Request id = '%s'", id)
# If this is a hub challenge
if self.request.get('hub.challenge'):
# If this subscription exists
mode = self.request.get('hub.mode')
topic = self.request.get('hub.topic')
if mode == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
elif mode == "unsubscribe" and not xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
else:
self.response.set_status(404)
self.response.out.write("Challenge failed")
logging.info("Challenge failed for feed: %s" % topic)
# Once a challenge has been issued there's no point in returning anything other than challenge passed or failed
return
def post(self):
"""Create a new resource in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
- logging.info('Request: %s' % str(self.request))
- logging.debug("New content: %s" % self.request.body)
id = self.request.get('id')
logging.debug("Request id = '%s'", id)
subscription = xmpp.Subscription.get_by_id(int(id))
if not subscription:
self.response.set_status(404)
self.response.out.write("No such subscription")
logging.warning('No subscription for %s' % id)
return
subscriber = subscription.subscriber
search_term = subscription.search_term
parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB)
url = parser.extractFeedUrl()
if not parser.dataValid():
parser.logErrors()
self.response.out.write("Bad entries: %s" % parser.data)
return
else:
posts = parser.extractPosts()
logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url))
xmpp.send_posts(posts, subscriber, search_term)
self.response.set_status(200)
application = webapp.WSGIApplication([
(settings.FRONT_PAGE_HANDLER_URL, FrontPageHandler),
(settings.PROFILE_HANDLER_URL, ProfileViewingHandler),
('/start_dance', oauth_handlers.DanceStartingHandler),
('/finish_dance', oauth_handlers.DanceFinishingHandler),
('/delete_tokens', oauth_handlers.TokenDeletionHandler),
('/posts', PostsHandler),
('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
diff --git a/profile.html b/profile.html
index 36d91d1..23a84c2 100644
--- a/profile.html
+++ b/profile.html
@@ -1,21 +1,19 @@
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html> <head>
<title>Buzz Chat Bot</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
</head>
<body>
<div>
<h1>{{ user_profile_data.displayName }}'s settings for the Buzz Chat Bot</h1>
<img src="{{ user_profile_data.photos.1.value }}">
</div>
<hr/>
-
+<h2>Email: {{ user_profile_data.emails.0.value }}</h2>
<hr/>
-<h2>Access Token is: {{ access_token }}</h2>
-
<h2>Profile: {{ user_profile_data.aboutMe }}</h2>
<hr/>
</body> </html>
diff --git a/xmpp.py b/xmpp.py
index e7c11f3..48a8e36 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,425 +1,425 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*)\s*(.*)", string)
if results:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*)\s*", string)
if results:
command = results.group(1)
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if not self.__scm_command:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
ALTERNATIVE_HELP_CMD = '?'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
SEARCH_CMD = 'search'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD, SEARCH_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
'%s Prints out this message' % ALTERNATIVE_HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD,
'%s [some search term] Searches for that search term on Buzz'
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def _make_wrapper(self, email_address):
return oauth_handlers.make_wrapper(email_address)
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
logging.info('Command was: %s' % message.command)
command = self._get_canonical_command(message)
self.buzz_wrapper = self._make_wrapper(message.sender)
if command and command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % command
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
else:
logging.info('No handler available for command: %s' % command)
self.unhandled_command(message)
def _get_canonical_command(self, message):
command = message.command.lower()
# The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards
# compatibility for early adopters and people who are used to IRC syntax.
if command.startswith('/'):
command = command[1:]
# Handle aliases for commands
if command == XmppHandler.ALTERNATIVE_HELP_CMD:
command = XmppHandler.HELP_CMD
return command
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
- logging.error("Invalid XMPP request: Missing required field %s", e[0])
+ logging.error("Invalid XMPP request: Missing required field: %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
- logging.error( "handle_exception: calling webapp.RequestHandler superclass")
+ logging.error('handle_exception: calling webapp.RequestHandler superclass')
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
- self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
+ self.xmpp_message.reply('Oops. Something went wrong. Sorry about that')
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
logging.debug('%s has not given access to their Google Buzz account but is attempting to post anyway' % sender)
elif not user_token.access_token_string:
logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token: %s' % (sender, str(user_token)))
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token.' % sender)
else:
url = self.buzz_wrapper.post(sender, message.arg)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def search_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
message_builder.add('Search results for %s:' % message.arg)
results = self.buzz_wrapper.search(message.arg)
for index, result in enumerate(results):
title = result['title']
permalink = result['links']['alternate'][0]['href']
line = '%s- %s : %s' % (index+1, title, permalink)
message_builder.add(line)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
ddbd5a5ee51b36132127220baecb7de8e9baadb5
|
Got rid of the callback URL in favour of a dynamic parameter that's worked out from the server's identity. OAuth dance now works on localhost.
|
diff --git a/main.py b/main.py
index 3f805c9..18515ef 100644
--- a/main.py
+++ b/main.py
@@ -1,127 +1,127 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
import oauth_handlers
import os
import settings
import xmpp
import pshb
import simple_buzz_wrapper
class ProfileViewingHandler(webapp.RequestHandler):
@login_required
def get(self):
user_token = oauth_handlers.UserToken.get_current_user_token()
- buzz_wrapper = simple_buzz_wrapper.SimpleBuzzWrapper(user_token)
+ buzz_wrapper = oauth_handlers.make_wrapper(user_token.email_address)
user_profile_data = buzz_wrapper.get_profile()
template_values = {'user_profile_data': user_profile_data, 'access_token': user_token.access_token_string}
path = os.path.join(os.path.dirname(__file__), 'profile.html')
self.response.out.write(template.render(path, template_values))
class FrontPageHandler(webapp.RequestHandler):
def get(self):
template_values = {'commands' : xmpp.XmppHandler.COMMAND_HELP_MSG_LIST,
'help_command' : xmpp.XmppHandler.HELP_CMD,
'jabber_id' : '%[email protected]' % settings.APP_NAME,
'admin_url' : settings.ADMIN_PROFILE_URL}
path = os.path.join(os.path.dirname(__file__), 'front_page.html')
self.response.out.write(template.render(path, template_values))
class PostsHandler(webapp.RequestHandler):
def _get_subscription(self):
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
return subscription
def get(self):
"""Show all the resources in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.debug("New content: %s" % self.request.body)
id = self.request.get('id')
logging.debug("Request id = '%s'", id)
# If this is a hub challenge
if self.request.get('hub.challenge'):
# If this subscription exists
mode = self.request.get('hub.mode')
topic = self.request.get('hub.topic')
if mode == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
elif mode == "unsubscribe" and not xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
else:
self.response.set_status(404)
self.response.out.write("Challenge failed")
logging.info("Challenge failed for feed: %s" % topic)
# Once a challenge has been issued there's no point in returning anything other than challenge passed or failed
return
def post(self):
"""Create a new resource in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.debug("New content: %s" % self.request.body)
id = self.request.get('id')
logging.debug("Request id = '%s'", id)
subscription = xmpp.Subscription.get_by_id(int(id))
if not subscription:
self.response.set_status(404)
self.response.out.write("No such subscription")
logging.warning('No subscription for %s' % id)
return
subscriber = subscription.subscriber
search_term = subscription.search_term
parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB)
url = parser.extractFeedUrl()
if not parser.dataValid():
parser.logErrors()
self.response.out.write("Bad entries: %s" % parser.data)
return
else:
posts = parser.extractPosts()
logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url))
xmpp.send_posts(posts, subscriber, search_term)
self.response.set_status(200)
application = webapp.WSGIApplication([
(settings.FRONT_PAGE_HANDLER_URL, FrontPageHandler),
(settings.PROFILE_HANDLER_URL, ProfileViewingHandler),
('/start_dance', oauth_handlers.DanceStartingHandler),
('/finish_dance', oauth_handlers.DanceFinishingHandler),
('/delete_tokens', oauth_handlers.TokenDeletionHandler),
('/posts', PostsHandler),
('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
diff --git a/oauth_handlers.py b/oauth_handlers.py
index 2a2e075..51811ab 100644
--- a/oauth_handlers.py
+++ b/oauth_handlers.py
@@ -1,138 +1,150 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+from google.appengine.api import users
+from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
-from google.appengine.api import users
-from google.appengine.api import xmpp
import buzz_gae_client
import logging
import os
import settings
+import simple_buzz_wrapper
class UserToken(db.Model):
# The user_id is the key_name so we don't have to make it an explicit property
request_token_string = db.StringProperty()
access_token_string = db.StringProperty()
email_address = db.StringProperty()
def get_request_token(self):
"Returns request token as a dictionary of tokens including oauth_token, oauth_token_secret and oauth_callback_confirmed."
return eval(self.request_token_string)
def set_access_token(self, access_token):
access_token_string = repr(access_token)
self.access_token_string = access_token_string
def get_access_token(self):
"Returns access token as a dictionary of tokens including consumer_key, consumer_secret, oauth_token and oauth_token_secret"
return eval(self.access_token_string)
@staticmethod
def create_user_token(request_token):
user = users.get_current_user()
user_id = user.user_id()
request_token_string = repr(request_token)
# TODO(ade) Support users who sign in to AppEngine with a federated identity aka OpenId
email = user.email()
logging.info('Creating user token: key_name: %s request_token_string: %s email_address: %s' % (
user_id, request_token_string, email))
return UserToken(key_name=user_id, request_token_string=request_token_string, access_token_string='',
email_address=email)
@staticmethod
def get_current_user_token():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
return user_token
@staticmethod
def access_token_exists():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
logging.info('user_token: %s' % user_token)
return user_token and user_token.access_token_string
@staticmethod
def find_by_email_address(email_address):
user_tokens = UserToken.gql('WHERE email_address = :1', email_address).fetch(1)
if user_tokens:
return user_tokens[0] # The result of the query is a list
else:
return None
class DanceStartingHandler(webapp.RequestHandler):
@login_required
def get(self):
logging.info('Request body %s' % self.request.body)
user = users.get_current_user()
logging.debug('Started OAuth dance for: %s' % user.email())
template_values = {"jabber_id": ("%[email protected]" % settings.APP_NAME)}
if UserToken.access_token_exists():
template_values['access_token_exists'] = 'true'
else:
# Generate the request token
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
- request_token = client.get_request_token(settings.CALLBACK_URL)
+ request_token = client.get_request_token(self.request.host_url + '/finish_dance')
+ logging.info('Request token: %s' % request_token)
# Create the request token and associate it with the current user
user_token = UserToken.create_user_token(request_token)
UserToken.put(user_token)
authorisation_url = client.generate_authorisation_url(request_token)
logging.info('Authorisation URL is: %s' % authorisation_url)
template_values['destination'] = authorisation_url
path = os.path.join(os.path.dirname(__file__), 'start_dance.html')
self.response.out.write(template.render(path, template_values))
class TokenDeletionHandler(webapp.RequestHandler):
def post(self):
user_token = UserToken.get_current_user_token()
UserToken.delete(user_token)
self.redirect(settings.FRONT_PAGE_HANDLER_URL)
class DanceFinishingHandler(webapp.RequestHandler):
def get(self):
logging.info("Request body %s" % self.request.body)
user = users.get_current_user()
logging.debug('Finished OAuth dance for: %s' % user.email())
oauth_verifier = self.request.get('oauth_verifier')
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
user_token = UserToken.get_current_user_token()
request_token = user_token.get_request_token()
access_token = client.upgrade_to_access_token(request_token, oauth_verifier)
logging.info('SUCCESS: Received access token.')
user_token.set_access_token(access_token)
UserToken.put(user_token)
logging.debug('Access token was: %s' % user_token.access_token_string)
# Send an XMPP invitation
logging.info('Sending invite to %s' % user_token.email_address)
xmpp.send_invite(user_token.email_address)
msg = 'Welcome to the BuzzChatBot: %s' % settings.APP_URL
xmpp.send_message(user_token.email_address, msg)
- self.redirect(settings.PROFILE_HANDLER_URL)
\ No newline at end of file
+ self.redirect(settings.PROFILE_HANDLER_URL)
+
+def make_wrapper(email_address):
+ user_token = UserToken.find_by_email_address(email_address)
+ if user_token:
+ oauth_params_dict = user_token.get_access_token()
+ return simple_buzz_wrapper.SimpleBuzzWrapper(api_key=settings.API_KEY, consumer_key=oauth_params_dict['consumer_key'],
+ consumer_secret=oauth_params_dict['consumer_secret'], oauth_token=oauth_params_dict['oauth_token'],
+ oauth_token_secret=oauth_params_dict['oauth_token_secret'])
+ else:
+ return simple_buzz_wrapper.SimpleBuzzWrapper(api_key=settings.API_KEY)
\ No newline at end of file
diff --git a/settings.py b/settings.py
index 8500908..8e4123f 100644
--- a/settings.py
+++ b/settings.py
@@ -1,64 +1,62 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
APP_NAME = 'buzzchatbot'
# This is an API key generated by Ade Oshineye.
# Please don't use it or you'll find that your app runs out of quota because
# you're sharing that quota with the world. Instead you should generate your own at:
# https://code.google.com/apis/console
API_KEY = 'AIzaSyDSMX3UNdWWobl3k_eml_yAXfmJZzldfLg'
#Note that the APP_URL must _not_ end in a slash as it will be concatenated with other values
APP_URL = 'http://%s.appspot.com' % APP_NAME
ADMIN_PROFILE_URL = 'http://profiles.google.com/adewale'
#PSHB settings
# This is the token that will act as a shared secret to verify that this application is the one that registered the
# given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
# OAuth consumer key and secret - you should change these to 'anonymous' unless you really are buzzchatbot.appspot.com
# Alternatively you could go here: https://www.google.com/accounts/ManageDomains and register your instance so that
# you'll get your own consumer key and consumer secret
#CONSUMER_KEY = 'buzzchatbot.appspot.com'
#CONSUMER_SECRET = 'tcw1rCMgLVY556Y0Q4rW/RnK'
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
-# OAuth callback URL
-CALLBACK_URL = '%s/finish_dance' % APP_URL
PROFILE_HANDLER_URL = '/profile'
FRONT_PAGE_HANDLER_URL = '/'
# Installation specific config ends.
diff --git a/xmpp.py b/xmpp.py
index b858370..e7c11f3 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,432 +1,425 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*)\s*(.*)", string)
if results:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*)\s*", string)
if results:
command = results.group(1)
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if not self.__scm_command:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
ALTERNATIVE_HELP_CMD = '?'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
SEARCH_CMD = 'search'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD, SEARCH_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
'%s Prints out this message' % ALTERNATIVE_HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD,
'%s [some search term] Searches for that search term on Buzz'
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def _make_wrapper(self, email_address):
- user_token = oauth_handlers.UserToken.find_by_email_address(email_address)
- if user_token:
- oauth_params_dict = user_token.get_access_token()
- return simple_buzz_wrapper.SimpleBuzzWrapper(api_key=settings.API_KEY, consumer_key=oauth_params_dict['consumer_key'],
- consumer_secret=oauth_params_dict['consumer_secret'], oauth_token=oauth_params_dict['oauth_token'],
- oauth_token_secret=oauth_params_dict['oauth_token_secret'])
- else:
- return simple_buzz_wrapper.SimpleBuzzWrapper(api_key=settings.API_KEY)
+ return oauth_handlers.make_wrapper(email_address)
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
logging.info('Command was: %s' % message.command)
command = self._get_canonical_command(message)
self.buzz_wrapper = self._make_wrapper(message.sender)
if command and command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % command
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
else:
logging.info('No handler available for command: %s' % command)
self.unhandled_command(message)
def _get_canonical_command(self, message):
command = message.command.lower()
# The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards
# compatibility for early adopters and people who are used to IRC syntax.
if command.startswith('/'):
command = command[1:]
# Handle aliases for commands
if command == XmppHandler.ALTERNATIVE_HELP_CMD:
command = XmppHandler.HELP_CMD
return command
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
logging.debug('%s has not given access to their Google Buzz account but is attempting to post anyway' % sender)
elif not user_token.access_token_string:
logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token: %s' % (sender, str(user_token)))
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token.' % sender)
else:
url = self.buzz_wrapper.post(sender, message.arg)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def search_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
message_builder.add('Search results for %s:' % message.arg)
results = self.buzz_wrapper.search(message.arg)
for index, result in enumerate(results):
title = result['title']
permalink = result['links']['alternate'][0]['href']
line = '%s- %s : %s' % (index+1, title, permalink)
message_builder.add(line)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
d863ea08dbec9b14d80ae64e5869c7af46c366d6
|
Continuing to refactor in order to backport into the client library. Added more tests. Removed app engine dependency from SimpleBuzzWrapper.
|
diff --git a/TODO b/TODO
index 0196c46..7c4e65f 100644
--- a/TODO
+++ b/TODO
@@ -1,25 +1,23 @@
Buzz Chat Bot
============
Register the app so that people don't have to trust anonymous
When someone adds the bot to their roster, send them a link to the app's website so that they can do the oauth dance
Profile page should show the email address of the current user.
Verify that phrase search works and add tests for it
-/search [some search]
Update the PRD - describing this bot
Work out how to handle location-based Track and complex searches. Perhaps using the web interface?
Use Bob Wyman's trick where /track initially does a /search and gives you the first 10 results to verify that it's worked
File a bug for language indexing in search
File a bug for search by actor.id
Allow untrack to accept a search term as well as an id
Allow for a stopword list -- useful for popular terms
Implement a 'pause' command which stops sending you messages until you issue a 'resume' command
Add the following commands
follow @[email protected]
unfollow @[email protected]
follow profiles.google.com/userid
unfollow profiles.google.com/userid
get @[email protected]
get profiles.google.com/userid
-search searchterm
-search "phrase containing more than one search term"
\ No newline at end of file
+search "phrase containing more than one search term"
diff --git a/buzz_gae_client.py b/buzz_gae_client.py
index ffc74c3..b7cb4ae 100644
--- a/buzz_gae_client.py
+++ b/buzz_gae_client.py
@@ -1,105 +1,118 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = '[email protected]'
import apiclient.discovery
import logging
import oauth_wrap
import oauth2 as oauth
import urllib
import urlparse
try:
from urlparse import parse_qs, parse_qsl, urlparse
except ImportError:
from cgi import parse_qs, parse_qsl
# TODO(ade) Replace user-agent with something specific
HEADERS = {
'user-agent': 'gdata-python-v3-sample-client/0.1',
'content-type': 'application/x-www-form-urlencoded'
}
REQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken?domain=anonymous&scope=https://www.googleapis.com/auth/buzz'
AUTHORIZE_URL = 'https://www.google.com/buzz/api/auth/OAuthAuthorizeToken?domain=anonymous&scope=https://www.googleapis.com/auth/buzz'
ACCESS_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetAccessToken'
+
+class Error(Exception):
+ """Base error for this module."""
+ pass
+
+
+class RequestError(Error):
+ """Request returned failure or unexpected data."""
+ pass
+
+
# TODO(ade) This class is really a BuzzGaeBuilder. Rename it.
class BuzzGaeClient(object):
- def __init__(self, consumer_key='anonymous', consumer_secret='anonymous'):
+ def __init__(self, consumer_key='anonymous', consumer_secret='anonymous', api_key=None,):
+ self.api_key = api_key
self.consumer = oauth.Consumer(consumer_key, consumer_secret)
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
def _make_post_request(self, client, url, parameters):
resp, content = client.request(url, 'POST', headers=HEADERS,
body=urllib.urlencode(parameters, True))
if resp['status'] != '200':
logging.warn('Request: %s failed with status: %s. Content was: %s' % (url, resp['status'], content))
- raise Exception('Invalid response %s.' % resp['status'])
+ raise RequestError('Invalid response %s.' % resp['status'])
return resp, content
def get_request_token(self, callback_url, display_name = None):
parameters = {
'oauth_callback': callback_url
}
if display_name is not None:
parameters['xoauth_displayname'] = display_name
client = oauth.Client(self.consumer)
resp, content = self._make_post_request(client, REQUEST_TOKEN_URL, parameters)
request_token = dict(parse_qsl(content))
return request_token
def generate_authorisation_url(self, request_token):
"""Returns the URL the user should be redirected to in other to gain access to their account."""
base_url = urlparse.urlparse(AUTHORIZE_URL)
query = parse_qs(base_url.query)
query['oauth_token'] = request_token['oauth_token']
logging.info(urllib.urlencode(query, True))
url = (base_url.scheme, base_url.netloc, base_url.path, base_url.params,
urllib.urlencode(query, True), base_url.fragment)
authorisation_url = urlparse.urlunparse(url)
return authorisation_url
def upgrade_to_access_token(self, request_token, oauth_verifier):
token = oauth.Token(request_token['oauth_token'],
request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(self.consumer, token)
parameters = {}
resp, content = self._make_post_request(client, ACCESS_TOKEN_URL, parameters)
access_token = dict(parse_qsl(content))
d = {
'consumer_key' : self.consumer_key,
'consumer_secret' : self.consumer_secret
}
d.update(access_token)
return d
def build_api_client(self, oauth_params=None):
if oauth_params is not None:
http = oauth_wrap.get_authorised_http(oauth_params)
- return apiclient.discovery.build('buzz', 'v1', http = http)
+ return apiclient.discovery.build('buzz', 'v1', http=http,
+ developerKey=self.api_key)
else:
- return apiclient.discovery.build('buzz', 'v1')
+ return apiclient.discovery.build('buzz', 'v1', developerKey=self.api_key)
diff --git a/functional_tests.py b/functional_tests.py
index cbbe145..4a13c64 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,376 +1,380 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from stubs import StubMessage, StubSimpleBuzzWrapper
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import oauth_handlers
import settings
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
+class StubXmppHandler(XmppHandler):
+ def _make_wrapper(self, email_address):
+ return StubSimpleBuzzWrapper()
+
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def __init__(self, methodName='runTest'):
BuzzChatBotFunctionalTestCase.__init__(self, methodName)
- self.stub_buzz_wrapper = StubSimpleBuzzWrapper()
self.stub_hub_subscriber = StubHubSubscriber()
- self.handler = XmppHandler(buzz_wrapper=self.stub_buzz_wrapper, hub_subscriber=self.stub_hub_subscriber)
+ self.handler = StubXmppHandler(hub_subscriber=self.stub_hub_subscriber)
def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
arg = 'Some day my prints will come'
message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg))
# We call the method directly here because we actually care about the object that is returned
subscription = self.handler.track_command(message=message)
self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id()))
def test_invalid_symbol_command_shows_correct_error(self):
command = '~'
message = StubMessage(body=command)
self.handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_unhandled_command_shows_correct_error(self):
command = 'wibble'
message = StubMessage(body=command)
self.handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
self.handler.message_received(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
self.handler.message_received(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
self.handler.message_received(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
self.handler.message_received(message=message)
expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
self.handler.message_received(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
- expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
+ expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'some message'
- self.assertEquals(expected_item, self.stub_buzz_wrapper.message)
+ self.assertEquals(expected_item, self.handler.buzz_wrapper.message)
def test_slash_post_command_strips_command_from_posted_message(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'some message'
- self.assertEquals(expected_item, self.stub_buzz_wrapper.message)
+ self.assertEquals(expected_item, self.handler.buzz_wrapper.message)
def test_slash_post_gets_treated_as_post_command(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
- expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
+ expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_uppercase_post_gets_treated_as_post_command(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD.upper())
self.handler.message_received(message=message)
- expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
+ expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_slash_uppercase_post_gets_treated_as_post_command(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD.upper())
self.handler.message_received(message=message)
- expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
+ expected_item = 'Posted: %s' % self.handler.buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_help_command_lists_available_commands(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
self.handler.message_received(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in XmppHandler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
def test_alternative_help_command_lists_available_commands(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ALTERNATIVE_HELP_CMD)
self.handler.message_received(message=message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % XmppHandler.ALTERNATIVE_HELP_CMD not in message.message_to_send)
self.assertTrue(len(message.message_to_send) > 0)
for command in XmppHandler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
def test_search_command_succeeds_for_single_token(self):
arg = 'onewordsearchterm'
message = StubMessage(body='%s %s ' % (XmppHandler.SEARCH_CMD,arg))
self.handler.message_received(message=message)
self.assertTrue(len(message.message_to_send) > 0, message)
class XmppHandlerHttpTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
+
def test_help_command_can_be_triggered_via_http(self):
# Help command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'help'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_list_command_can_be_triggered_via_http(self):
# List command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'list'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_search_command_can_be_triggered_via_http(self):
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'search somesearchterm'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_invalid_http_request_triggers_error(self):
response = self.post('/_ah/xmpp/message/chat/', data={}, expect_errors=True)
self.assertEquals('400 Bad Request', response.status)
diff --git a/settings.py b/settings.py
index 1b14899..8500908 100644
--- a/settings.py
+++ b/settings.py
@@ -1,58 +1,64 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
APP_NAME = 'buzzchatbot'
+# This is an API key generated by Ade Oshineye.
+# Please don't use it or you'll find that your app runs out of quota because
+# you're sharing that quota with the world. Instead you should generate your own at:
+# https://code.google.com/apis/console
+API_KEY = 'AIzaSyDSMX3UNdWWobl3k_eml_yAXfmJZzldfLg'
+
#Note that the APP_URL must _not_ end in a slash as it will be concatenated with other values
APP_URL = 'http://%s.appspot.com' % APP_NAME
ADMIN_PROFILE_URL = 'http://profiles.google.com/adewale'
#PSHB settings
# This is the token that will act as a shared secret to verify that this application is the one that registered the
# given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
# OAuth consumer key and secret - you should change these to 'anonymous' unless you really are buzzchatbot.appspot.com
# Alternatively you could go here: https://www.google.com/accounts/ManageDomains and register your instance so that
# you'll get your own consumer key and consumer secret
#CONSUMER_KEY = 'buzzchatbot.appspot.com'
#CONSUMER_SECRET = 'tcw1rCMgLVY556Y0Q4rW/RnK'
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
# OAuth callback URL
CALLBACK_URL = '%s/finish_dance' % APP_URL
PROFILE_HANDLER_URL = '/profile'
FRONT_PAGE_HANDLER_URL = '/'
# Installation specific config ends.
diff --git a/simple_buzz_wrapper.py b/simple_buzz_wrapper.py
index 2b164a8..619815b 100644
--- a/simple_buzz_wrapper.py
+++ b/simple_buzz_wrapper.py
@@ -1,67 +1,69 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import buzz_gae_client
-import settings
-import oauth_handlers
import logging
class SimpleBuzzWrapper(object):
"Simple client that exposes the bare minimum set of common Buzz operations"
- def __init__(self, user_token=None):
- if user_token:
- self.current_user_token = user_token
- self.builder = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
+ def __init__(self, api_key=None, consumer_key='anonymous', consumer_secret='anonymous',
+ oauth_token=None, oauth_token_secret=None):
+
+ self.builder = buzz_gae_client.BuzzGaeClient(consumer_key, consumer_secret, api_key=api_key)
+ if oauth_token and oauth_token_secret:
+ oauth_params_dict = {}
+ oauth_params_dict['consumer_key'] = consumer_key
+ oauth_params_dict['consumer_secret'] = consumer_secret
+ oauth_params_dict['oauth_token'] = oauth_token
+ oauth_params_dict['oauth_token_secret'] = oauth_token_secret
+ self.api_client = self.builder.build_api_client(oauth_params=oauth_params_dict)
+ else:
+ self.api_client = self.builder.build_api_client()
def search(self, query, user_token=None, max_results=10):
if query is None or query.strip() is '':
return None
- api_client = self.builder.build_api_client()
- json = api_client.activities().search(q=query, max_results=max_results).execute()
+ json = self.api_client.activities().search(q=query, max_results=max_results).execute()
if json.has_key('items'):
return json['items']
return []
def post(self, sender, message_body):
if message_body is None or message_body.strip() is '':
return None
- user_token = oauth_handlers.UserToken.find_by_email_address(sender)
- api_client = self.builder.build_api_client(user_token.get_access_token())
-
#TODO(ade) What happens with users who have hidden their email address?
- # Switch to @me so it won't matter
+ # Maybe we should switch to @me so it won't matter?
user_id = sender.split('@')[0]
- activities = api_client.activities()
+ activities = self.api_client.activities()
logging.info('Retrieved activities for: %s' % user_id)
activity = activities.insert(userId=user_id, body={
'data' : {
'title': message_body,
'object': {
'content': message_body,
'type': 'note'}
}
}
).execute()
url = activity['links']['alternate'][0]['href']
logging.info('Just created: %s' % url)
return url
- def get_profile(self):
- api_client = self.builder.build_api_client(self.current_user_token.get_access_token())
- user_profile_data = api_client.people().get(userId='@me').execute()
+ def get_profile(self, user_id='@me'):
+ user_profile_data = self.api_client.people().get(userId=user_id).execute()
return user_profile_data
diff --git a/simple_buzz_wrapper_tests.py b/simple_buzz_wrapper_tests.py
index 16d2c3e..5858d3a 100644
--- a/simple_buzz_wrapper_tests.py
+++ b/simple_buzz_wrapper_tests.py
@@ -1,44 +1,65 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import simple_buzz_wrapper
import unittest
class SimpleBuzzWrapperTest(unittest.TestCase):
-# None of the tests make a remote call. We assume the underlying libraries
+# None of these tests make a remote call. We assume the underlying libraries
# and servers are working.
def test_wrapper_rejects_empty_post(self):
wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
self.assertEquals(None, wrapper.post('[email protected]', ''))
def test_wrapper_rejects_post_containing_only_whitespace(self):
wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
self.assertEquals(None, wrapper.post('[email protected]', ' '))
def test_wrapper_rejects_none_post(self):
wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
self.assertEquals(None, wrapper.post('[email protected]', None))
def test_wrapper_rejects_empty_search(self):
wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
self.assertEquals(None, wrapper.search(''))
def test_wrapper_rejects_search_containing_only_whitespace(self):
wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
self.assertEquals(None, wrapper.search(' '))
def test_wrapper_rejects_search_with_none(self):
wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
- self.assertEquals(None, wrapper.search(None))
\ No newline at end of file
+ self.assertEquals(None, wrapper.search(None))
+
+class SimpleBuzzWrapperRemoteTest(unittest.TestCase):
+# These tests make remote calls
+ def test_searching_returns_results(self):
+ wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
+ results = wrapper.search('oshineye')
+ self.assertTrue(results is not None)
+
+ def test_searching_honours_max_results(self):
+ wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
+ max = 5
+ results = wrapper.search('oshineye', max_results=max)
+ self.assertEquals(max, len(results))
+
+ def test_can_fetch_profile(self):
+ wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
+ profile = wrapper.get_profile('googlebuzz')
+ self.assertTrue(profile is not None)
+
+ profile = wrapper.get_profile(user_id = 'adewale')
+ self.assertTrue(profile is not None)
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index 2bb8e7b..b858370 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,421 +1,432 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*)\s*(.*)", string)
if results:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*)\s*", string)
if results:
command = results.group(1)
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if not self.__scm_command:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
-
+
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
ALTERNATIVE_HELP_CMD = '?'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
SEARCH_CMD = 'search'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD, SEARCH_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
'%s Prints out this message' % ALTERNATIVE_HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD,
'%s [some search term] Searches for that search term on Buzz'
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
- def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper(), hub_subscriber=pshb.HubSubscriber()):
- self.buzz_wrapper = buzz_wrapper
+ def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
+ def _make_wrapper(self, email_address):
+ user_token = oauth_handlers.UserToken.find_by_email_address(email_address)
+ if user_token:
+ oauth_params_dict = user_token.get_access_token()
+ return simple_buzz_wrapper.SimpleBuzzWrapper(api_key=settings.API_KEY, consumer_key=oauth_params_dict['consumer_key'],
+ consumer_secret=oauth_params_dict['consumer_secret'], oauth_token=oauth_params_dict['oauth_token'],
+ oauth_token_secret=oauth_params_dict['oauth_token_secret'])
+ else:
+ return simple_buzz_wrapper.SimpleBuzzWrapper(api_key=settings.API_KEY)
+
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
logging.info('Command was: %s' % message.command)
command = self._get_canonical_command(message)
+
+ self.buzz_wrapper = self._make_wrapper(message.sender)
if command and command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % command
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
else:
logging.info('No handler available for command: %s' % command)
self.unhandled_command(message)
def _get_canonical_command(self, message):
command = message.command.lower()
# The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards
# compatibility for early adopters and people who are used to IRC syntax.
if command.startswith('/'):
command = command[1:]
# Handle aliases for commands
if command == XmppHandler.ALTERNATIVE_HELP_CMD:
command = XmppHandler.HELP_CMD
return command
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
logging.debug('%s has not given access to their Google Buzz account but is attempting to post anyway' % sender)
elif not user_token.access_token_string:
logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token: %s' % (sender, str(user_token)))
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token.' % sender)
else:
url = self.buzz_wrapper.post(sender, message.arg)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def search_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
message_builder.add('Search results for %s:' % message.arg)
results = self.buzz_wrapper.search(message.arg)
for index, result in enumerate(results):
title = result['title']
permalink = result['links']['alternate'][0]['href']
line = '%s- %s : %s' % (index+1, title, permalink)
message_builder.add(line)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
90e7fadcb11b2de818d678ae77cf0487eefae3b9
|
Added ability to perform a search using the search functionality in the updated SimpleBuzzWrapper
|
diff --git a/README b/README
index ee9bf39..cfa0639 100644
--- a/README
+++ b/README
@@ -1,55 +1,56 @@
This is an experimental jaiku-style chat bot for Google Buzz.
If it breaks you get to keep both pieces.
What does it do?
================
At the moment it lets you ask for:
help Prints out this message
track [search term] Starts tracking the given search term and returns the id for your subscription
untrack [id] Removes your subscription for that id
list Lists all search terms and ids currently being tracked by you
about Tells you which instance of the Buzz Chat Bot you are using
post [some message] Posts that message to Buzz
Why does it exist?
==================
There are 2 sets of reasons why this bot exists.
1- I wanted to create a demo app (using the new Python client library: http://code.google.com/p/google-api-python-client/ ) which would show people a different kind of Buzz app. It's not trying to be a slightly different clone of the existing UI.
2- My experience with Jaiku and Friendfeed taught me that chat interfaces have a number of advantage over web interfaces:
- they're quicker since you can't beat the latency of alt-tabbing to Adium
- they're always on
- they're transient so you don't feel inundated if you track lots of keywords or see lots of posts because they all just flow by
- they encourage statuscasting: http://www.designingsocialinterfaces.com/patterns/Statuscasting which makes for a more conversational experience
- they allow people and brands to conveniently track keywords without having to learn how PSHB works
What does it require?
=====================
App Engine
Python
Tests
=====
To run the tests you need gae-testbed, nose and nose-gae. So...
sudo easy_install gaetestbed
sudo easy_install nose
sudo easy_install nosegae
They can be run like this:
nosetests --with-gae tracker_tests.py
Although I prefer to do something like this:
nosetests --with-gae *test*py
INSTALLATION
============
This isn't yet ready for installation by people who don't feel like changing the Python code. However if you feel brave you should:
- Register an AppEngine application at http://appengine.google.com/start/createapp?
- Change the app.yaml file to have the same Application Identifier as your application.
- Take a look at settings.py
-- Change the settings.APP_NAME constant to have the same Application Identifier as your application.
-- Change the settings.SECRET_TOKEN from the default
-- Use the Google App Engine Launcher: http://code.google.com/appengine/downloads.html#Google_App_Engine_SDK_for_Python to deploy the application.
\ No newline at end of file
+- Use the Google App Engine Launcher: http://code.google.com/appengine/downloads.html#Google_App_Engine_SDK_for_Python to deploy the application.
+
diff --git a/functional_tests.py b/functional_tests.py
index cf309a9..cbbe145 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,377 +1,376 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from stubs import StubMessage, StubSimpleBuzzWrapper
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import oauth_handlers
import settings
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def __init__(self, methodName='runTest'):
BuzzChatBotFunctionalTestCase.__init__(self, methodName)
self.stub_buzz_wrapper = StubSimpleBuzzWrapper()
self.stub_hub_subscriber = StubHubSubscriber()
self.handler = XmppHandler(buzz_wrapper=self.stub_buzz_wrapper, hub_subscriber=self.stub_hub_subscriber)
def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
arg = 'Some day my prints will come'
message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg))
# We call the method directly here because we actually care about the object that is returned
subscription = self.handler.track_command(message=message)
self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id()))
def test_invalid_symbol_command_shows_correct_error(self):
command = '~'
message = StubMessage(body=command)
self.handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_unhandled_command_shows_correct_error(self):
command = 'wibble'
message = StubMessage(body=command)
self.handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
self.handler.message_received(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
self.handler.message_received(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
self.handler.message_received(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
self.handler.message_received(message=message)
expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
self.handler.message_received(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'some message'
self.assertEquals(expected_item, self.stub_buzz_wrapper.message)
def test_slash_post_command_strips_command_from_posted_message(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'some message'
self.assertEquals(expected_item, self.stub_buzz_wrapper.message)
def test_slash_post_gets_treated_as_post_command(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_uppercase_post_gets_treated_as_post_command(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD.upper())
self.handler.message_received(message=message)
expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_slash_uppercase_post_gets_treated_as_post_command(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD.upper())
self.handler.message_received(message=message)
expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_help_command_lists_available_commands(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
self.handler.message_received(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in XmppHandler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
def test_alternative_help_command_lists_available_commands(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ALTERNATIVE_HELP_CMD)
self.handler.message_received(message=message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % XmppHandler.ALTERNATIVE_HELP_CMD not in message.message_to_send)
self.assertTrue(len(message.message_to_send) > 0)
for command in XmppHandler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
- def IGNORE__test_search_command_succeeds_for_single_token(self):
+ def test_search_command_succeeds_for_single_token(self):
arg = 'onewordsearchterm'
- message = StubMessage( body='%s %s ' % (XmppHandler.SEARCH_CMD,arg))
+ message = StubMessage(body='%s %s ' % (XmppHandler.SEARCH_CMD,arg))
- # We call the method directly here because we actually care about the object that is returned
- results_string = self.handler.search_command(message=message)
- self.assertTrue(XmppHandler.SEARCH_RESULTS_PREFIX in message.message_to_send)
+ self.handler.message_received(message=message)
+
+ self.assertTrue(len(message.message_to_send) > 0, message)
class XmppHandlerHttpTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_help_command_can_be_triggered_via_http(self):
# Help command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'help'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_list_command_can_be_triggered_via_http(self):
# List command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'list'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_search_command_can_be_triggered_via_http(self):
- # List command was chosen as it has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'search somesearchterm'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_invalid_http_request_triggers_error(self):
response = self.post('/_ah/xmpp/message/chat/', data={}, expect_errors=True)
self.assertEquals('400 Bad Request', response.status)
diff --git a/simple_buzz_wrapper.py b/simple_buzz_wrapper.py
index d6e39f8..2b164a8 100644
--- a/simple_buzz_wrapper.py
+++ b/simple_buzz_wrapper.py
@@ -1,69 +1,67 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import buzz_gae_client
import settings
import oauth_handlers
import logging
class SimpleBuzzWrapper(object):
- "Simple client that exposes the bare minimum set of Buzz operations"
+ "Simple client that exposes the bare minimum set of common Buzz operations"
def __init__(self, user_token=None):
if user_token:
self.current_user_token = user_token
self.builder = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
- def search(self, sender, message_body ):
- """ TODO(julian): standardize methods for accessing api clients once it's clear what the implications
- of the 2 paths (email, user_token) are """
- if message_body is None or message_body.strip() is '':
+ def search(self, query, user_token=None, max_results=10):
+ if query is None or query.strip() is '':
return None
+ api_client = self.builder.build_api_client()
- user_token = oauth_handlers.UserToken.find_by_email_address(sender)
- api_client = self.builder.build_api_client(user_token.get_access_token())
-
- # TODO(ade) Implement search functionality
+ json = api_client.activities().search(q=query, max_results=max_results).execute()
+ if json.has_key('items'):
+ return json['items']
+ return []
-
def post(self, sender, message_body):
if message_body is None or message_body.strip() is '':
return None
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
api_client = self.builder.build_api_client(user_token.get_access_token())
#TODO(ade) What happens with users who have hidden their email address?
# Switch to @me so it won't matter
user_id = sender.split('@')[0]
activities = api_client.activities()
logging.info('Retrieved activities for: %s' % user_id)
activity = activities.insert(userId=user_id, body={
'data' : {
'title': message_body,
'object': {
'content': message_body,
'type': 'note'}
}
}
).execute()
url = activity['links']['alternate'][0]['href']
logging.info('Just created: %s' % url)
return url
def get_profile(self):
api_client = self.builder.build_api_client(self.current_user_token.get_access_token())
user_profile_data = api_client.people().get(userId='@me').execute()
return user_profile_data
diff --git a/simple_buzz_wrapper_tests.py b/simple_buzz_wrapper_tests.py
index ead2c00..16d2c3e 100644
--- a/simple_buzz_wrapper_tests.py
+++ b/simple_buzz_wrapper_tests.py
@@ -1,29 +1,44 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import simple_buzz_wrapper
import unittest
class SimpleBuzzWrapperTest(unittest.TestCase):
+# None of the tests make a remote call. We assume the underlying libraries
+# and servers are working.
+
def test_wrapper_rejects_empty_post(self):
wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
self.assertEquals(None, wrapper.post('[email protected]', ''))
def test_wrapper_rejects_post_containing_only_whitespace(self):
wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
self.assertEquals(None, wrapper.post('[email protected]', ' '))
def test_wrapper_rejects_none_post(self):
wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
- self.assertEquals(None, wrapper.post('[email protected]', None))
\ No newline at end of file
+ self.assertEquals(None, wrapper.post('[email protected]', None))
+
+ def test_wrapper_rejects_empty_search(self):
+ wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
+ self.assertEquals(None, wrapper.search(''))
+
+ def test_wrapper_rejects_search_containing_only_whitespace(self):
+ wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
+ self.assertEquals(None, wrapper.search(' '))
+
+ def test_wrapper_rejects_search_with_none(self):
+ wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
+ self.assertEquals(None, wrapper.search(None))
\ No newline at end of file
diff --git a/stubs.py b/stubs.py
index ad53726..cbaa572 100644
--- a/stubs.py
+++ b/stubs.py
@@ -1,42 +1,45 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from xmpp import SlashlessCommandMessage
import pshb
import simple_buzz_wrapper
class StubHubSubscriber(pshb.HubSubscriber):
def subscribe(self, url, hub, callback_url):
self.callback_url = callback_url
def unsubscribe(self, url, hub, callback_url):
self.callback_url = callback_url
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
self.command, self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
self.message_to_send = None
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
- return self.url
\ No newline at end of file
+ return self.url
+
+ def search(self, message):
+ return [{'title':'Title1', 'links':{'alternate':[{'href':'http://www.example.com/1'}]}}, {'title': 'Title2', 'links':{'alternate':[{'href':'http://www.example.com/2'}]}}]
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index ca3a0f0..2bb8e7b 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,405 +1,421 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*)\s*(.*)", string)
if results:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*)\s*", string)
if results:
command = results.group(1)
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if not self.__scm_command:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
ALTERNATIVE_HELP_CMD = '?'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
+ SEARCH_CMD = 'search'
- PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
+ PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD, SEARCH_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
'%s Prints out this message' % ALTERNATIVE_HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
- '%s [some message] Posts that message to Buzz' % POST_CMD
+ '%s [some message] Posts that message to Buzz' % POST_CMD,
+ '%s [some search term] Searches for that search term on Buzz'
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper(), hub_subscriber=pshb.HubSubscriber()):
self.buzz_wrapper = buzz_wrapper
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
logging.info('Command was: %s' % message.command)
command = self._get_canonical_command(message)
if command and command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % command
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
else:
logging.info('No handler available for command: %s' % command)
self.unhandled_command(message)
def _get_canonical_command(self, message):
command = message.command.lower()
# The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards
# compatibility for early adopters and people who are used to IRC syntax.
if command.startswith('/'):
command = command[1:]
# Handle aliases for commands
if command == XmppHandler.ALTERNATIVE_HELP_CMD:
command = XmppHandler.HELP_CMD
return command
-
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
+
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
logging.debug('%s has not given access to their Google Buzz account but is attempting to post anyway' % sender)
elif not user_token.access_token_string:
logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token: %s' % (sender, str(user_token)))
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token.' % sender)
else:
url = self.buzz_wrapper.post(sender, message.arg)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
+ def search_command(self, message):
+ logging.info('Received message from: %s' % message.sender)
+ message_builder = MessageBuilder()
+ sender = extract_sender_email_address(message.sender)
+ logging.info('Sender: %s' % sender)
+
+ message_builder.add('Search results for %s:' % message.arg)
+ results = self.buzz_wrapper.search(message.arg)
+ for index, result in enumerate(results):
+ title = result['title']
+ permalink = result['links']['alternate'][0]['href']
+ line = '%s- %s : %s' % (index+1, title, permalink)
+ message_builder.add(line)
+ reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
d1fc785360144ad5164a8417f6845e3e8fe5c4fe
|
Added new files from apiclient that I forgot to add last time
|
diff --git a/apiclient/ext/django.py b/apiclient/ext/django.py
new file mode 100644
index 0000000..4217eaa
--- /dev/null
+++ b/apiclient/ext/django.py
@@ -0,0 +1,36 @@
+from django.db import models
+
+class OAuthCredentialsField(models.Field):
+
+ __metaclass__ = models.SubfieldBase
+
+ def db_type(self):
+ return 'VARCHAR'
+
+ def to_python(self, value):
+ if value is None:
+ return None
+ if isinstance(value, apiclient.oauth.Credentials):
+ return value
+ return pickle.loads(base64.b64decode(value))
+
+ def get_db_prep_value(self, value):
+ return base64.b64encode(pickle.dumps(value))
+
+class FlowThreeLeggedField(models.Field):
+
+ __metaclass__ = models.SubfieldBase
+
+ def db_type(self):
+ return 'VARCHAR'
+
+ def to_python(self, value):
+ print "In to_python", value
+ if value is None:
+ return None
+ if isinstance(value, apiclient.oauth.FlowThreeLegged):
+ return value
+ return pickle.loads(base64.b64decode(value))
+
+ def get_db_prep_value(self, value):
+ return base64.b64encode(pickle.dumps(value))
diff --git a/apiclient/json.py b/apiclient/json.py
new file mode 100644
index 0000000..7fb7846
--- /dev/null
+++ b/apiclient/json.py
@@ -0,0 +1,32 @@
+# Copyright (C) 2010 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Utility module to import a JSON module
+
+Hides all the messy details of exactly where
+we get a simplejson module from.
+"""
+
+__author__ = '[email protected] (Joe Gregorio)'
+
+
+try: # pragma: no cover
+ import simplejson
+except ImportError: # pragma: no cover
+ try:
+ # Try to import from django, should work on App Engine
+ from django.utils import simplejson
+ except ImportError:
+ # Should work for Python2.6 and higher.
+ import json as simplejson
|
adewale/Buzz-Chat-Bot
|
6210667b9308dabe6224c4e92a5909df10550d68
|
Added more logging. Upgraded to latest version of discovery-based Python Buzz client library.
|
diff --git a/apiclient/contrib/buzz/future.json b/apiclient/contrib/buzz/future.json
index ed6f0f9..81b61bf 100644
--- a/apiclient/contrib/buzz/future.json
+++ b/apiclient/contrib/buzz/future.json
@@ -1,147 +1,148 @@
{
"data": {
"buzz": {
"v1": {
"baseUrl": "https://www.googleapis.com/",
"auth": {
"request": {
"url": "https://www.google.com/accounts/OAuthGetRequestToken",
"parameters": {
"xoauth_displayname": {
"parameterType": "query",
"required": false
},
"domain": {
"parameterType": "query",
"required": true
},
"scope": {
"parameterType": "query",
"required": true
}
}
},
"authorize": {
"url": "https://www.google.com/buzz/api/auth/OAuthAuthorizeToken",
"parameters": {
"oauth_token": {
"parameterType": "query",
"required": true
},
"iconUrl": {
"parameterType": "query",
"required": false
},
"domain": {
"parameterType": "query",
"required": true
},
"scope": {
"parameterType": "query",
"required": true
}
}
},
"access": {
"url": "https://www.google.com/accounts/OAuthGetAccessToken",
"parameters": {
"domain": {
"parameterType": "query",
"required": true
},
"scope": {
"parameterType": "query",
"required": true
}
}
}
},
"resources": {
"activities": {
"methods": {
"delete": {},
+ "extractPeopleFromSearch": {},
"get": {},
"insert": {},
"list": {
"next": {
"type": "uri",
"location": ["links", "next", 0, "href"]
}
},
"search": {
"next": {
"type": "uri",
"location": ["links", "next", 0, "href"]
}
},
"update": {}
}
},
"comments": {
"methods": {
"delete": {},
"get": {},
"insert": {},
"list": {},
"update": {}
}
},
"feeds": {
"methods": {
"delete": {},
"insert": {},
"list": {},
"update": {}
}
},
"groups": {
"methods": {
"delete": {},
"get": {},
"insert": {},
"list": {
"next": {
"type": "uri",
"location": ["links", "next", 0, "href"]
}
},
"update": {}
}
},
"people": {
"methods": {
"delete": {},
"get": {},
"liked": {
"next": {
"type": "uri",
"location": ["links", "next", 0, "href"]
}
},
"list": {},
"relatedToUri": {},
"reshared": {},
"search": {},
"update": {}
}
},
"photos": {
"methods": {
"insert": {}
}
},
"related": {
"methods": {
"list": {}
}
},
"search": {
"methods": {
"extractPeople": {}
}
}
}
}
}
}
}
diff --git a/apiclient/contrib/moderator/future.json b/apiclient/contrib/moderator/future.json
index 7e3d978..87d525b 100644
--- a/apiclient/contrib/moderator/future.json
+++ b/apiclient/contrib/moderator/future.json
@@ -1,113 +1,113 @@
{
"data": {
"moderator": {
"v1": {
- "baseUrl": "https://www.googleapis.com/",
+ "baseUrl": "https://www.googleapis.com/",
"auth": {
"request": {
"url": "https://www.google.com/accounts/OAuthGetRequestToken",
"parameters": {
"xoauth_displayname": {
"parameterType": "query",
"required": false
},
"domain": {
"parameterType": "query",
"required": false
},
"scope": {
"parameterType": "query",
"required": true
}
}
},
"authorize": {
"url": "https://www.google.com/accounts/OAuthAuthorizeToken",
"parameters": {
"oauth_token": {
"parameterType": "query",
"required": true
},
"iconUrl": {
"parameterType": "query",
"required": false
},
"domain": {
"parameterType": "query",
"required": false
},
"scope": {
"parameterType": "query",
"required": true
}
}
},
"access": {
"url": "https://www.google.com/accounts/OAuthGetAccessToken",
"parameters": {
"domain": {
"parameterType": "query",
"required": false
},
"scope": {
"parameterType": "query",
"required": true
}
}
}
},
"resources": {
"profiles": {
"methods": {
"get": {},
"update": {}
}
},
"responses": {
"methods": {
"insert": {},
"list": {}
}
},
"series": {
"methods": {
"get": {},
"insert": {},
"list": {},
"update": {}
}
},
"submissions": {
"methods": {
"get": {},
"insert": {},
"list": {}
}
},
"tags": {
"methods": {
"delete": {},
"insert": {},
"list": {}
}
},
"topics": {
"methods": {
"get": {},
"insert": {},
"list": {}
}
},
"votes": {
"methods": {
"get": {},
"insert": {},
"list": {},
"update": {}
}
}
}
}
}
}
}
diff --git a/apiclient/discovery.py b/apiclient/discovery.py
index 8aba7ef..73a87da 100644
--- a/apiclient/discovery.py
+++ b/apiclient/discovery.py
@@ -1,312 +1,320 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Client for discovery based APIs
A client library for Google's discovery
based APIs.
"""
__author__ = '[email protected] (Joe Gregorio)'
import httplib2
import logging
import os
import re
import uritemplate
import urllib
import urlparse
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
from apiclient.http import HttpRequest
+from apiclient.json import simplejson
-try: # pragma: no cover
- import simplejson
-except ImportError: # pragma: no cover
- try:
- # Try to import from django, should work on App Engine
- from django.utils import simplejson
- except ImportError:
- # Should work for Python2.6 and higher.
- import json as simplejson
+class Error(Exception):
+ """Base error for this module."""
+ pass
-class HttpError(Exception):
- pass
+class HttpError(Error):
+ """HTTP data was invalid or unexpected."""
+ def __init__(self, resp, detail):
+ self.resp = resp
+ self.detail = detail
+ def __str__(self):
+ return self.detail
-class UnknownLinkType(Exception):
+class UnknownLinkType(Error):
+ """Link type unknown or unexpected."""
pass
+
DISCOVERY_URI = ('http://www.googleapis.com/discovery/0.1/describe'
'{?api,apiVersion}')
def key2param(key):
"""
max-results -> max_results
"""
result = []
key = list(key)
if not key[0].isalpha():
result.append('x')
for c in key:
if c.isalnum():
result.append(c)
else:
result.append('_')
return ''.join(result)
class JsonModel(object):
def request(self, headers, path_params, query_params, body_value):
query = self.build_query(query_params)
headers['accept'] = 'application/json'
if 'user-agent' in headers:
headers['user-agent'] += ' '
else:
headers['user-agent'] = ''
headers['user-agent'] += 'google-api-python-client/1.0'
if body_value is None:
return (headers, path_params, query, None)
else:
- model = {'data': body_value}
+ if len(body_value) == 1 and 'data' in body_value:
+ model = body_value
+ else:
+ model = {'data': body_value}
headers['content-type'] = 'application/json'
return (headers, path_params, query, simplejson.dumps(model))
def build_query(self, params):
- params.update({'alt': 'json', 'prettyprint': 'true'})
+ params.update({'alt': 'json'})
astuples = []
for key, value in params.iteritems():
if getattr(value, 'encode', False) and callable(value.encode):
value = value.encode('utf-8')
astuples.append((key, value))
return '?' + urllib.urlencode(astuples)
def response(self, resp, content):
# Error handling is TBD, for example, do we retry
# for some operation/error combinations?
if resp.status < 300:
+ if resp.status == 204:
+ # A 204: No Content response should be treated differently to all the other success states
+ return simplejson.loads('{}')
return simplejson.loads(content)['data']
else:
logging.debug('Content from bad request was: %s' % content)
- if resp.get('content-type', '') != 'application/json':
- raise HttpError('%d %s' % (resp.status, resp.reason))
+ if resp.get('content-type', '').startswith('application/json'):
+ raise HttpError(resp, simplejson.loads(content)['error'])
else:
- raise HttpError(simplejson.loads(content)['error'])
+ raise HttpError(resp, '%d %s' % (resp.status, resp.reason))
def build(serviceName, version, http=None,
discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=JsonModel()):
params = {
'api': serviceName,
'apiVersion': version
}
if http is None:
http = httplib2.Http()
requested_url = uritemplate.expand(discoveryServiceUrl, params)
logging.info('URL being requested: %s' % requested_url)
resp, content = http.request(requested_url)
d = simplejson.loads(content)
service = d['data'][serviceName][version]
fn = os.path.join(os.path.dirname(__file__), "contrib",
serviceName, "future.json")
f = file(fn, "r")
d = simplejson.load(f)
f.close()
future = d['data'][serviceName][version]['resources']
auth_discovery = d['data'][serviceName][version]['auth']
base = service['baseUrl']
resources = service['resources']
class Service(object):
"""Top level interface for a service"""
def __init__(self, http=http):
self._http = http
self._baseUrl = base
self._model = model
self._developerKey = developerKey
def auth_discovery(self):
return auth_discovery
def createMethod(theclass, methodName, methodDesc, futureDesc):
- def method(self, **kwargs):
+ def method(self):
return createResource(self._http, self._baseUrl, self._model,
methodName, self._developerKey, methodDesc, futureDesc)
setattr(method, '__doc__', 'A description of how to use this function')
setattr(theclass, methodName, method)
for methodName, methodDesc in resources.iteritems():
createMethod(Service, methodName, methodDesc, future[methodName])
return Service()
def createResource(http, baseUrl, model, resourceName, developerKey,
resourceDesc, futureDesc):
class Resource(object):
"""A class for interacting with a resource."""
def __init__(self):
self._http = http
self._baseUrl = baseUrl
self._model = model
self._developerKey = developerKey
def createMethod(theclass, methodName, methodDesc, futureDesc):
pathUrl = methodDesc['pathUrl']
pathUrl = re.sub(r'\{', r'{+', pathUrl)
httpMethod = methodDesc['httpMethod']
argmap = {}
if httpMethod in ['PUT', 'POST']:
argmap['body'] = 'body'
required_params = [] # Required parameters
pattern_params = {} # Parameters that must match a regex
query_params = [] # Parameters that will be used in the query string
path_params = {} # Parameters that will be used in the base URL
if 'parameters' in methodDesc:
for arg, desc in methodDesc['parameters'].iteritems():
param = key2param(arg)
argmap[param] = arg
if desc.get('pattern', ''):
pattern_params[param] = desc['pattern']
if desc.get('required', False):
required_params.append(param)
if desc.get('parameterType') == 'query':
query_params.append(param)
if desc.get('parameterType') == 'path':
path_params[param] = param
def method(self, **kwargs):
for name in kwargs.iterkeys():
if name not in argmap:
raise TypeError('Got an unexpected keyword argument "%s"' % name)
for name in required_params:
if name not in kwargs:
raise TypeError('Missing required parameter "%s"' % name)
for name, regex in pattern_params.iteritems():
if name in kwargs:
if re.match(regex, kwargs[name]) is None:
raise TypeError(
'Parameter "%s" value "%s" does not match the pattern "%s"' %
(name, kwargs[name], regex))
actual_query_params = {}
actual_path_params = {}
for key, value in kwargs.iteritems():
if key in query_params:
actual_query_params[argmap[key]] = value
if key in path_params:
actual_path_params[argmap[key]] = value
body_value = kwargs.get('body', None)
if self._developerKey:
actual_query_params['key'] = self._developerKey
headers = {}
headers, params, query, body = self._model.request(headers,
actual_path_params, actual_query_params, body_value)
# TODO(ade) This exists to fix a bug in V1 of the Buzz discovery document.
# Base URLs should not contain any path elements. If they do then urlparse.urljoin will strip them out
# This results in an incorrect URL which returns a 404
url_result = urlparse.urlsplit(self._baseUrl)
new_base_url = url_result.scheme + '://' + url_result.netloc
expanded_url = uritemplate.expand(pathUrl, params)
url = urlparse.urljoin(new_base_url, url_result.path + expanded_url + query)
logging.info('URL being requested: %s' % url)
return HttpRequest(self._http, url, method=httpMethod, body=body,
headers=headers, postproc=self._model.response)
docs = ['A description of how to use this function\n\n']
for arg in argmap.iterkeys():
required = ""
if arg in required_params:
required = " (required)"
docs.append('%s - A parameter%s\n' % (arg, required))
setattr(method, '__doc__', ''.join(docs))
setattr(theclass, methodName, method)
def createNextMethod(theclass, methodName, methodDesc):
def method(self, previous):
"""
Takes a single argument, 'body', which is the results
from the last call, and returns the next set of items
in the collection.
Returns None if there are no more items in
the collection.
"""
if methodDesc['type'] != 'uri':
raise UnknownLinkType(methodDesc['type'])
try:
p = previous
for key in methodDesc['location']:
p = p[key]
url = p
except (KeyError, TypeError):
return None
if self._developerKey:
parsed = list(urlparse.urlparse(url))
q = parse_qsl(parsed[4])
q.append(('key', self._developerKey))
parsed[4] = urllib.urlencode(q)
url = urlparse.urlunparse(parsed)
headers = {}
headers, params, query, body = self._model.request(headers, {}, {}, None)
logging.info('URL being requested: %s' % url)
resp, content = self._http.request(url, method='GET', headers=headers)
return HttpRequest(self._http, url, method='GET',
headers=headers, postproc=self._model.response)
setattr(theclass, methodName, method)
# Add basic methods to Resource
for methodName, methodDesc in resourceDesc['methods'].iteritems():
future = futureDesc['methods'].get(methodName, {})
createMethod(Resource, methodName, methodDesc, future)
# Add <m>_next() methods to Resource
for methodName, methodDesc in futureDesc['methods'].iteritems():
if 'next' in methodDesc and methodName in resourceDesc['methods']:
createNextMethod(Resource, methodName + "_next", methodDesc['next'])
return Resource()
diff --git a/apiclient/oauth.py b/apiclient/oauth.py
index 8b827c6..9907c46 100644
--- a/apiclient/oauth.py
+++ b/apiclient/oauth.py
@@ -1,232 +1,244 @@
#!/usr/bin/python2.4
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth.
"""
__author__ = '[email protected] (Joe Gregorio)'
import copy
import httplib2
import oauth2 as oauth
import urllib
import logging
try:
from urlparse import parse_qs, parse_qsl
except ImportError:
from cgi import parse_qs, parse_qsl
-class MissingParameter(Exception):
+class Error(Exception):
+ """Base error for this module."""
+ pass
+
+
+class RequestError(Error):
+ """Error occurred during request."""
+ pass
+
+
+class MissingParameter(Error):
pass
def _abstract():
raise NotImplementedError('You need to override this function')
def _oauth_uri(name, discovery, params):
"""Look up the OAuth UR from the discovery
document and add query parameters based on
params.
name - The name of the OAuth URI to lookup, one
of 'request', 'access', or 'authorize'.
discovery - Portion of discovery document the describes
the OAuth endpoints.
params - Dictionary that is used to form the query parameters
for the specified URI.
"""
if name not in ['request', 'access', 'authorize']:
raise KeyError(name)
keys = discovery[name]['parameters'].keys()
query = {}
for key in keys:
if key in params:
query[key] = params[key]
return discovery[name]['url'] + '?' + urllib.urlencode(query)
class Credentials(object):
"""Base class for all Credentials objects.
Subclasses must define an authorize() method
that applies the credentials to an HTTP transport.
"""
def authorize(self, http):
"""Take an httplib2.Http instance (or equivalent) and
authorizes it for the set of credentials, usually by
replacing http.request() with a method that adds in
the appropriate headers and then delegates to the original
Http.request() method.
"""
_abstract()
class OAuthCredentials(Credentials):
"""Credentials object for OAuth 1.0a
"""
def __init__(self, consumer, token, user_agent):
"""
consumer - An instance of oauth.Consumer.
token - An instance of oauth.Token constructed with
the access token and secret.
user_agent - The HTTP User-Agent to provide for this application.
"""
self.consumer = consumer
self.token = token
self.user_agent = user_agent
def authorize(self, http):
"""
Args:
http - An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can't create a new OAuth
subclass of httplib2.Authenication because
it never gets passed the absolute URI, which is
needed for signing. So instead we have to overload
'request' with a closure that adds in the
Authorization header and then calls the original version
of 'request()'.
"""
request_orig = http.request
signer = oauth.SignatureMethod_HMAC_SHA1()
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the appropriate
Authorization header."""
req = oauth.Request.from_consumer_and_token(
self.consumer, self.token, http_method=method, http_url=uri)
req.sign_request(signer, self.consumer, self.token)
if headers == None:
headers = {}
headers.update(req.to_header())
- if 'user-agent' not in headers:
- headers['user-agent'] = self.user_agent
+ if 'user-agent' in headers:
+ headers['user-agent'] = self.user_agent + ' ' + headers['user-agent']
+ else:
+ headers['user-agent'] = self.user_agent
return request_orig(uri, method, body, headers,
redirections, connection_type)
http.request = new_request
return http
class FlowThreeLegged(object):
"""Does the Three Legged Dance for OAuth 1.0a.
"""
def __init__(self, discovery, consumer_key, consumer_secret, user_agent,
**kwargs):
"""
discovery - Section of the API discovery document that describes
the OAuth endpoints.
consumer_key - OAuth consumer key
consumer_secret - OAuth consumer secret
user_agent - The HTTP User-Agent that identifies the application.
**kwargs - The keyword arguments are all optional and required
parameters for the OAuth calls.
"""
self.discovery = discovery
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.user_agent = user_agent
self.params = kwargs
self.request_token = {}
required = {}
for uriinfo in discovery.itervalues():
for name, value in uriinfo['parameters'].iteritems():
if value['required'] and not name.startswith('oauth_'):
required[name] = 1
for key in required.iterkeys():
if key not in self.params:
raise MissingParameter('Required parameter %s not supplied' % key)
def step1_get_authorize_url(self, oauth_callback='oob'):
"""Returns a URI to redirect to the provider.
oauth_callback - Either the string 'oob' for a non-web-based application,
or a URI that handles the callback from the authorization
server.
If oauth_callback is 'oob' then pass in the
generated verification code to step2_exchange,
otherwise pass in the query parameters received
at the callback uri to step2_exchange.
"""
consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
client = oauth.Client(consumer)
headers = {
'user-agent': self.user_agent,
'content-type': 'application/x-www-form-urlencoded'
}
body = urllib.urlencode({'oauth_callback': oauth_callback})
uri = _oauth_uri('request', self.discovery, self.params)
resp, content = client.request(uri, 'POST', headers=headers,
body=body)
if resp['status'] != '200':
logging.error('Failed to retrieve temporary authorization: %s' % content)
- raise Exception('Invalid response %s.' % resp['status'])
+ raise RequestError('Invalid response %s.' % resp['status'])
self.request_token = dict(parse_qsl(content))
auth_params = copy.copy(self.params)
auth_params['oauth_token'] = self.request_token['oauth_token']
return _oauth_uri('authorize', self.discovery, auth_params)
def step2_exchange(self, verifier):
"""Exhanges an authorized request token
for OAuthCredentials.
verifier - either the verifier token, or a dictionary
of the query parameters to the callback, which contains
the oauth_verifier.
"""
if not (isinstance(verifier, str) or isinstance(verifier, unicode)):
verifier = verifier['oauth_verifier']
token = oauth.Token(
self.request_token['oauth_token'],
self.request_token['oauth_token_secret'])
token.set_verifier(verifier)
consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
client = oauth.Client(consumer, token)
headers = {
'user-agent': self.user_agent,
'content-type': 'application/x-www-form-urlencoded'
}
uri = _oauth_uri('access', self.discovery, self.params)
resp, content = client.request(uri, 'POST', headers=headers)
if resp['status'] != '200':
logging.error('Failed to retrieve access token: %s' % content)
- raise Exception('Invalid response %s.' % resp['status'])
+ raise RequestError('Invalid response %s.' % resp['status'])
oauth_params = dict(parse_qsl(content))
token = oauth.Token(
oauth_params['oauth_token'],
oauth_params['oauth_token_secret'])
return OAuthCredentials(consumer, token, self.user_agent)
diff --git a/xmpp.py b/xmpp.py
index cdb8625..ca3a0f0 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,401 +1,405 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*)\s*(.*)", string)
if results:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*)\s*", string)
if results:
command = results.group(1)
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if not self.__scm_command:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
ALTERNATIVE_HELP_CMD = '?'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
'%s Prints out this message' % ALTERNATIVE_HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper(), hub_subscriber=pshb.HubSubscriber()):
self.buzz_wrapper = buzz_wrapper
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
logging.info('Command was: %s' % message.command)
command = self._get_canonical_command(message)
if command and command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % command
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
else:
logging.info('No handler available for command: %s' % command)
self.unhandled_command(message)
def _get_canonical_command(self, message):
command = message.command.lower()
# The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards
# compatibility for early adopters and people who are used to IRC syntax.
if command.startswith('/'):
command = command[1:]
# Handle aliases for commands
if command == XmppHandler.ALTERNATIVE_HELP_CMD:
command = XmppHandler.HELP_CMD
return command
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
+ logging.debug('%s has not given access to their Google Buzz account but is attempting to post anyway' % sender)
elif not user_token.access_token_string:
+ logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token: %s' % (sender, str(user_token)))
+
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
+ logging.debug('%s did not complete the process for giving access to their Google Buzz account. Deleting their incomplete token.' % sender)
else:
url = self.buzz_wrapper.post(sender, message.arg)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
dfcdff7541066d4a546eeeea9c2569aee8b74054
|
Added improved logging to work out why OAuth is not working for a user.
|
diff --git a/oauth_handlers.py b/oauth_handlers.py
index 3edd3b4..2a2e075 100644
--- a/oauth_handlers.py
+++ b/oauth_handlers.py
@@ -1,133 +1,138 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import users
from google.appengine.api import xmpp
import buzz_gae_client
import logging
import os
import settings
class UserToken(db.Model):
# The user_id is the key_name so we don't have to make it an explicit property
request_token_string = db.StringProperty()
access_token_string = db.StringProperty()
email_address = db.StringProperty()
def get_request_token(self):
"Returns request token as a dictionary of tokens including oauth_token, oauth_token_secret and oauth_callback_confirmed."
return eval(self.request_token_string)
def set_access_token(self, access_token):
access_token_string = repr(access_token)
self.access_token_string = access_token_string
def get_access_token(self):
"Returns access token as a dictionary of tokens including consumer_key, consumer_secret, oauth_token and oauth_token_secret"
return eval(self.access_token_string)
@staticmethod
def create_user_token(request_token):
user = users.get_current_user()
user_id = user.user_id()
request_token_string = repr(request_token)
# TODO(ade) Support users who sign in to AppEngine with a federated identity aka OpenId
email = user.email()
logging.info('Creating user token: key_name: %s request_token_string: %s email_address: %s' % (
user_id, request_token_string, email))
return UserToken(key_name=user_id, request_token_string=request_token_string, access_token_string='',
email_address=email)
@staticmethod
def get_current_user_token():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
return user_token
@staticmethod
def access_token_exists():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
logging.info('user_token: %s' % user_token)
return user_token and user_token.access_token_string
@staticmethod
def find_by_email_address(email_address):
user_tokens = UserToken.gql('WHERE email_address = :1', email_address).fetch(1)
if user_tokens:
return user_tokens[0] # The result of the query is a list
else:
return None
class DanceStartingHandler(webapp.RequestHandler):
@login_required
def get(self):
- logging.info("Request body %s" % self.request.body)
+ logging.info('Request body %s' % self.request.body)
+ user = users.get_current_user()
+ logging.debug('Started OAuth dance for: %s' % user.email())
+
template_values = {"jabber_id": ("%[email protected]" % settings.APP_NAME)}
if UserToken.access_token_exists():
template_values['access_token_exists'] = 'true'
else:
# Generate the request token
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
request_token = client.get_request_token(settings.CALLBACK_URL)
# Create the request token and associate it with the current user
user_token = UserToken.create_user_token(request_token)
UserToken.put(user_token)
authorisation_url = client.generate_authorisation_url(request_token)
logging.info('Authorisation URL is: %s' % authorisation_url)
template_values['destination'] = authorisation_url
path = os.path.join(os.path.dirname(__file__), 'start_dance.html')
self.response.out.write(template.render(path, template_values))
class TokenDeletionHandler(webapp.RequestHandler):
def post(self):
user_token = UserToken.get_current_user_token()
UserToken.delete(user_token)
self.redirect(settings.FRONT_PAGE_HANDLER_URL)
class DanceFinishingHandler(webapp.RequestHandler):
def get(self):
logging.info("Request body %s" % self.request.body)
- oauth_verifier = self.request.get('oauth_verifier')
+ user = users.get_current_user()
+ logging.debug('Finished OAuth dance for: %s' % user.email())
+ oauth_verifier = self.request.get('oauth_verifier')
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
user_token = UserToken.get_current_user_token()
request_token = user_token.get_request_token()
access_token = client.upgrade_to_access_token(request_token, oauth_verifier)
logging.info('SUCCESS: Received access token.')
user_token.set_access_token(access_token)
UserToken.put(user_token)
logging.debug('Access token was: %s' % user_token.access_token_string)
# Send an XMPP invitation
logging.info('Sending invite to %s' % user_token.email_address)
xmpp.send_invite(user_token.email_address)
msg = 'Welcome to the BuzzChatBot: %s' % settings.APP_URL
xmpp.send_message(user_token.email_address, msg)
self.redirect(settings.PROFILE_HANDLER_URL)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
53e11093658b686e0938f5b359df1514f071ec2b
|
Removed TODO since we now accept commands irrespective of their case
|
diff --git a/xmpp.py b/xmpp.py
index f73eaf4..cdb8625 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,402 +1,401 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*)\s*(.*)", string)
if results:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*)\s*", string)
if results:
command = results.group(1)
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if not self.__scm_command:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
ALTERNATIVE_HELP_CMD = '?'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
'%s Prints out this message' % ALTERNATIVE_HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper(), hub_subscriber=pshb.HubSubscriber()):
self.buzz_wrapper = buzz_wrapper
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
logging.info('Command was: %s' % message.command)
command = self._get_canonical_command(message)
if command and command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % command
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
else:
logging.info('No handler available for command: %s' % command)
self.unhandled_command(message)
def _get_canonical_command(self, message):
- # TODO(ade) commands should be case insensitive
command = message.command.lower()
# The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards
# compatibility for early adopters and people who are used to IRC syntax.
if command.startswith('/'):
command = command[1:]
# Handle aliases for commands
if command == XmppHandler.ALTERNATIVE_HELP_CMD:
command = XmppHandler.HELP_CMD
return command
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
else:
url = self.buzz_wrapper.post(sender, message.arg)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
c4dcf1bced3ef25826de730efaf69e9f26f78aee
|
Made all commands case-insensitive
|
diff --git a/functional_tests.py b/functional_tests.py
index 2f91511..f687a6a 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,335 +1,359 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from stubs import StubMessage, StubSimpleBuzzWrapper
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import oauth_handlers
import settings
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def __init__(self, methodName='runTest'):
BuzzChatBotFunctionalTestCase.__init__(self, methodName)
self.stub_buzz_wrapper = StubSimpleBuzzWrapper()
self.stub_hub_subscriber = StubHubSubscriber()
self.handler = XmppHandler(buzz_wrapper=self.stub_buzz_wrapper, hub_subscriber=self.stub_hub_subscriber)
def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
arg = 'Some day my prints will come'
message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg))
# We call the method directly here because we actually care about the object that is returned
subscription = self.handler.track_command(message=message)
self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id()))
def test_invalid_symbol_command_shows_correct_error(self):
command = '~'
message = StubMessage(body=command)
self.handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_unhandled_command_shows_correct_error(self):
command = 'wibble'
message = StubMessage(body=command)
self.handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
self.handler.message_received(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
self.handler.message_received(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
self.handler.message_received(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
self.handler.message_received(message=message)
expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
self.handler.message_received(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'some message'
self.assertEquals(expected_item, self.stub_buzz_wrapper.message)
def test_slash_post_command_strips_command_from_posted_message(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'some message'
self.assertEquals(expected_item, self.stub_buzz_wrapper.message)
def test_slash_post_gets_treated_as_post_command(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
+ def test_uppercase_post_gets_treated_as_post_command(self):
+ sender = '[email protected]'
+ user_token = oauth_handlers.UserToken(email_address=sender)
+ user_token.access_token_string = 'some thing that looks like an access token from a distance'
+ user_token.put()
+ message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD.upper())
+
+ self.handler.message_received(message=message)
+
+ expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
+ self.assertEquals(expected_item, message.message_to_send)
+
+ def test_slash_uppercase_post_gets_treated_as_post_command(self):
+ sender = '[email protected]'
+ user_token = oauth_handlers.UserToken(email_address=sender)
+ user_token.access_token_string = 'some thing that looks like an access token from a distance'
+ user_token.put()
+ message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD.upper())
+
+ self.handler.message_received(message=message)
+
+ expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
+ self.assertEquals(expected_item, message.message_to_send)
+
def test_help_command_lists_available_commands(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
self.handler.message_received(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in XmppHandler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
def test_alternative_help_command_lists_available_commands(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ALTERNATIVE_HELP_CMD)
self.handler.message_received(message=message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % XmppHandler.ALTERNATIVE_HELP_CMD not in message.message_to_send)
self.assertTrue(len(message.message_to_send) > 0)
for command in XmppHandler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
class XmppHandlerHttpTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_help_command_can_be_triggered_via_http(self):
# Help command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'help'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_list_command_can_be_triggered_via_http(self):
# List command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'list'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_invalid_http_request_triggers_error(self):
response = self.post('/_ah/xmpp/message/chat/', data={}, expect_errors=True)
self.assertEquals('400 Bad Request', response.status)
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index 94f611c..f73eaf4 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,403 +1,402 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*)\s*(.*)", string)
if results:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*)\s*", string)
if results:
command = results.group(1)
- logging.debug('Groups matched: %s' % str(results))
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if not self.__scm_command:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
ALTERNATIVE_HELP_CMD = '?'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
'%s Prints out this message' % ALTERNATIVE_HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper(), hub_subscriber=pshb.HubSubscriber()):
self.buzz_wrapper = buzz_wrapper
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
logging.info('Command was: %s' % message.command)
command = self._get_canonical_command(message)
if command and command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % command
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
else:
logging.info('No handler available for command: %s' % command)
self.unhandled_command(message)
def _get_canonical_command(self, message):
# TODO(ade) commands should be case insensitive
+ command = message.command.lower()
# The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards
# compatibility for early adopters and people who are used to IRC syntax.
- command = message.command
if command.startswith('/'):
command = command[1:]
# Handle aliases for commands
if command == XmppHandler.ALTERNATIVE_HELP_CMD:
command = XmppHandler.HELP_CMD
return command
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
else:
url = self.buzz_wrapper.post(sender, message.arg)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
c360104f5c43d4168991ee8d842c16be6e32953f
|
Extracted out all stubs into their own module
|
diff --git a/BUGS b/BUGS
index 071d896..919f3bd 100644
--- a/BUGS
+++ b/BUGS
@@ -1,3 +1 @@
According to Brian Rose: posts that contain @mentions cause an error.
-
-
diff --git a/functional_tests.py b/functional_tests.py
index 5c9084b..2f91511 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,353 +1,335 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
+from stubs import StubMessage, StubSimpleBuzzWrapper
from tracker_tests import StubHubSubscriber
-from xmpp import Tracker, XmppHandler, SlashlessCommandMessage
+from xmpp import Tracker, XmppHandler
import oauth_handlers
import settings
-import simple_buzz_wrapper
-
-class StubMessage(object):
- def __init__(self, sender='[email protected]', body=''):
- self.sender = sender
- self.body = body
- self.command, self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
- self.message_to_send = None
-
- def reply(self, message_to_send, raw_xml=False):
- self.message_to_send = message_to_send
-
-class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
- def __init__(self):
- self.url = 'some fake url'
-
- def post(self, sender, message_body):
- self.message = message_body
- return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def __init__(self, methodName='runTest'):
BuzzChatBotFunctionalTestCase.__init__(self, methodName)
self.stub_buzz_wrapper = StubSimpleBuzzWrapper()
self.stub_hub_subscriber = StubHubSubscriber()
self.handler = XmppHandler(buzz_wrapper=self.stub_buzz_wrapper, hub_subscriber=self.stub_hub_subscriber)
def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
arg = 'Some day my prints will come'
message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg))
# We call the method directly here because we actually care about the object that is returned
subscription = self.handler.track_command(message=message)
self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id()))
def test_invalid_symbol_command_shows_correct_error(self):
command = '~'
message = StubMessage(body=command)
self.handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_unhandled_command_shows_correct_error(self):
command = 'wibble'
message = StubMessage(body=command)
self.handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
self.handler.message_received(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
self.handler.message_received(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
self.handler.message_received(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
self.handler.message_received(message=message)
expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
self.handler.message_received(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'some message'
self.assertEquals(expected_item, self.stub_buzz_wrapper.message)
def test_slash_post_command_strips_command_from_posted_message(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'some message'
self.assertEquals(expected_item, self.stub_buzz_wrapper.message)
def test_slash_post_gets_treated_as_post_command(self):
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
self.handler.message_received(message=message)
expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_help_command_lists_available_commands(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
self.handler.message_received(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in XmppHandler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
def test_alternative_help_command_lists_available_commands(self):
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ALTERNATIVE_HELP_CMD)
self.handler.message_received(message=message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % XmppHandler.ALTERNATIVE_HELP_CMD not in message.message_to_send)
self.assertTrue(len(message.message_to_send) > 0)
for command in XmppHandler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
class XmppHandlerHttpTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_help_command_can_be_triggered_via_http(self):
# Help command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'help'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_list_command_can_be_triggered_via_http(self):
# List command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'list'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_invalid_http_request_triggers_error(self):
response = self.post('/_ah/xmpp/message/chat/', data={}, expect_errors=True)
self.assertEquals('400 Bad Request', response.status)
\ No newline at end of file
diff --git a/stubs.py b/stubs.py
new file mode 100644
index 0000000..ad53726
--- /dev/null
+++ b/stubs.py
@@ -0,0 +1,42 @@
+# Copyright (C) 2010 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from xmpp import SlashlessCommandMessage
+
+import pshb
+import simple_buzz_wrapper
+
+class StubHubSubscriber(pshb.HubSubscriber):
+ def subscribe(self, url, hub, callback_url):
+ self.callback_url = callback_url
+
+ def unsubscribe(self, url, hub, callback_url):
+ self.callback_url = callback_url
+
+class StubMessage(object):
+ def __init__(self, sender='[email protected]', body=''):
+ self.sender = sender
+ self.body = body
+ self.command, self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
+ self.message_to_send = None
+
+ def reply(self, message_to_send, raw_xml=False):
+ self.message_to_send = message_to_send
+
+class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
+ def __init__(self):
+ self.url = 'some fake url'
+
+ def post(self, sender, message_body):
+ self.message = message_body
+ return self.url
\ No newline at end of file
diff --git a/tracker_tests.py b/tracker_tests.py
index 3964f26..e8e0186 100644
--- a/tracker_tests.py
+++ b/tracker_tests.py
@@ -1,162 +1,156 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-import unittest
-from xmpp import Subscription, Tracker, XmppHandler
-import pshb
+from stubs import StubHubSubscriber
+from xmpp import Subscription, Tracker
import settings
+import unittest
-class StubHubSubscriber(pshb.HubSubscriber):
- def subscribe(self, url, hub, callback_url):
- self.callback_url = callback_url
-
- def unsubscribe(self, url, hub, callback_url):
- self.callback_url = callback_url
class TrackerTest(unittest.TestCase):
def test_is_blank_works_on_blank_strings(self):
self.assertTrue(Tracker.is_blank(None))
self.assertTrue(Tracker.is_blank(" "))
self.assertTrue(Tracker.is_blank(" ")) # has a tab in it
self.assertTrue(Tracker.is_blank(""))
def test_is_blank_works_on_nonblank_strings(self):
self.assertFalse(Tracker.is_blank(" a"))
self.assertFalse(Tracker.is_blank("adf "))
self.assertFalse(Tracker.is_blank(" adfas "))
self.assertFalse(Tracker.is_blank("daf-sa"))
def test_tracker_rejects_empty_search_term(self):
sender = '[email protected]'
term = ''
tracker = Tracker(hub_subscriber=StubHubSubscriber())
self.assertEquals(None, tracker.track(sender, term))
def test_tracker_extracts_integer_id_given_integer(self):
self.assertEquals(7, Tracker.extract_number(7))
def test_tracker_extracts_integer_id_given_string(self):
self.assertEquals(7, Tracker.extract_number('7'))
def test_tracker_returns_none_given_invalid_integer(self):
self.assertEquals(None, Tracker.extract_number('jaiku'))
self.assertEquals(None, Tracker.extract_number(None))
def test_tracker_rejects_padded_empty_string(self):
sender = '[email protected]'
tracker = Tracker(hub_subscriber=StubHubSubscriber())
self.assertEquals(None, tracker.track(sender, ' '))
def test_tracker_accepts_valid_string(self):
sender = '[email protected]'
search_term='somestring'
tracker = Tracker(hub_subscriber=StubHubSubscriber())
expected_callback_url = '%s/posts/%s/%s' % (settings.APP_URL, sender, search_term)
expected_subscription = Subscription(url='https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, search_term=search_term, callback_url=expected_callback_url)
actual_subscription = tracker.track(sender, search_term)
self.assertEquals(expected_subscription.url, actual_subscription.url)
self.assertEquals(expected_subscription.search_term, actual_subscription.search_term)
def test_tracker_builds_correct_pshb_url(self):
search_term = 'somestring'
tracker = Tracker(hub_subscriber=StubHubSubscriber())
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, tracker._build_subscription_url(search_term))
def test_tracker_url_encodes_search_term(self):
search_term = 'some string'
tracker = Tracker(hub_subscriber=StubHubSubscriber())
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=' + 'some%20string', tracker._build_subscription_url(search_term))
def _delete_all_subscriptions(self):
for subscription in Subscription.all().fetch(100):
subscription.delete()
def test_tracker_saves_subscription(self):
self._delete_all_subscriptions()
self.assertEquals(0, len(Subscription.all().fetch(100)))
sender = '[email protected]'
search_term='somestring'
tracker = Tracker(hub_subscriber=StubHubSubscriber())
subscription = tracker.track(sender, search_term)
self.assertEquals(1, len(Subscription.all().fetch(100)))
self.assertEquals(subscription, Subscription.all().fetch(1)[0])
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query(self):
sender = '[email protected]'
search_term='somestring'
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, search_term)
expected_callback_url = '%s/posts?id=%s' % (settings.APP_URL, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_urlencoded_callback_url(self):
sender = '[email protected]'
search_term='some string'
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, search_term)
expected_callback_url = '%s/posts?id=%s' % (settings.APP_URL, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query_without_xmpp_client_identifier(self):
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, search_term)
expected_callback_url = '%s/posts?id=%s' % (settings.APP_URL, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_rejects_invalid_id_for_untracking(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.untrack(sender, '1')
self.assertEquals(None, subscription)
def test_tracker_untracks_valid_id(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
track_subscription = tracker.track(sender, search_term)
untrack_subscription = tracker.untrack(sender, track_subscription.id())
self.assertEquals(track_subscription, untrack_subscription)
self.assertFalse(Subscription.exists(track_subscription.id()))
self.assertEquals('%s/posts?id=%s' % (settings.APP_URL, track_subscription.id()), hub_subscriber.callback_url)
|
adewale/Buzz-Chat-Bot
|
3e190d1bcd9ae7e70261204691f1eb39e64d7a2b
|
Bot now works on Empath IM client since you can use slashless commands
|
diff --git a/BUGS b/BUGS
index e49705e..071d896 100644
--- a/BUGS
+++ b/BUGS
@@ -1,4 +1,3 @@
According to Brian Rose: posts that contain @mentions cause an error.
-According to Robert C Sanchez the bot doesn't work with Empathy on Ubuntu. I suspect this is to do with either the formatting of the messages or the structure of the JID. Although Michael Bernstein has a theory that the /commands are being intercepted by the chat client. However commands like /post and /track aren't working for him so there may be something else wrong.
|
adewale/Buzz-Chat-Bot
|
44f09aebb08bfbaf1666f65d8d2df20d022e89a4
|
Made all tests reuse the same statelesss instance of XmppHandler. This simplifies the tests, speeds up the tests and should ensure that any tests that won't work offline will stick out because they won't be using the existing handler which uses stubs.
|
diff --git a/functional_tests.py b/functional_tests.py
index 889a95c..5c9084b 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,375 +1,353 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler, SlashlessCommandMessage
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
self.command, self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
self.message_to_send = None
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
+
def post(self, sender, message_body):
self.message = message_body
return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
+ def __init__(self, methodName='runTest'):
+ BuzzChatBotFunctionalTestCase.__init__(self, methodName)
+
+ self.stub_buzz_wrapper = StubSimpleBuzzWrapper()
+ self.stub_hub_subscriber = StubHubSubscriber()
+ self.handler = XmppHandler(buzz_wrapper=self.stub_buzz_wrapper, hub_subscriber=self.stub_hub_subscriber)
+
def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
arg = 'Some day my prints will come'
- message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg) )
- hub_subscriber = StubHubSubscriber()
- handler = XmppHandler(hub_subscriber=hub_subscriber)
+ message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg))
# We call the method directly here because we actually care about the object that is returned
- subscription = handler.track_command(message=message)
+ subscription = self.handler.track_command(message=message)
self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id()))
def test_invalid_symbol_command_shows_correct_error(self):
command = '~'
message = StubMessage(body=command)
- handler = XmppHandler()
- handler.message_received(message)
+ self.handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_unhandled_command_shows_correct_error(self):
command = 'wibble'
message = StubMessage(body=command)
- handler = XmppHandler()
- handler.message_received(message)
+ self.handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
- handler = XmppHandler()
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
- handler = XmppHandler()
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
- handler = XmppHandler()
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
- handler = XmppHandler()
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
- hub_subscriber = StubHubSubscriber()
- handler = XmppHandler(hub_subscriber=hub_subscriber)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
- handler = XmppHandler()
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
- handler = XmppHandler()
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
- handler = XmppHandler()
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
- handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
- handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
- handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
- handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
- handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
- stub = StubSimpleBuzzWrapper()
- handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
- stub = StubSimpleBuzzWrapper()
- handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
- expected_item = 'Posted: %s' % stub.url
+ expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
- stub = StubSimpleBuzzWrapper()
- handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
expected_item = 'some message'
- self.assertEquals(expected_item, stub.message)
+ self.assertEquals(expected_item, self.stub_buzz_wrapper.message)
def test_slash_post_command_strips_command_from_posted_message(self):
- stub = StubSimpleBuzzWrapper()
- handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
expected_item = 'some message'
- self.assertEquals(expected_item, stub.message)
+ self.assertEquals(expected_item, self.stub_buzz_wrapper.message)
def test_slash_post_gets_treated_as_post_command(self):
- stub = StubSimpleBuzzWrapper()
- handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
- expected_item = 'Posted: %s' % stub.url
+ expected_item = 'Posted: %s' % self.stub_buzz_wrapper.url
self.assertEquals(expected_item, message.message_to_send)
def test_help_command_lists_available_commands(self):
- handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
self.assertTrue(len(message.message_to_send) > 0)
- for command in handler.COMMAND_HELP_MSG_LIST:
+ for command in XmppHandler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
def test_alternative_help_command_lists_available_commands(self):
- handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ALTERNATIVE_HELP_CMD)
- handler.message_received(message=message)
+ self.handler.message_received(message=message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % XmppHandler.ALTERNATIVE_HELP_CMD not in message.message_to_send)
self.assertTrue(len(message.message_to_send) > 0)
- for command in handler.COMMAND_HELP_MSG_LIST:
+ for command in XmppHandler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
class XmppHandlerHttpTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_help_command_can_be_triggered_via_http(self):
# Help command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'help'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_list_command_can_be_triggered_via_http(self):
# List command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'list'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_invalid_http_request_triggers_error(self):
response = self.post('/_ah/xmpp/message/chat/', data={}, expect_errors=True)
self.assertEquals('400 Bad Request', response.status)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
adfcb33fc6184a3b2280690d2f8c0723d08aa900
|
Made untrack test work offline.
|
diff --git a/functional_tests.py b/functional_tests.py
index a284084..889a95c 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,374 +1,375 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler, SlashlessCommandMessage
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
self.command, self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
self.message_to_send = None
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
arg = 'Some day my prints will come'
message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg) )
hub_subscriber = StubHubSubscriber()
handler = XmppHandler(hub_subscriber=hub_subscriber)
# We call the method directly here because we actually care about the object that is returned
subscription = handler.track_command(message=message)
self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id()))
def test_invalid_symbol_command_shows_correct_error(self):
command = '~'
message = StubMessage(body=command)
handler = XmppHandler()
handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_unhandled_command_shows_correct_error(self):
command = 'wibble'
message = StubMessage(body=command)
handler = XmppHandler()
handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
- handler = XmppHandler()
+ hub_subscriber = StubHubSubscriber()
+ handler = XmppHandler(hub_subscriber=hub_subscriber)
handler.message_received(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.message_received(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.message_received(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.message_received(message=message)
expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.message_received(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.message_received(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.message_received(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.message_received(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.message_received(message=message)
expected_item = 'some message'
self.assertEquals(expected_item, stub.message)
def test_slash_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
handler.message_received(message=message)
expected_item = 'some message'
self.assertEquals(expected_item, stub.message)
def test_slash_post_gets_treated_as_post_command(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
handler.message_received(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
handler.message_received(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
def test_alternative_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ALTERNATIVE_HELP_CMD)
handler.message_received(message=message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % XmppHandler.ALTERNATIVE_HELP_CMD not in message.message_to_send)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
class XmppHandlerHttpTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_help_command_can_be_triggered_via_http(self):
# Help command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'help'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_list_command_can_be_triggered_via_http(self):
# List command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'list'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_invalid_http_request_triggers_error(self):
response = self.post('/_ah/xmpp/message/chat/', data={}, expect_errors=True)
self.assertEquals('400 Bad Request', response.status)
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index 3d59e64..94f611c 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,401 +1,403 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*)\s*(.*)", string)
if results:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*)\s*", string)
if results:
command = results.group(1)
logging.debug('Groups matched: %s' % str(results))
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if not self.__scm_command:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
ALTERNATIVE_HELP_CMD = '?'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
'%s Prints out this message' % ALTERNATIVE_HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper(), hub_subscriber=pshb.HubSubscriber()):
self.buzz_wrapper = buzz_wrapper
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
logging.info('Command was: %s' % message.command)
command = self._get_canonical_command(message)
if command and command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % command
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
else:
logging.info('No handler available for command: %s' % command)
self.unhandled_command(message)
def _get_canonical_command(self, message):
+ # TODO(ade) commands should be case insensitive
+
# The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards
# compatibility for early adopters and people who are used to IRC syntax.
command = message.command
if command.startswith('/'):
command = command[1:]
# Handle aliases for commands
if command == XmppHandler.ALTERNATIVE_HELP_CMD:
command = XmppHandler.HELP_CMD
return command
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
else:
url = self.buzz_wrapper.post(sender, message.arg)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
4e86170e01f82912d482f0693a34e4e147605e15
|
Fixed bug where /post would leave a dangling 't' because we only trimmed the first 4 characters from the message body.
|
diff --git a/app.yaml b/app.yaml
index 522fb2a..e30bf45 100644
--- a/app.yaml
+++ b/app.yaml
@@ -1,15 +1,15 @@
-application: favedby
+application: buzzchatbot
version: 1
runtime: python
api_version: 1
handlers:
- url: /css
static_dir: css
- url: /images
static_dir: images
- url: /.*
script: main.py
inbound_services:
- xmpp_message
\ No newline at end of file
diff --git a/functional_tests.py b/functional_tests.py
index 2f145a8..a284084 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,360 +1,374 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler, SlashlessCommandMessage
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
- self.command,self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
+ self.command, self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
self.message_to_send = None
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
arg = 'Some day my prints will come'
message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg) )
hub_subscriber = StubHubSubscriber()
handler = XmppHandler(hub_subscriber=hub_subscriber)
# We call the method directly here because we actually care about the object that is returned
subscription = handler.track_command(message=message)
self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id()))
def test_invalid_symbol_command_shows_correct_error(self):
command = '~'
message = StubMessage(body=command)
handler = XmppHandler()
handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_unhandled_command_shows_correct_error(self):
command = 'wibble'
message = StubMessage(body=command)
handler = XmppHandler()
handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.message_received(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.message_received(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.message_received(message=message)
expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.message_received(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.message_received(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.message_received(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.message_received(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.message_received(message=message)
- expected_item = ' some message'
+ expected_item = 'some message'
+ self.assertEquals(expected_item, stub.message)
+
+ def test_slash_post_command_strips_command_from_posted_message(self):
+ stub = StubSimpleBuzzWrapper()
+ handler = XmppHandler(buzz_wrapper=stub)
+ sender = '[email protected]'
+ user_token = oauth_handlers.UserToken(email_address=sender)
+ user_token.access_token_string = 'some thing that looks like an access token from a distance'
+ user_token.put()
+ message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
+
+ handler.message_received(message=message)
+
+ expected_item = 'some message'
self.assertEquals(expected_item, stub.message)
def test_slash_post_gets_treated_as_post_command(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
handler.message_received(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
handler.message_received(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
def test_alternative_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ALTERNATIVE_HELP_CMD)
handler.message_received(message=message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % XmppHandler.ALTERNATIVE_HELP_CMD not in message.message_to_send)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
class XmppHandlerHttpTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_help_command_can_be_triggered_via_http(self):
# Help command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'help'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_list_command_can_be_triggered_via_http(self):
# List command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'list'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_invalid_http_request_triggers_error(self):
response = self.post('/_ah/xmpp/message/chat/', data={}, expect_errors=True)
self.assertEquals('400 Bad Request', response.status)
\ No newline at end of file
diff --git a/settings.py b/settings.py
index 7c77037..1b14899 100644
--- a/settings.py
+++ b/settings.py
@@ -1,58 +1,58 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-APP_NAME = 'favedby'
+APP_NAME = 'buzzchatbot'
#Note that the APP_URL must _not_ end in a slash as it will be concatenated with other values
APP_URL = 'http://%s.appspot.com' % APP_NAME
ADMIN_PROFILE_URL = 'http://profiles.google.com/adewale'
#PSHB settings
# This is the token that will act as a shared secret to verify that this application is the one that registered the
# given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
# OAuth consumer key and secret - you should change these to 'anonymous' unless you really are buzzchatbot.appspot.com
# Alternatively you could go here: https://www.google.com/accounts/ManageDomains and register your instance so that
# you'll get your own consumer key and consumer secret
#CONSUMER_KEY = 'buzzchatbot.appspot.com'
#CONSUMER_SECRET = 'tcw1rCMgLVY556Y0Q4rW/RnK'
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
# OAuth callback URL
CALLBACK_URL = '%s/finish_dance' % APP_URL
PROFILE_HANDLER_URL = '/profile'
FRONT_PAGE_HANDLER_URL = '/'
# Installation specific config ends.
diff --git a/xmpp.py b/xmpp.py
index f17fbf5..3d59e64 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,402 +1,401 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*)\s*(.*)", string)
if results:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*)\s*", string)
if results:
command = results.group(1)
logging.debug('Groups matched: %s' % str(results))
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if not self.__scm_command:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
ALTERNATIVE_HELP_CMD = '?'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
'%s Prints out this message' % ALTERNATIVE_HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper(), hub_subscriber=pshb.HubSubscriber()):
self.buzz_wrapper = buzz_wrapper
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
logging.info('Command was: %s' % message.command)
command = self._get_canonical_command(message)
if command and command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % command
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
else:
logging.info('No handler available for command: %s' % command)
self.unhandled_command(message)
def _get_canonical_command(self, message):
# The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards
# compatibility for early adopters and people who are used to IRC syntax.
command = message.command
if command.startswith('/'):
command = command[1:]
# Handle aliases for commands
if command == XmppHandler.ALTERNATIVE_HELP_CMD:
command = XmppHandler.HELP_CMD
return command
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
else:
- message_body = message.body[len(XmppHandler.POST_CMD):]
- url = self.buzz_wrapper.post(sender, message_body)
+ url = self.buzz_wrapper.post(sender, message.arg)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
4e417053a830e2db3de93c887deabe8011649986
|
Changed tests so that they don't directly call the appropriate command method but always go through the dispatching logic. Commands can now be prefixed with an optional /. This allows users who preferred the old syntax to keep using it without affecting people who prefer the new syntax. Added test to verify that commands behave the same with and without a / prefix. Added ? as an alias for help or /help. There's now a method that converts commands to their canonical variant. Added more logging to make debugging these kinds of problems easier.
|
diff --git a/app.yaml b/app.yaml
index e30bf45..522fb2a 100644
--- a/app.yaml
+++ b/app.yaml
@@ -1,15 +1,15 @@
-application: buzzchatbot
+application: favedby
version: 1
runtime: python
api_version: 1
handlers:
- url: /css
static_dir: css
- url: /images
static_dir: images
- url: /.*
script: main.py
inbound_services:
- xmpp_message
\ No newline at end of file
diff --git a/functional_tests.py b/functional_tests.py
index 6d8e88b..2f145a8 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,333 +1,360 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler, SlashlessCommandMessage
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
self.command,self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
self.message_to_send = None
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
arg = 'Some day my prints will come'
message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg) )
hub_subscriber = StubHubSubscriber()
handler = XmppHandler(hub_subscriber=hub_subscriber)
+ # We call the method directly here because we actually care about the object that is returned
subscription = handler.track_command(message=message)
self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id()))
def test_invalid_symbol_command_shows_correct_error(self):
- command = '?'
+ command = '~'
message = StubMessage(body=command)
handler = XmppHandler()
handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_unhandled_command_shows_correct_error(self):
command = 'wibble'
message = StubMessage(body=command)
handler = XmppHandler()
handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
handler = XmppHandler()
- handler.track_command(message=message)
+ handler.message_received(message=message)
self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
- handler.untrack_command(message=message)
+ handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
- message = StubMessage()
+ message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
- handler.untrack_command(message=message)
+ handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
- handler.untrack_command(message=message)
+ handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
- handler.untrack_command(message=message)
+ handler.message_received(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
- handler.untrack_command(message=message)
+ handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
- handler.untrack_command(message=message)
+ handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
- handler.untrack_command(message=message)
+ handler.message_received(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
- handler.list_command(message=message)
+ handler.message_received(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
- handler.list_command(message=message)
+ handler.message_received(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
- handler.list_command(message=message)
+ handler.message_received(message=message)
expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
- handler.about_command(message=message)
+ handler.message_received(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
- handler.post_command(message=message)
+ handler.message_received(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
- handler.post_command(message=message)
+ handler.message_received(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
- handler.post_command(message=message)
+ handler.message_received(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
- handler.post_command(message=message)
+ handler.message_received(message=message)
expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
+ def test_slash_post_gets_treated_as_post_command(self):
+ stub = StubSimpleBuzzWrapper()
+ handler = XmppHandler(buzz_wrapper=stub)
+ sender = '[email protected]'
+ user_token = oauth_handlers.UserToken(email_address=sender)
+ user_token.access_token_string = 'some thing that looks like an access token from a distance'
+ user_token.put()
+ message = StubMessage(sender=sender, body='/%s some message' % XmppHandler.POST_CMD)
+
+ handler.message_received(message=message)
+
+ expected_item = 'Posted: %s' % stub.url
+ self.assertEquals(expected_item, message.message_to_send)
+
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
- handler.help_command(message=message)
+ handler.message_received(message=message)
+
+ self.assertTrue(len(message.message_to_send) > 0)
+ for command in handler.COMMAND_HELP_MSG_LIST:
+ self.assertTrue(command in message.message_to_send, message.message_to_send)
+
+ def test_alternative_help_command_lists_available_commands(self):
+ handler = XmppHandler()
+ sender = '[email protected]'
+ message = StubMessage(sender=sender, body='%s' % XmppHandler.ALTERNATIVE_HELP_CMD)
+
+ handler.message_received(message=message)
+ self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % XmppHandler.ALTERNATIVE_HELP_CMD not in message.message_to_send)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
class XmppHandlerHttpTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_help_command_can_be_triggered_via_http(self):
# Help command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'help'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_list_command_can_be_triggered_via_http(self):
# List command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'list'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_invalid_http_request_triggers_error(self):
response = self.post('/_ah/xmpp/message/chat/', data={}, expect_errors=True)
self.assertEquals('400 Bad Request', response.status)
\ No newline at end of file
diff --git a/settings.py b/settings.py
index 1b14899..7c77037 100644
--- a/settings.py
+++ b/settings.py
@@ -1,58 +1,58 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-APP_NAME = 'buzzchatbot'
+APP_NAME = 'favedby'
#Note that the APP_URL must _not_ end in a slash as it will be concatenated with other values
APP_URL = 'http://%s.appspot.com' % APP_NAME
ADMIN_PROFILE_URL = 'http://profiles.google.com/adewale'
#PSHB settings
# This is the token that will act as a shared secret to verify that this application is the one that registered the
# given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
# OAuth consumer key and secret - you should change these to 'anonymous' unless you really are buzzchatbot.appspot.com
# Alternatively you could go here: https://www.google.com/accounts/ManageDomains and register your instance so that
# you'll get your own consumer key and consumer secret
#CONSUMER_KEY = 'buzzchatbot.appspot.com'
#CONSUMER_SECRET = 'tcw1rCMgLVY556Y0Q4rW/RnK'
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
# OAuth callback URL
CALLBACK_URL = '%s/finish_dance' % APP_URL
PROFILE_HANDLER_URL = '/profile'
FRONT_PAGE_HANDLER_URL = '/'
# Installation specific config ends.
diff --git a/xmpp.py b/xmpp.py
index a3e64a1..f17fbf5 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,382 +1,402 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*)\s*(.*)", string)
if results:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*)\s*", string)
if results:
command = results.group(1)
logging.debug('Groups matched: %s' % str(results))
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if not self.__scm_command:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
+ ALTERNATIVE_HELP_CMD = '?'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
- PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
+ PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,ALTERNATIVE_HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
+ '%s Prints out this message' % ALTERNATIVE_HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper(), hub_subscriber=pshb.HubSubscriber()):
self.buzz_wrapper = buzz_wrapper
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
- using introspection. E.g. if the command is 'track' it will map to track_command.
+ using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
- if message.command and message.command in XmppHandler.PERMITTED_COMMANDS:
- handler_name = '%s_command' % (message.command,)
+ logging.info('Command was: %s' % message.command)
+ command = self._get_canonical_command(message)
+
+ if command and command in XmppHandler.PERMITTED_COMMANDS:
+ handler_name = '%s_command' % command
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
+ else:
+ logging.info('No handler available for command: %s' % command)
self.unhandled_command(message)
+ def _get_canonical_command(self, message):
+ # The old-style / prefixed commands are honoured as if they were slashless commands. This provides backwards
+ # compatibility for early adopters and people who are used to IRC syntax.
+ command = message.command
+ if command.startswith('/'):
+ command = command[1:]
+
+ # Handle aliases for commands
+ if command == XmppHandler.ALTERNATIVE_HELP_CMD:
+ command = XmppHandler.HELP_CMD
+ return command
+
+
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
else:
message_body = message.body[len(XmppHandler.POST_CMD):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
d9f9f85fea990d8d0dfdfa952c2a270b2baf148c
|
Added tests that check that spaces don't affect the commands. Changed regexp to ignore word boundaries. Still need to explicitly test the extraction of each command when paired with meaningful arguments
|
diff --git a/slashlesscommandmessage_tests.py b/slashlesscommandmessage_tests.py
index 127808e..453c39e 100644
--- a/slashlesscommandmessage_tests.py
+++ b/slashlesscommandmessage_tests.py
@@ -1,24 +1,36 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from xmpp import SlashlessCommandMessage, XmppHandler
class SlashlessCommandMessageTest(unittest.TestCase):
def test_extracts_symbol_as_command_given_symbol(self):
self.assertEquals('?', SlashlessCommandMessage.extract_command_and_arg_from_string('?')[0])
def test_extracts_all_commands(self):
for command in XmppHandler.PERMITTED_COMMANDS:
- self.assertEquals(command, SlashlessCommandMessage.extract_command_and_arg_from_string(command)[0])
\ No newline at end of file
+ self.assertEquals(command, SlashlessCommandMessage.extract_command_and_arg_from_string(command)[0])
+
+ def test_extracts_all_commands_prefixed_with_space(self):
+ for command in XmppHandler.PERMITTED_COMMANDS:
+ self.assertEquals(command, SlashlessCommandMessage.extract_command_and_arg_from_string(' ' + command)[0])
+
+ def test_extracts_all_commands_suffixed_with_space(self):
+ for command in XmppHandler.PERMITTED_COMMANDS:
+ self.assertEquals(command, SlashlessCommandMessage.extract_command_and_arg_from_string(command + ' ')[0])
+
+ def test_extracts_all_commands_surrounded_with_space(self):
+ for command in XmppHandler.PERMITTED_COMMANDS:
+ self.assertEquals(command, SlashlessCommandMessage.extract_command_and_arg_from_string(' ' + command + ' ')[0])
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index ecc7335..a3e64a1 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,382 +1,382 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
- results = re.search(r"\s*(\S*\b)\s*(.*)", string)
+ results = re.search(r"\s*(\S*)\s*(.*)", string)
if results:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*)\s*", string)
if results:
command = results.group(1)
logging.debug('Groups matched: %s' % str(results))
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if not self.__scm_command:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper(), hub_subscriber=pshb.HubSubscriber()):
self.buzz_wrapper = buzz_wrapper
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
if message.command and message.command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % (message.command,)
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
self.unhandled_command(message)
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
else:
message_body = message.body[len(XmppHandler.POST_CMD):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
de0a36f45af19b8ad955bd9a22e73e72d313e577
|
Added tests for SlashLessCommandMessage. Fixed user-reported bug with symbols by tweaking the regex to ignore the word boundaries. Tidied up a few places where unidiomatic comparisons to None were being made
|
diff --git a/app.yaml b/app.yaml
index 522fb2a..e30bf45 100644
--- a/app.yaml
+++ b/app.yaml
@@ -1,15 +1,15 @@
-application: favedby
+application: buzzchatbot
version: 1
runtime: python
api_version: 1
handlers:
- url: /css
static_dir: css
- url: /images
static_dir: images
- url: /.*
script: main.py
inbound_services:
- xmpp_message
\ No newline at end of file
diff --git a/functional_tests.py b/functional_tests.py
index 061f4b8..6d8e88b 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,324 +1,333 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler, SlashlessCommandMessage
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
self.command,self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
self.message_to_send = None
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
arg = 'Some day my prints will come'
message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg) )
hub_subscriber = StubHubSubscriber()
handler = XmppHandler(hub_subscriber=hub_subscriber)
subscription = handler.track_command(message=message)
self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id()))
+ def test_invalid_symbol_command_shows_correct_error(self):
+ command = '?'
+ message = StubMessage(body=command)
+ handler = XmppHandler()
+
+ handler.message_received(message)
+
+ self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
+
def test_unhandled_command_shows_correct_error(self):
command = 'wibble'
message = StubMessage(body=command)
handler = XmppHandler()
handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
handler = XmppHandler()
handler.track_command(message=message)
self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
handler.help_command(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
class XmppHandlerHttpTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_help_command_can_be_triggered_via_http(self):
# Help command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'help'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_list_command_can_be_triggered_via_http(self):
# List command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'list'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_invalid_http_request_triggers_error(self):
response = self.post('/_ah/xmpp/message/chat/', data={}, expect_errors=True)
self.assertEquals('400 Bad Request', response.status)
\ No newline at end of file
diff --git a/settings.py b/settings.py
index 7c77037..1b14899 100644
--- a/settings.py
+++ b/settings.py
@@ -1,58 +1,58 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-APP_NAME = 'favedby'
+APP_NAME = 'buzzchatbot'
#Note that the APP_URL must _not_ end in a slash as it will be concatenated with other values
APP_URL = 'http://%s.appspot.com' % APP_NAME
ADMIN_PROFILE_URL = 'http://profiles.google.com/adewale'
#PSHB settings
# This is the token that will act as a shared secret to verify that this application is the one that registered the
# given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
# OAuth consumer key and secret - you should change these to 'anonymous' unless you really are buzzchatbot.appspot.com
# Alternatively you could go here: https://www.google.com/accounts/ManageDomains and register your instance so that
# you'll get your own consumer key and consumer secret
#CONSUMER_KEY = 'buzzchatbot.appspot.com'
#CONSUMER_SECRET = 'tcw1rCMgLVY556Y0Q4rW/RnK'
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
# OAuth callback URL
CALLBACK_URL = '%s/finish_dance' % APP_URL
PROFILE_HANDLER_URL = '/profile'
FRONT_PAGE_HANDLER_URL = '/'
# Installation specific config ends.
diff --git a/slashlesscommandmessage_tests.py b/slashlesscommandmessage_tests.py
new file mode 100644
index 0000000..127808e
--- /dev/null
+++ b/slashlesscommandmessage_tests.py
@@ -0,0 +1,24 @@
+# Copyright (C) 2010 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import unittest
+from xmpp import SlashlessCommandMessage, XmppHandler
+
+
+class SlashlessCommandMessageTest(unittest.TestCase):
+ def test_extracts_symbol_as_command_given_symbol(self):
+ self.assertEquals('?', SlashlessCommandMessage.extract_command_and_arg_from_string('?')[0])
+
+ def test_extracts_all_commands(self):
+ for command in XmppHandler.PERMITTED_COMMANDS:
+ self.assertEquals(command, SlashlessCommandMessage.extract_command_and_arg_from_string(command)[0])
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index 8a3c45f..ecc7335 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,382 +1,382 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*\b)\s*(.*)", string)
- if results != None:
+ if results:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
- results = re.search(r"\s*(\S*\b)\s*", string)
- if results != None:
+ results = re.search(r"\s*(\S*)\s*", string)
+ if results:
command = results.group(1)
-
+ logging.debug('Groups matched: %s' % str(results))
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
- if self.__scm_command == None:
+ if not self.__scm_command:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper(), hub_subscriber=pshb.HubSubscriber()):
self.buzz_wrapper = buzz_wrapper
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
if message.command and message.command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % (message.command,)
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
self.unhandled_command(message)
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
else:
message_body = message.body[len(XmppHandler.POST_CMD):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
c11ee4cfd6dab7eff15fa716a3397f23572f64df
|
The bot now sends the user a chat invite and a welcome message when the user completes the OAuth Dance
|
diff --git a/TODO b/TODO
index 96891e4..d0ae15e 100644
--- a/TODO
+++ b/TODO
@@ -1,22 +1,15 @@
Buzz Chat Bot
============
-Add a sensible explanation of what this bot does and why anyone would want to use it:
-- mention the low-latency of using chat clients, which are always on, versus the web
-- mention that GChat saves messages that you received whilst you were offline
-- mention statuscasting: http://www.designingsocialinterfaces.com/patterns/Statuscasting
Register the app so that people don't have to trust anonymous
-Fix the Welcome page so that people can see it without needing to be logged in
-Update the web page so that it's more informative and doesn't require you login before it tells you anything
When someone adds the bot to their roster, send them a link to the app's website so that they can do the oauth dance
-When someone visits the website and does the OAuth dance, send them a chat invite
Profile page should show the email address of the current user.
-
Verify that phrase search works and add tests for it
/search [some search]
Update the PRD - describing this bot
Work out how to handle location-based Track and complex searches. Perhaps using the web interface?
Use Bob Wyman's trick where /track initially does a /search and gives you the first 10 results to verify that it's worked
File a bug for language indexing in search
File a bug for search by actor.id
Allow untrack to accept a search term as well as an id
-Allow for a stopword list -- useful for popular terms
\ No newline at end of file
+Allow for a stopword list -- useful for popular terms
+Implement a 'pause' command which stops sending you messages until you issue a 'resume' command
\ No newline at end of file
diff --git a/functional_tests.py b/functional_tests.py
index 2e20222..061f4b8 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,324 +1,324 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler, SlashlessCommandMessage
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
self.command,self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
self.message_to_send = None
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
arg = 'Some day my prints will come'
message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg) )
hub_subscriber = StubHubSubscriber()
handler = XmppHandler(hub_subscriber=hub_subscriber)
subscription = handler.track_command(message=message)
self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id()))
def test_unhandled_command_shows_correct_error(self):
command = 'wibble'
message = StubMessage(body=command)
handler = XmppHandler()
handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
handler = XmppHandler()
handler.track_command(message=message)
self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
- expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
+ expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
- expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
+ expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
handler.help_command(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.COMMAND_HELP_MSG_LIST:
self.assertTrue(command in message.message_to_send, message.message_to_send)
class XmppHandlerHttpTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_help_command_can_be_triggered_via_http(self):
# Help command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'help'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_list_command_can_be_triggered_via_http(self):
# List command was chosen as it's idempotent and has no side-effects
data = {'from' : settings.APP_NAME + '@appspot.com',
'to' : settings.APP_NAME + '@appspot.com',
'body' : 'list'}
response = self.post('/_ah/xmpp/message/chat/', data=data)
self.assertOK(response)
def test_invalid_http_request_triggers_error(self):
response = self.post('/_ah/xmpp/message/chat/', data={}, expect_errors=True)
self.assertEquals('400 Bad Request', response.status)
\ No newline at end of file
diff --git a/oauth_handlers.py b/oauth_handlers.py
index 26e6848..3edd3b4 100644
--- a/oauth_handlers.py
+++ b/oauth_handlers.py
@@ -1,126 +1,133 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import users
+from google.appengine.api import xmpp
import buzz_gae_client
import logging
import os
import settings
class UserToken(db.Model):
# The user_id is the key_name so we don't have to make it an explicit property
request_token_string = db.StringProperty()
access_token_string = db.StringProperty()
email_address = db.StringProperty()
def get_request_token(self):
"Returns request token as a dictionary of tokens including oauth_token, oauth_token_secret and oauth_callback_confirmed."
return eval(self.request_token_string)
def set_access_token(self, access_token):
access_token_string = repr(access_token)
self.access_token_string = access_token_string
def get_access_token(self):
"Returns access token as a dictionary of tokens including consumer_key, consumer_secret, oauth_token and oauth_token_secret"
return eval(self.access_token_string)
@staticmethod
def create_user_token(request_token):
user = users.get_current_user()
user_id = user.user_id()
request_token_string = repr(request_token)
# TODO(ade) Support users who sign in to AppEngine with a federated identity aka OpenId
email = user.email()
logging.info('Creating user token: key_name: %s request_token_string: %s email_address: %s' % (
user_id, request_token_string, email))
return UserToken(key_name=user_id, request_token_string=request_token_string, access_token_string='',
email_address=email)
@staticmethod
def get_current_user_token():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
return user_token
@staticmethod
def access_token_exists():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
logging.info('user_token: %s' % user_token)
return user_token and user_token.access_token_string
@staticmethod
def find_by_email_address(email_address):
user_tokens = UserToken.gql('WHERE email_address = :1', email_address).fetch(1)
if user_tokens:
return user_tokens[0] # The result of the query is a list
else:
return None
class DanceStartingHandler(webapp.RequestHandler):
@login_required
def get(self):
logging.info("Request body %s" % self.request.body)
template_values = {"jabber_id": ("%[email protected]" % settings.APP_NAME)}
if UserToken.access_token_exists():
template_values['access_token_exists'] = 'true'
else:
# Generate the request token
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
request_token = client.get_request_token(settings.CALLBACK_URL)
# Create the request token and associate it with the current user
user_token = UserToken.create_user_token(request_token)
UserToken.put(user_token)
authorisation_url = client.generate_authorisation_url(request_token)
logging.info('Authorisation URL is: %s' % authorisation_url)
template_values['destination'] = authorisation_url
path = os.path.join(os.path.dirname(__file__), 'start_dance.html')
self.response.out.write(template.render(path, template_values))
class TokenDeletionHandler(webapp.RequestHandler):
def post(self):
user_token = UserToken.get_current_user_token()
UserToken.delete(user_token)
self.redirect(settings.FRONT_PAGE_HANDLER_URL)
class DanceFinishingHandler(webapp.RequestHandler):
def get(self):
logging.info("Request body %s" % self.request.body)
oauth_verifier = self.request.get('oauth_verifier')
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
user_token = UserToken.get_current_user_token()
request_token = user_token.get_request_token()
access_token = client.upgrade_to_access_token(request_token, oauth_verifier)
logging.info('SUCCESS: Received access token.')
user_token.set_access_token(access_token)
UserToken.put(user_token)
logging.debug('Access token was: %s' % user_token.access_token_string)
+ # Send an XMPP invitation
+ logging.info('Sending invite to %s' % user_token.email_address)
+ xmpp.send_invite(user_token.email_address)
+ msg = 'Welcome to the BuzzChatBot: %s' % settings.APP_URL
+ xmpp.send_message(user_token.email_address, msg)
+
self.redirect(settings.PROFILE_HANDLER_URL)
\ No newline at end of file
diff --git a/settings.py b/settings.py
index 2eaa241..7c77037 100644
--- a/settings.py
+++ b/settings.py
@@ -1,53 +1,58 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
APP_NAME = 'favedby'
+
+#Note that the APP_URL must _not_ end in a slash as it will be concatenated with other values
+APP_URL = 'http://%s.appspot.com' % APP_NAME
ADMIN_PROFILE_URL = 'http://profiles.google.com/adewale'
#PSHB settings
-# This is the token that will act as a shared secret to verify that this application is the one that registered the given subscription. The hub will send us a challenge containing this token.
+# This is the token that will act as a shared secret to verify that this application is the one that registered the
+# given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
# OAuth consumer key and secret - you should change these to 'anonymous' unless you really are buzzchatbot.appspot.com
-# Alternatively you could go here: https://www.google.com/accounts/ManageDomains and register your instance so that you'll get your own consumer key and consumer secret
+# Alternatively you could go here: https://www.google.com/accounts/ManageDomains and register your instance so that
+# you'll get your own consumer key and consumer secret
#CONSUMER_KEY = 'buzzchatbot.appspot.com'
#CONSUMER_SECRET = 'tcw1rCMgLVY556Y0Q4rW/RnK'
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
# OAuth callback URL
-CALLBACK_URL = 'http://%s.appspot.com/finish_dance' % APP_NAME
+CALLBACK_URL = '%s/finish_dance' % APP_URL
PROFILE_HANDLER_URL = '/profile'
FRONT_PAGE_HANDLER_URL = '/'
# Installation specific config ends.
diff --git a/tracker_tests.py b/tracker_tests.py
index 6857a0e..3964f26 100644
--- a/tracker_tests.py
+++ b/tracker_tests.py
@@ -1,162 +1,162 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from xmpp import Subscription, Tracker, XmppHandler
import pshb
import settings
class StubHubSubscriber(pshb.HubSubscriber):
def subscribe(self, url, hub, callback_url):
self.callback_url = callback_url
def unsubscribe(self, url, hub, callback_url):
self.callback_url = callback_url
class TrackerTest(unittest.TestCase):
def test_is_blank_works_on_blank_strings(self):
self.assertTrue(Tracker.is_blank(None))
self.assertTrue(Tracker.is_blank(" "))
self.assertTrue(Tracker.is_blank(" ")) # has a tab in it
self.assertTrue(Tracker.is_blank(""))
def test_is_blank_works_on_nonblank_strings(self):
self.assertFalse(Tracker.is_blank(" a"))
self.assertFalse(Tracker.is_blank("adf "))
self.assertFalse(Tracker.is_blank(" adfas "))
self.assertFalse(Tracker.is_blank("daf-sa"))
def test_tracker_rejects_empty_search_term(self):
sender = '[email protected]'
term = ''
tracker = Tracker(hub_subscriber=StubHubSubscriber())
self.assertEquals(None, tracker.track(sender, term))
def test_tracker_extracts_integer_id_given_integer(self):
self.assertEquals(7, Tracker.extract_number(7))
def test_tracker_extracts_integer_id_given_string(self):
self.assertEquals(7, Tracker.extract_number('7'))
def test_tracker_returns_none_given_invalid_integer(self):
self.assertEquals(None, Tracker.extract_number('jaiku'))
self.assertEquals(None, Tracker.extract_number(None))
def test_tracker_rejects_padded_empty_string(self):
sender = '[email protected]'
tracker = Tracker(hub_subscriber=StubHubSubscriber())
self.assertEquals(None, tracker.track(sender, ' '))
def test_tracker_accepts_valid_string(self):
sender = '[email protected]'
search_term='somestring'
tracker = Tracker(hub_subscriber=StubHubSubscriber())
- expected_callback_url = 'http://%s.appspot.com/posts/%s/%s' % (settings.APP_NAME, sender, search_term)
+ expected_callback_url = '%s/posts/%s/%s' % (settings.APP_URL, sender, search_term)
expected_subscription = Subscription(url='https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, search_term=search_term, callback_url=expected_callback_url)
actual_subscription = tracker.track(sender, search_term)
self.assertEquals(expected_subscription.url, actual_subscription.url)
self.assertEquals(expected_subscription.search_term, actual_subscription.search_term)
def test_tracker_builds_correct_pshb_url(self):
search_term = 'somestring'
tracker = Tracker(hub_subscriber=StubHubSubscriber())
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, tracker._build_subscription_url(search_term))
def test_tracker_url_encodes_search_term(self):
search_term = 'some string'
tracker = Tracker(hub_subscriber=StubHubSubscriber())
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=' + 'some%20string', tracker._build_subscription_url(search_term))
def _delete_all_subscriptions(self):
for subscription in Subscription.all().fetch(100):
subscription.delete()
def test_tracker_saves_subscription(self):
self._delete_all_subscriptions()
self.assertEquals(0, len(Subscription.all().fetch(100)))
sender = '[email protected]'
search_term='somestring'
tracker = Tracker(hub_subscriber=StubHubSubscriber())
subscription = tracker.track(sender, search_term)
self.assertEquals(1, len(Subscription.all().fetch(100)))
self.assertEquals(subscription, Subscription.all().fetch(1)[0])
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query(self):
sender = '[email protected]'
search_term='somestring'
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, search_term)
- expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
+ expected_callback_url = '%s/posts?id=%s' % (settings.APP_URL, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_urlencoded_callback_url(self):
sender = '[email protected]'
search_term='some string'
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, search_term)
- expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
+ expected_callback_url = '%s/posts?id=%s' % (settings.APP_URL, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query_without_xmpp_client_identifier(self):
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, search_term)
- expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
+ expected_callback_url = '%s/posts?id=%s' % (settings.APP_URL, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_rejects_invalid_id_for_untracking(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.untrack(sender, '1')
self.assertEquals(None, subscription)
def test_tracker_untracks_valid_id(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
track_subscription = tracker.track(sender, search_term)
untrack_subscription = tracker.untrack(sender, track_subscription.id())
self.assertEquals(track_subscription, untrack_subscription)
self.assertFalse(Subscription.exists(track_subscription.id()))
- self.assertEquals('http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, track_subscription.id()), hub_subscriber.callback_url)
+ self.assertEquals('%s/posts?id=%s' % (settings.APP_URL, track_subscription.id()), hub_subscriber.callback_url)
diff --git a/xmpp.py b/xmpp.py
index e7b0d63..8a3c45f 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,382 +1,382 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string is None) or (len(string) == 0) or string.isspace()
@staticmethod
def extract_number(id):
"""Convert an id to an integer and return None if the conversion fails."""
if id is None:
return None
try:
id = int(id)
except ValueError, e:
return None
return id
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
- return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
+ return "%s/posts?id=%s" % (settings.APP_URL, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# TODO(ade) Do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
xmpp.Message.__init__(self, vars)
#TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*\b)\s*(.*)", string)
if results != None:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*\b)\s*", string)
if results != None:
command = results.group(1)
return (command,arg)
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if self.__scm_command == None:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
logging.info("command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg))
# These properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
""" TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml=False):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
COMMAND_HELP_MSG_LIST = [
'%s Prints out this message' % HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper(), hub_subscriber=pshb.HubSubscriber()):
self.buzz_wrapper = buzz_wrapper
self.tracker = Tracker(hub_subscriber=hub_subscriber)
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
-
+
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
if message.command and message.command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % (message.command,)
handler = getattr(self, handler_name, None)
if handler:
handler(message)
return
self.unhandled_command(message)
-
+
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
self.error(400)
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Sorry about that")
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" Print out the help command.
Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.COMMAND_HELP_MSG_LIST)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" Start tracking a phrase against the Buzz API.
message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = self.tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
subscription = self.tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
- about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
+ about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: %s' % (settings.APP_NAME, settings.APP_URL)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
- message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
+ message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
- message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
+ message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: %s' % (sender, settings.APP_URL))
else:
message_body = message.body[len(XmppHandler.POST_CMD):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
d967b725accf78732fa2e1936e2c3c6419d21db3
|
Fixed a regression in some of the tests subscription.id() => subscription.id done
|
diff --git a/functional_tests.py b/functional_tests.py
index 3a0703b..9d8ca2d 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,276 +1,276 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler, SlashlessCommandMessage
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
self.command,self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
self.message_to_send = None
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
- response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id))
+ response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
- response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id))
+ response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
# def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
# arg = 'Some day my prints will come'
# message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg) )
# handler = XmppHandler()
# subscription = handler.track_command(message=message)
-# self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id))
+# self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id()))
# # now as this is real, remove it again
# handler = XmppHandler()
# handler.untrack_command('%s %s' % (XmppHandler.UNTRACK_CMD, subscription.id))
def test_unhandled_command_shows_correct_error(self):
command = 'wibble'
message = StubMessage(body=command)
handler = XmppHandler()
handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
handler = XmppHandler()
handler.track_command(message=message)
self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
handler.help_command(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.commands:
self.assertTrue(command in message.message_to_send, message.message_to_send)
diff --git a/simple_buzz_wrapper.py b/simple_buzz_wrapper.py
index 0257d4f..15e7202 100644
--- a/simple_buzz_wrapper.py
+++ b/simple_buzz_wrapper.py
@@ -1,55 +1,65 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import buzz_gae_client
import settings
import oauth_handlers
import logging
class SimpleBuzzWrapper(object):
"Simple client that exposes the bare minimum set of Buzz operations"
def __init__(self, user_token=None):
if user_token:
self.current_user_token = user_token
self.builder = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
+ def search(self, sender, message_body ):
+ """ TODO(julian): standardize methods for accessing api clients once it's clear what the implications
+ of the 2 paths (email, user_token) are """
+ if message_body is None or message_body.strip() is '':
+ return None
+
+ user_token = oauth_handlers.UserToken.find_by_email_address(sender)
+ api_client = self.builder.build_api_client(user_token.get_access_token())
+
+
def post(self, sender, message_body):
if message_body is None or message_body.strip() is '':
return None
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
api_client = self.builder.build_api_client(user_token.get_access_token())
#TODO(ade) What happens with users who have hidden their email address?
# Switch to @me so it won't matter
user_id = sender.split('@')[0]
activities = api_client.activities()
logging.info('Retrieved activities for: %s' % user_id)
activity = activities.insert(userId=user_id, body={
'title': message_body,
'object': {
'content': message_body,
'type': 'note'}
}
).execute()
url = activity['links']['alternate'][0]['href']
logging.info('Just created: %s' % url)
return url
def get_profile(self):
api_client = self.builder.build_api_client(self.current_user_token.get_access_token())
user_profile_data = api_client.people().get(userId='@me').execute()
return user_profile_data
diff --git a/simple_buzz_wrapper_tests.py b/simple_buzz_wrapper_tests.py
index e1c1cf3..ead2c00 100644
--- a/simple_buzz_wrapper_tests.py
+++ b/simple_buzz_wrapper_tests.py
@@ -1,29 +1,29 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import simple_buzz_wrapper
import unittest
class SimpleBuzzWrapperTest(unittest.TestCase):
- def test_wrapper_rejects_empty_message(self):
+ def test_wrapper_rejects_empty_post(self):
wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
self.assertEquals(None, wrapper.post('[email protected]', ''))
- def test_wrapper_rejects_messsage_containing_only_whitespace(self):
+ def test_wrapper_rejects_post_containing_only_whitespace(self):
wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
self.assertEquals(None, wrapper.post('[email protected]', ' '))
- def test_wrapper_rejects_none_message(self):
+ def test_wrapper_rejects_none_post(self):
wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
self.assertEquals(None, wrapper.post('[email protected]', None))
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index 3afece1..356f3f5 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,391 +1,391 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string == None) or (len(string) == 0) or string.isspace()
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
@staticmethod
def extract_number(id):
""" some jiggery pokery to get the number. TODO there must be libraries for this kind of thing"""
if id == None:
return None
if type(id) == type(int()):
return id
try:
id = int(id)
except ValueError, e:
return None
return id
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
- TODO: you should be able to untrack <term> directly. """
+ TODO(julian): you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# todo do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
#super(xmpp.Message, self).__init__(vars) -- silently fails. #pythonwtf
xmpp.Message.__init__(self, vars)
- #TODO make arg and command protected. because __arg and __command are hidden as private
+ #TODO(julian) make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*\b)\s*(.*)", string)
if results != None:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*\b)\s*", string)
if results != None:
command = results.group(1)
return [command,arg]
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if self.__scm_command == None:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
print "command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg)
# these properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
@property
def message_to_send(self):
- """ TODO rename: this is actually response_message """
+ """ TODO(julian) rename: this is actually response_message """
return self.__message_to_send
def reply(self, message_to_send, raw_xml):
logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
#this should be called COMMAND_HELP_MSG_LIST but App Engine requires this specific name!
# make this dependency explicit.
commands = [
'%s Prints out this message' % HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
self.buzz_wrapper = buzz_wrapper
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
if message.command and message.command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % (message.command,)
handler = getattr(self, handler_name, None)
if handler:
handler(message)
else:
self.unhandled_command(message)
else:
self.unhandled_command(message)
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
- TODO xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
+ TODO(julian) xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
- TODO this has no test coverage
+ TODO(julian) this has no test coverage
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply("Oops. Something went wrong. Beta software etc." )
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" print out the help command. Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" start tracking a phrase against the Buzz API. message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
tracker = Tracker()
logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
subscription = tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
message_body = message.body[len(XmppHandler.POST_CMD):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
93ab673dd21a18932d966af2fca11bdc92391a30
|
Broke tracking in last build -- fixed (test coverage for integration tests is quite tricky right now).
|
diff --git a/xmpp.py b/xmpp.py
index b93d21a..3afece1 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,380 +1,391 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string == None) or (len(string) == 0) or string.isspace()
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, search_term):
return not Tracker.is_blank(search_term)
def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, search_term):
if self._valid_subscription(search_term):
return self._subscribe(message_sender, search_term)
else:
return None
@staticmethod
def extract_number(id):
""" some jiggery pokery to get the number. TODO there must be libraries for this kind of thing"""
if id == None:
return None
if type(id) == type(int()):
return id
try:
id = int(id)
except ValueError, e:
return None
return id
def untrack(self, message_sender, id):
""" Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
TODO: you should be able to untrack <term> directly. """
logging.info("Tracker.untrack: id is: '%s'" % id)
id_as_int = Tracker.extract_number(id)
if id_as_int == None:
# todo do a subscription lookup by name here
return None
subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
#super(xmpp.Message, self).__init__(vars) -- silently fails. #pythonwtf
xmpp.Message.__init__(self, vars)
#TODO make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
+ self.__message_to_send = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*\b)\s*(.*)", string)
if results != None:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*\b)\s*", string)
if results != None:
command = results.group(1)
return [command,arg]
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if self.__scm_command == None:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
print "command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg)
# these properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
+
+ @property
+ def message_to_send(self):
+ """ TODO rename: this is actually response_message """
+ return self.__message_to_send
+
+ def reply(self, message_to_send, raw_xml):
+ logging.debug( "SlashlessCommandMessage.reply: message_to_send = %s" % message_to_send)
+ xmpp.Message.reply(self, message_to_send, raw_xml=raw_xml)
+ self.__message_to_send = message_to_send
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
#this should be called COMMAND_HELP_MSG_LIST but App Engine requires this specific name!
# make this dependency explicit.
commands = [
'%s Prints out this message' % HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
self.buzz_wrapper = buzz_wrapper
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
if message.command and message.command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % (message.command,)
handler = getattr(self, handler_name, None)
if handler:
handler(message)
else:
self.unhandled_command(message)
else:
self.unhandled_command(message)
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
TODO this has no test coverage
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
- self.xmpp_message.reply('Oops. Something went wrong.')
+ self.xmpp_message.reply("Oops. Something went wrong. Beta software etc." )
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" print out the help command. Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" start tracking a phrase against the Buzz API. message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
tracker = Tracker()
- logging.debug( "track_command: calling tracker.track with body = '%s'")
- subscription = tracker.track(message.sender, message.body)
+ logging.debug( "track_command: calling tracker.track with term '%s'" % message.arg )
+ subscription = tracker.track(message.sender, message.arg)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
- print "message.message_to_send = '%s'" % message.message_to_send
+ logging.debug( "message.message_to_send = '%s'" % message.message_to_send )
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
message_body = message.body[len(XmppHandler.POST_CMD):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
a432bfd3dd0a95235a9265183a4d686927e2850e
|
Tidied up Tracker so that it accepts a search term rather than the message body. This avoids the whole 'reparse message body again' code and means the command line now can deal more flexibly with whitespace (previously you had to have exactly one space between command and terms).
|
diff --git a/TODO b/TODO
index 36f49cc..96891e4 100644
--- a/TODO
+++ b/TODO
@@ -1,21 +1,22 @@
Buzz Chat Bot
============
Add a sensible explanation of what this bot does and why anyone would want to use it:
- mention the low-latency of using chat clients, which are always on, versus the web
- mention that GChat saves messages that you received whilst you were offline
- mention statuscasting: http://www.designingsocialinterfaces.com/patterns/Statuscasting
Register the app so that people don't have to trust anonymous
Fix the Welcome page so that people can see it without needing to be logged in
Update the web page so that it's more informative and doesn't require you login before it tells you anything
When someone adds the bot to their roster, send them a link to the app's website so that they can do the oauth dance
When someone visits the website and does the OAuth dance, send them a chat invite
Profile page should show the email address of the current user.
Verify that phrase search works and add tests for it
/search [some search]
Update the PRD - describing this bot
Work out how to handle location-based Track and complex searches. Perhaps using the web interface?
Use Bob Wyman's trick where /track initially does a /search and gives you the first 10 results to verify that it's worked
File a bug for language indexing in search
File a bug for search by actor.id
-
+Allow untrack to accept a search term as well as an id
+Allow for a stopword list -- useful for popular terms
\ No newline at end of file
diff --git a/functional_tests.py b/functional_tests.py
index cac18fe..3a0703b 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,275 +1,276 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler, SlashlessCommandMessage
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
self.command,self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
+ self.message_to_send = None
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
# def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
# arg = 'Some day my prints will come'
# message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg) )
# handler = XmppHandler()
# subscription = handler.track_command(message=message)
# self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id))
# # now as this is real, remove it again
# handler = XmppHandler()
# handler.untrack_command('%s %s' % (XmppHandler.UNTRACK_CMD, subscription.id))
def test_unhandled_command_shows_correct_error(self):
command = 'wibble'
message = StubMessage(body=command)
handler = XmppHandler()
handler.message_received(message)
self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
handler = XmppHandler()
handler.track_command(message=message)
- self.assertTrue(XmppHandler.NOTHING_TO_TRACK in message.message_to_send, message.message_to_send)
+ self.assertTrue(XmppHandler.NOTHING_TO_TRACK_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
- expected_item = 'No subscriptions'
+ expected_item = XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
handler.help_command(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.commands:
self.assertTrue(command in message.message_to_send, message.message_to_send)
diff --git a/tracker_tests.py b/tracker_tests.py
index c857690..8ea01dc 100644
--- a/tracker_tests.py
+++ b/tracker_tests.py
@@ -1,158 +1,141 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from xmpp import Subscription, Tracker, XmppHandler
import pshb
import settings
class StubHubSubscriber(pshb.HubSubscriber):
def subscribe(self, url, hub, callback_url):
self.callback_url = callback_url
def unsubscribe(self, url, hub, callback_url):
self.callback_url = callback_url
class TrackerTest(unittest.TestCase):
def test_is_blank_works_on_blank_strings(self):
self.assertTrue(Tracker.is_blank(None))
self.assertTrue(Tracker.is_blank(" "))
self.assertTrue(Tracker.is_blank(" ")) # has a tab in it
self.assertTrue(Tracker.is_blank(""))
def test_is_blank_works_on_nonblank_strings(self):
self.assertFalse(Tracker.is_blank(" a"))
self.assertFalse(Tracker.is_blank("adf "))
self.assertFalse(Tracker.is_blank(" adfas "))
self.assertFalse(Tracker.is_blank("daf-sa"))
def test_tracker_rejects_empty_search_term(self):
sender = '[email protected]'
- body = XmppHandler.TRACK_CMD
+ term = ''
tracker = Tracker()
- self.assertEquals(None, tracker.track(sender, body))
+ self.assertEquals(None, tracker.track(sender, term))
def test_tracker_rejects_padded_empty_string(self):
sender = '[email protected]'
- body = '%s ' % XmppHandler.TRACK_CMD
tracker = Tracker()
- self.assertEquals(None, tracker.track(sender, body))
+ self.assertEquals(None, tracker.track(sender, ' '))
def test_tracker_accepts_valid_string(self):
sender = '[email protected]'
search_term='somestring'
- body = '%s %s' % (XmppHandler.TRACK_CMD, search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
expected_callback_url = 'http://%s.appspot.com/posts/%s/%s' % (settings.APP_NAME, sender, search_term)
expected_subscription = Subscription(url='https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, search_term=search_term, callback_url=expected_callback_url)
- actual_subscription = tracker.track(sender, body)
+ actual_subscription = tracker.track(sender, search_term)
self.assertEquals(expected_subscription.url, actual_subscription.url)
self.assertEquals(expected_subscription.search_term, actual_subscription.search_term)
- def test_tracker_extracts_correct_search_term(self):
- search_term = 'somestring'
- body = '%s %s' % (XmppHandler.TRACK_CMD, search_term)
- tracker = Tracker()
- self.assertEquals(search_term, tracker._extract_search_term(body))
-
def test_tracker_builds_correct_pshb_url(self):
search_term = 'somestring'
tracker = Tracker()
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, tracker._build_subscription_url(search_term))
def test_tracker_url_encodes_search_term(self):
search_term = 'some string'
tracker = Tracker()
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=' + 'some%20string', tracker._build_subscription_url(search_term))
def _delete_all_subscriptions(self):
for subscription in Subscription.all().fetch(100):
subscription.delete()
def test_tracker_saves_subscription(self):
self._delete_all_subscriptions()
self.assertEquals(0, len(Subscription.all().fetch(100)))
sender = '[email protected]'
search_term='somestring'
- body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
tracker = Tracker()
- subscription = tracker.track(sender, body)
+ subscription = tracker.track(sender, search_term)
self.assertEquals(1, len(Subscription.all().fetch(100)))
self.assertEquals(subscription, Subscription.all().fetch(1)[0])
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query(self):
sender = '[email protected]'
search_term='somestring'
- body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
- subscription = tracker.track(sender, body)
+ subscription = tracker.track(sender, search_term)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_urlencoded_callback_url(self):
sender = '[email protected]'
search_term='some string'
- body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
- subscription = tracker.track(sender, body)
+ subscription = tracker.track(sender, search_term)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query_without_xmpp_client_identifier(self):
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
- body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
- subscription = tracker.track(sender, body)
+ subscription = tracker.track(sender, search_term)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_rejects_invalid_id_for_untracking(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
- body = '%s 1' % XmppHandler.UNTRACK_CMD
-
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
- subscription = tracker.untrack(sender, body)
+ subscription = tracker.untrack(sender, '1')
self.assertEquals(None, subscription)
def test_tracker_untracks_valid_id(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
- body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
- track_subscription = tracker.track(sender, body)
-
- body = '%s %s' % (XmppHandler.UNTRACK_CMD,track_subscription.id())
- untrack_subscription = tracker.untrack(sender, body)
+ track_subscription = tracker.track(sender, search_term)
+ untrack_subscription = tracker.untrack(sender, track_subscription.id())
self.assertEquals(track_subscription, untrack_subscription)
self.assertFalse(Subscription.exists(track_subscription.id()))
self.assertEquals('http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, track_subscription.id()), hub_subscriber.callback_url)
diff --git a/xmpp.py b/xmpp.py
index 5ffe223..b93d21a 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,376 +1,380 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (string == None) or (len(string) == 0) or string.isspace()
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
- def _valid_subscription(self, message_body):
- return not Tracker.is_blank(self._extract_search_term(message_body))
+ def _valid_subscription(self, search_term):
+ return not Tracker.is_blank(search_term)
- def _extract_search_term(self, message_body):
- search_term = message_body[len(XmppHandler.TRACK_CMD):]
- return search_term.strip()
-
- def _subscribe(self, message_sender, message_body):
+ def _subscribe(self, message_sender, search_term):
message_sender = extract_sender_email_address(message_sender)
- search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
- def track(self, message_sender, message_body):
- if self._valid_subscription(message_body):
- return self._subscribe(message_sender, message_body)
+ def track(self, message_sender, search_term):
+ if self._valid_subscription(search_term):
+ return self._subscribe(message_sender, search_term)
else:
return None
@staticmethod
- def is_number(id):
- if not id:
- return False
- id = id.strip()
- for char in id:
- if not char.isdigit():
- return False
- return True
-
- def untrack(self, message_sender, message_body):
- logging.info('Message is: %s' % message_body)
- id = message_body[len(XmppHandler.UNTRACK_CMD):]
- if not Tracker.is_number(id):
+ def extract_number(id):
+ """ some jiggery pokery to get the number. TODO there must be libraries for this kind of thing"""
+ if id == None:
+ return None
+
+ if type(id) == type(int()):
+ return id
+ try:
+ id = int(id)
+ except ValueError, e:
+ return None
+ return id
+
+ def untrack(self, message_sender, id):
+ """ Given an id, untrack takes it and attempts to unsubscribe from the list of tracked items.
+ TODO: you should be able to untrack <term> directly. """
+ logging.info("Tracker.untrack: id is: '%s'" % id)
+ id_as_int = Tracker.extract_number(id)
+ if id_as_int == None:
+ # todo do a subscription lookup by name here
return None
- id = id.strip()
- subscription = Subscription.get_by_id(int(id))
- logging.info('Subscripton: %s' % str(subscription))
+ subscription = Subscription.get_by_id(id_as_int)
if not subscription:
return None
+ logging.info('Subscripton: %s' % str(subscription))
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
#super(xmpp.Message, self).__init__(vars) -- silently fails. #pythonwtf
xmpp.Message.__init__(self, vars)
#TODO make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*\b)\s*(.*)", string)
if results != None:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*\b)\s*", string)
if results != None:
command = results.group(1)
return [command,arg]
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if self.__scm_command == None:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
print "command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg)
# these properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
#this should be called COMMAND_HELP_MSG_LIST but App Engine requires this specific name!
# make this dependency explicit.
commands = [
'%s Prints out this message' % HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
- TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
- NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
- UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
- SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
-
+ TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
+ NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
+ UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
+ SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
+ LIST_NOT_TRACKING_ANYTHING_MSG = 'You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>'
+
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
- print "XmppHandler.__init__"
self.buzz_wrapper = buzz_wrapper
def unhandled_command(self, message):
""" User entered a command that is not recognised. Tell them this and show help"""
self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
if message.command and message.command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % (message.command,)
handler = getattr(self, handler_name, None)
if handler:
handler(message)
else:
self.unhandled_command(message)
else:
self.unhandled_command(message)
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
TODO this has no test coverage
"""
logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
logging.error( "handle_exception: calling webapp.RequestHandler superclass")
webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply('Oops. Something went wrong.')
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None, prompt='We all need a little help sometimes' ):
""" print out the help command. Optionally accepts a message builder
so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
lines = [prompt]
lines.extend(self.commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
""" start tracking a phrase against the Buzz API. message must be a valid
xmpp.Message or subclass and cannot be null. """
logging.debug('Received message from: %s' % message.sender)
subscription = None
message_builder = MessageBuilder()
if message.arg == '':
message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
tracker = Tracker()
+ logging.debug( "track_command: calling tracker.track with body = '%s'")
subscription = tracker.track(message.sender, message.body)
if subscription:
message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
- reply(message_builder, message)
+
+ reply(message_builder, message)
+ print "message.message_to_send = '%s'" % message.message_to_send
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
- subscription = tracker.untrack(message.sender, message.body)
+ subscription = tracker.untrack(message.sender, message.arg)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
- message_builder.add('You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>')
+ message_builder.add(XmppHandler.LIST_NOT_TRACKING_ANYTHING_MSG)
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
message_body = message.body[len(XmppHandler.POST_CMD):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
3102ea3431bcd049a9950657fe672108d94822bb
|
First build that actually works with no slash prefix. Commands are as before but you type:
|
diff --git a/README b/README
index 5fb7360..ee9bf39 100644
--- a/README
+++ b/README
@@ -1,55 +1,55 @@
This is an experimental jaiku-style chat bot for Google Buzz.
If it breaks you get to keep both pieces.
What does it do?
================
At the moment it lets you ask for:
-/help Prints out this message
-/track [search term] Starts tracking the given search term and returns the id for your subscription
-/untrack [id] Removes your subscription for that id
-/list Lists all search terms and ids currently being tracked by you
-/about Tells you which instance of the Buzz Chat Bot you are using
-/post [some message] Posts that message to Buzz
+help Prints out this message
+track [search term] Starts tracking the given search term and returns the id for your subscription
+untrack [id] Removes your subscription for that id
+list Lists all search terms and ids currently being tracked by you
+about Tells you which instance of the Buzz Chat Bot you are using
+post [some message] Posts that message to Buzz
Why does it exist?
==================
There are 2 sets of reasons why this bot exists.
1- I wanted to create a demo app (using the new Python client library: http://code.google.com/p/google-api-python-client/ ) which would show people a different kind of Buzz app. It's not trying to be a slightly different clone of the existing UI.
2- My experience with Jaiku and Friendfeed taught me that chat interfaces have a number of advantage over web interfaces:
- they're quicker since you can't beat the latency of alt-tabbing to Adium
- they're always on
- they're transient so you don't feel inundated if you track lots of keywords or see lots of posts because they all just flow by
- they encourage statuscasting: http://www.designingsocialinterfaces.com/patterns/Statuscasting which makes for a more conversational experience
- they allow people and brands to conveniently track keywords without having to learn how PSHB works
What does it require?
=====================
App Engine
Python
Tests
=====
To run the tests you need gae-testbed, nose and nose-gae. So...
sudo easy_install gaetestbed
sudo easy_install nose
sudo easy_install nosegae
They can be run like this:
nosetests --with-gae tracker_tests.py
Although I prefer to do something like this:
nosetests --with-gae *test*py
INSTALLATION
============
This isn't yet ready for installation by people who don't feel like changing the Python code. However if you feel brave you should:
- Register an AppEngine application at http://appengine.google.com/start/createapp?
- Change the app.yaml file to have the same Application Identifier as your application.
- Take a look at settings.py
-- Change the settings.APP_NAME constant to have the same Application Identifier as your application.
-- Change the settings.SECRET_TOKEN from the default
- Use the Google App Engine Launcher: http://code.google.com/appengine/downloads.html#Google_App_Engine_SDK_for_Python to deploy the application.
\ No newline at end of file
diff --git a/app.yaml b/app.yaml
index e30bf45..d827c65 100644
--- a/app.yaml
+++ b/app.yaml
@@ -1,15 +1,15 @@
-application: buzzchatbot
+application: kiwibuzzer
version: 1
runtime: python
api_version: 1
handlers:
- url: /css
static_dir: css
- url: /images
static_dir: images
- url: /.*
script: main.py
inbound_services:
- xmpp_message
\ No newline at end of file
diff --git a/functional_tests.py b/functional_tests.py
index 2fa0a0b..cac18fe 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,268 +1,275 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler, SlashlessCommandMessage
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
- #self.command,self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
+ self.command,self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
-
-
+
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
# def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
# arg = 'Some day my prints will come'
# message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg) )
# handler = XmppHandler()
# subscription = handler.track_command(message=message)
# self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id))
# # now as this is real, remove it again
# handler = XmppHandler()
# handler.untrack_command('%s %s' % (XmppHandler.UNTRACK_CMD, subscription.id))
+ def test_unhandled_command_shows_correct_error(self):
+ command = 'wibble'
+ message = StubMessage(body=command)
+ handler = XmppHandler()
+ handler.message_received(message)
+ self.assertTrue(XmppHandler.UNKNOWN_COMMAND_MSG % command in message.message_to_send, message.message_to_send)
+
+
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
handler = XmppHandler()
handler.track_command(message=message)
- self.assertTrue(XmppHandler.TRACK_FAILED_MSG in message.message_to_send, message.message_to_send)
+ self.assertTrue(XmppHandler.NOTHING_TO_TRACK in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
handler.help_command(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.commands:
self.assertTrue(command in message.message_to_send, message.message_to_send)
diff --git a/main.py b/main.py
index cd7a9d8..e66a1df 100644
--- a/main.py
+++ b/main.py
@@ -1,125 +1,127 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
import oauth_handlers
import os
import settings
import xmpp
import pshb
import simple_buzz_wrapper
class ProfileViewingHandler(webapp.RequestHandler):
@login_required
def get(self):
user_token = oauth_handlers.UserToken.get_current_user_token()
buzz_wrapper = simple_buzz_wrapper.SimpleBuzzWrapper(user_token)
user_profile_data = buzz_wrapper.get_profile()
template_values = {'user_profile_data': user_profile_data, 'access_token': user_token.access_token_string}
path = os.path.join(os.path.dirname(__file__), 'profile.html')
self.response.out.write(template.render(path, template_values))
class FrontPageHandler(webapp.RequestHandler):
def get(self):
template_values = {'commands' : xmpp.XmppHandler.commands,
'help_command' : xmpp.XmppHandler.HELP_CMD,
'jabber_id' : '%[email protected]' % settings.APP_NAME,
'admin_url' : settings.ADMIN_PROFILE_URL}
path = os.path.join(os.path.dirname(__file__), 'front_page.html')
self.response.out.write(template.render(path, template_values))
class PostsHandler(webapp.RequestHandler):
def _get_subscription(self):
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
return subscription
def get(self):
"""Show all the resources in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.debug("New content: %s" % self.request.body)
id = self.request.get('id')
+ logging.debug("Request id = '%s'", id)
# If this is a hub challenge
if self.request.get('hub.challenge'):
# If this subscription exists
mode = self.request.get('hub.mode')
topic = self.request.get('hub.topic')
if mode == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
elif mode == "unsubscribe" and not xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
else:
self.response.set_status(404)
self.response.out.write("Challenge failed")
logging.info("Challenge failed for feed: %s" % topic)
# Once a challenge has been issued there's no point in returning anything other than challenge passed or failed
return
def post(self):
"""Create a new resource in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.debug("New content: %s" % self.request.body)
id = self.request.get('id')
+ logging.debug("Request id = '%s'", id)
subscription = xmpp.Subscription.get_by_id(int(id))
if not subscription:
self.response.set_status(404)
self.response.out.write("No such subscription")
logging.warning('No subscription for %s' % id)
return
subscriber = subscription.subscriber
search_term = subscription.search_term
parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB)
url = parser.extractFeedUrl()
if not parser.dataValid():
parser.logErrors()
self.response.out.write("Bad entries: %s" % parser.data)
return
else:
posts = parser.extractPosts()
logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url))
xmpp.send_posts(posts, subscriber, search_term)
self.response.set_status(200)
application = webapp.WSGIApplication([
(settings.FRONT_PAGE_HANDLER_URL, FrontPageHandler),
(settings.PROFILE_HANDLER_URL, ProfileViewingHandler),
('/start_dance', oauth_handlers.DanceStartingHandler),
('/finish_dance', oauth_handlers.DanceFinishingHandler),
('/delete_tokens', oauth_handlers.TokenDeletionHandler),
('/posts', PostsHandler),
('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
diff --git a/settings.py b/settings.py
index 9723e8b..338f9d0 100644
--- a/settings.py
+++ b/settings.py
@@ -1,54 +1,54 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-APP_NAME = 'buzzchatbot'
-ADMIN_PROFILE_URL = 'http://profiles.google.com/adewale'
+APP_NAME = 'kiwibuzzer'
+ADMIN_PROFILE_URL = 'http://profiles.google.com/julian.harris'
#PSHB settings
# This is the token that will act as a shared secret to verify that this application is the one that registered the given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
# OAuth consumer key and secret - you should change these to 'anonymous' unless you really are buzzchatbot.appspot.com
# Alternatively you could go here: https://www.google.com/accounts/ManageDomains and register your instance so that you'll get your own consumer key and consumer secret
#CONSUMER_KEY = 'buzzchatbot.appspot.com'
#CONSUMER_SECRET = 'tcw1rCMgLVY556Y0Q4rW/RnK'
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
# OAuth callback URL
CALLBACK_URL = 'http://%s.appspot.com/finish_dance' % APP_NAME
PROFILE_HANDLER_URL = '/profile'
FRONT_PAGE_HANDLER_URL = '/'
# Installation specific config ends.
diff --git a/tracker_tests.py b/tracker_tests.py
index 39f8aee..c857690 100644
--- a/tracker_tests.py
+++ b/tracker_tests.py
@@ -1,157 +1,158 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from xmpp import Subscription, Tracker, XmppHandler
import pshb
import settings
class StubHubSubscriber(pshb.HubSubscriber):
def subscribe(self, url, hub, callback_url):
self.callback_url = callback_url
def unsubscribe(self, url, hub, callback_url):
self.callback_url = callback_url
class TrackerTest(unittest.TestCase):
def test_is_blank_works_on_blank_strings(self):
+ self.assertTrue(Tracker.is_blank(None))
self.assertTrue(Tracker.is_blank(" "))
self.assertTrue(Tracker.is_blank(" ")) # has a tab in it
self.assertTrue(Tracker.is_blank(""))
def test_is_blank_works_on_nonblank_strings(self):
self.assertFalse(Tracker.is_blank(" a"))
self.assertFalse(Tracker.is_blank("adf "))
self.assertFalse(Tracker.is_blank(" adfas "))
self.assertFalse(Tracker.is_blank("daf-sa"))
def test_tracker_rejects_empty_search_term(self):
sender = '[email protected]'
body = XmppHandler.TRACK_CMD
tracker = Tracker()
self.assertEquals(None, tracker.track(sender, body))
def test_tracker_rejects_padded_empty_string(self):
sender = '[email protected]'
body = '%s ' % XmppHandler.TRACK_CMD
tracker = Tracker()
self.assertEquals(None, tracker.track(sender, body))
def test_tracker_accepts_valid_string(self):
sender = '[email protected]'
search_term='somestring'
body = '%s %s' % (XmppHandler.TRACK_CMD, search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
expected_callback_url = 'http://%s.appspot.com/posts/%s/%s' % (settings.APP_NAME, sender, search_term)
expected_subscription = Subscription(url='https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, search_term=search_term, callback_url=expected_callback_url)
actual_subscription = tracker.track(sender, body)
self.assertEquals(expected_subscription.url, actual_subscription.url)
self.assertEquals(expected_subscription.search_term, actual_subscription.search_term)
def test_tracker_extracts_correct_search_term(self):
search_term = 'somestring'
body = '%s %s' % (XmppHandler.TRACK_CMD, search_term)
tracker = Tracker()
self.assertEquals(search_term, tracker._extract_search_term(body))
def test_tracker_builds_correct_pshb_url(self):
search_term = 'somestring'
tracker = Tracker()
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, tracker._build_subscription_url(search_term))
def test_tracker_url_encodes_search_term(self):
search_term = 'some string'
tracker = Tracker()
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=' + 'some%20string', tracker._build_subscription_url(search_term))
def _delete_all_subscriptions(self):
for subscription in Subscription.all().fetch(100):
subscription.delete()
def test_tracker_saves_subscription(self):
self._delete_all_subscriptions()
self.assertEquals(0, len(Subscription.all().fetch(100)))
sender = '[email protected]'
search_term='somestring'
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
tracker = Tracker()
subscription = tracker.track(sender, body)
self.assertEquals(1, len(Subscription.all().fetch(100)))
self.assertEquals(subscription, Subscription.all().fetch(1)[0])
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query(self):
sender = '[email protected]'
search_term='somestring'
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_urlencoded_callback_url(self):
sender = '[email protected]'
search_term='some string'
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query_without_xmpp_client_identifier(self):
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_rejects_invalid_id_for_untracking(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
body = '%s 1' % XmppHandler.UNTRACK_CMD
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.untrack(sender, body)
self.assertEquals(None, subscription)
def test_tracker_untracks_valid_id(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
track_subscription = tracker.track(sender, body)
body = '%s %s' % (XmppHandler.UNTRACK_CMD,track_subscription.id())
untrack_subscription = tracker.untrack(sender, body)
self.assertEquals(track_subscription, untrack_subscription)
self.assertFalse(Subscription.exists(track_subscription.id()))
self.assertEquals('http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, track_subscription.id()), hub_subscriber.callback_url)
diff --git a/xmpp.py b/xmpp.py
index b7d9eed..5ffe223 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,372 +1,376 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
from google.appengine.ext import webapp
+
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
- return (len(string) == 0) or string.isspace()
+ return (string == None) or (len(string) == 0) or string.isspace()
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return not Tracker.is_blank(self._extract_search_term(message_body))
def _extract_search_term(self, message_body):
search_term = message_body[len(XmppHandler.TRACK_CMD):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
@staticmethod
def is_number(id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len(XmppHandler.UNTRACK_CMD):]
if not Tracker.is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
#super(xmpp.Message, self).__init__(vars) -- silently fails. #pythonwtf
xmpp.Message.__init__(self, vars)
#TODO make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
# END TODO
@staticmethod
def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
command = None
arg = None
results = re.search(r"\s*(\S*\b)\s*(.*)", string)
if results != None:
command = results.group(1)
arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
results = re.search(r"\s*(\S*\b)\s*", string)
if results != None:
command = results.group(1)
return [command,arg]
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if self.__scm_command == None:
self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
print "command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg)
# these properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
- PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD, UNTRACK_CMD]
+ PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD,UNTRACK_CMD]
#this should be called COMMAND_HELP_MSG_LIST but App Engine requires this specific name!
# make this dependency explicit.
commands = [
'%s Prints out this message' % HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
- TRACK_FAILED_MSG = 'Sorry there was a problem with your last track command '
- UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood."
- SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
+ TRACK_FAILED_MSG = 'Sorry there was a problem with that track command '
+ NOTHING_TO_TRACK_MSG = "To track a phrase on buzz, you need to enter the phrase :) Please type: track <your phrase to track>"
+ UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood. Here are a list of the things you can do:"
+ SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
print "XmppHandler.__init__"
self.buzz_wrapper = buzz_wrapper
def unhandled_command(self, message):
- """ User entered a command that is not recognised. """
- message.reply(UNKNOWN_COMMAND_MSG % message )
+ """ User entered a command that is not recognised. Tell them this and show help"""
+ self.help_command(message, XmppHandler.UNKNOWN_COMMAND_MSG % message.command )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
if message.command and message.command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % (message.command,)
handler = getattr(self, handler_name, None)
if handler:
handler(message)
- self.unhandled_command(message)
-
-
- def handle_exception(self, exception, debug_mode):
- """Called if this handler throws an exception during execution.
-
- Args:
- exception: the exception that was thrown
- debug_mode: True if the web application is running in debug mode
- """
- super(BaseHandler, self).handle_exception(exception, debug_mode)
- if self.xmpp_message:
- self.xmpp_message.reply('Oops. Something went wrong.')
+ else:
+ self.unhandled_command(message)
+ else:
+ self.unhandled_command(message)
+
def post(self):
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
TODO this has no test coverage
"""
+ logging.info("Received chat msg, raw post = '%s'" % self.request.POST)
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
- super(xmpp_handlers.CommandHandler, self).handle_exception(exception, debug_mode)
+ logging.error( "handle_exception: calling webapp.RequestHandler superclass")
+ webapp.RequestHandler.handle_exception(self, exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply('Oops. Something went wrong.')
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
- def help_command(self, message=None):
+ def help_command(self, message=None, prompt='We all need a little help sometimes' ):
+ """ print out the help command. Optionally accepts a message builder
+ so help can be printed out if the user looks like they're having trouble """
logging.info('Received message from: %s' % message.sender)
- lines = ['We all need a little help sometimes']
+ lines = [prompt]
lines.extend(self.commands)
-
message_builder = MessageBuilder()
+
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
- logging.info('Received message from: %s' % message.sender)
-
- tracker = Tracker()
- subscription = tracker.track(message.sender, message.body)
+ """ start tracking a phrase against the Buzz API. message must be a valid
+ xmpp.Message or subclass and cannot be null. """
+ logging.debug('Received message from: %s' % message.sender)
+ subscription = None
+
message_builder = MessageBuilder()
- if subscription:
- message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
+ if message.arg == '':
+ message_builder.add( XmppHandler.NOTHING_TO_TRACK_MSG )
else:
- message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
- reply(message_builder, message)
+ tracker = Tracker()
+ subscription = tracker.track(message.sender, message.body)
+ if subscription:
+ message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
+ else:
+ message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
+ reply(message_builder, message)
return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
- message_builder.add('No subscriptions')
+ message_builder.add('You are not tracking anything. To track when a word or phrase appears in Buzz, enter: track <thing of interest>')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
message_body = message.body[len(XmppHandler.POST_CMD):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
a2606aded8e744197e167e88d010256d9749cd88
|
Some attempts to add support for track_command. In meantime I'm getting internal server errors against the following code -- looks to be a transient error:
|
diff --git a/functional_tests.py b/functional_tests.py
index faae696..2fa0a0b 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,261 +1,268 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler, SlashlessCommandMessage
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
+ #self.command,self.arg = SlashlessCommandMessage.extract_command_and_arg_from_string(body)
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
- response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
+ response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
- response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
+ response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
# def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
# arg = 'Some day my prints will come'
-# message = SlashlessCommandMessage(body='%s %s ' % (XmppHandler.TRACK_CMD,arg))
+# message = StubMessage( body='%s %s ' % (XmppHandler.TRACK_CMD,arg) )
+# handler = XmppHandler()
+# subscription = handler.track_command(message=message)
+# self.assertEqual(message.message_to_send, XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (message.arg,subscription.id))
+# # now as this is real, remove it again
+# handler = XmppHandler()
+# handler.untrack_command('%s %s' % (XmppHandler.UNTRACK_CMD, subscription.id))
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
handler = XmppHandler()
handler.track_command(message=message)
self.assertTrue(XmppHandler.TRACK_FAILED_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
handler.help_command(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.commands:
self.assertTrue(command in message.message_to_send, message.message_to_send)
diff --git a/xmpp.py b/xmpp.py
index 8a0b6a1..b7d9eed 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,363 +1,372 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (len(string) == 0) or string.isspace()
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return not Tracker.is_blank(self._extract_search_term(message_body))
def _extract_search_term(self, message_body):
search_term = message_body[len(XmppHandler.TRACK_CMD):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
@staticmethod
def is_number(id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len(XmppHandler.UNTRACK_CMD):]
if not Tracker.is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __init__(self, vars):
#super(xmpp.Message, self).__init__(vars) -- silently fails. #pythonwtf
xmpp.Message.__init__(self, vars)
#TODO make arg and command protected. because __arg and __command are hidden as private
#in xmpp.Message, we have to define our own separate instances of these variables
#even though all we do is change the property accessors for them.
# scm = slashless command message
# luckily __arg and __command aren't used elsewhere in Message but
# we can't guarantee this so it's a bit of a mess
self.__scm_arg = None
self.__scm_command = None
# END TODO
-
- def __ensure_command_and_args_extracted(self):
- """ Take the message and identify the command and argument if there is one.
- In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
- """
- # cache the values.
- if self.__scm_command != None:
- return
+ @staticmethod
+ def extract_command_and_arg_from_string(string):
# match any white space and then a word (cmd)
- # then any white space then everything after that (arg).
- results = re.search(r"\s*(\S*\b)\s*(.*)", self.body)
+ # then any white space then everything after that (arg).
+ command = None
+ arg = None
+
+ results = re.search(r"\s*(\S*\b)\s*(.*)", string)
if results != None:
- self.__scm_command = results.group(1)
- self.__scm_arg = results.group(2)
+ command = results.group(1)
+ arg = results.group(2)
# we didn't find a command and an arg so maybe we'll just find the command
# some commands may not have args
else:
- print "_ensure_command_and_args_extracted: command and args missing for body '%s' so trying just with command" % self.body
- results = re.search(r"\s*(\S*\b)\s*", self.body)
+ results = re.search(r"\s*(\S*\b)\s*", string)
if results != None:
- self.__scm_command = results.group(1)
+ command = results.group(1)
+
+ return [command,arg]
+
+
+ def __ensure_command_and_args_extracted(self):
+ """ Take the message and identify the command and argument if there is one.
+ In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
+ """
+ # cache the values.
+ if self.__scm_command == None:
+ self.__scm_command,self.__scm_arg = SlashlessCommandMessage.extract_command_and_arg_from_string(self.body)
+ print "command = '%s', arg = '%s'" %(self.__scm_command,self.__scm_arg)
# these properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
return self.__scm_arg
class XmppHandler(webapp.RequestHandler):
ABOUT_CMD = 'about'
HELP_CMD = 'help'
LIST_CMD = 'list'
POST_CMD = 'post'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD, UNTRACK_CMD]
#this should be called COMMAND_HELP_MSG_LIST but App Engine requires this specific name!
# make this dependency explicit.
commands = [
'%s Prints out this message' % HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
TRACK_FAILED_MSG = 'Sorry there was a problem with your last track command '
UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood."
+ SUBSCRIPTION_SUCCESS_MSG = 'Tracking: %s with id: %s'
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
print "XmppHandler.__init__"
self.buzz_wrapper = buzz_wrapper
def unhandled_command(self, message):
""" User entered a command that is not recognised. """
message.reply(UNKNOWN_COMMAND_MSG % message )
def message_received(self, message):
""" Take the message we've received and dispatch it to the appropriate command handler
using introspection. E.g. if the command is 'track' it will map to track_command.
Args:
message: Message: The message that was sent by the user.
"""
if message.command and message.command in XmppHandler.PERMITTED_COMMANDS:
handler_name = '%s_command' % (message.command,)
handler = getattr(self, handler_name, None)
if handler:
handler(message)
self.unhandled_command(message)
def handle_exception(self, exception, debug_mode):
"""Called if this handler throws an exception during execution.
Args:
exception: the exception that was thrown
debug_mode: True if the web application is running in debug mode
"""
super(BaseHandler, self).handle_exception(exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply('Oops. Something went wrong.')
def post(self):
- crash-here-please
- print "XmppHandler.post"
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
+ TODO this has no test coverage
"""
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
super(xmpp_handlers.CommandHandler, self).handle_exception(exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply('Oops. Something went wrong.')
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(self.commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
- message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
+ message_builder.add( XmppHandler.SUBSCRIPTION_SUCCESS_MSG % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
+ return subscription
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
message_body = message.body[len(XmppHandler.POST_CMD):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
87026af39c2637de05b784bfc2db7ea46ce25673
|
SlashlessCommandMessageTest unit test created for new subclass of xmpp.Message.
|
diff --git a/functional_tests.py b/functional_tests.py
index 49c120b..faae696 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,256 +1,261 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
-from xmpp import Tracker, XmppHandler
+from xmpp import Tracker, XmppHandler, SlashlessCommandMessage
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
+# def test_track_command_succeeds_for_varying_combinations_of_whitespace(self):
+# arg = 'Some day my prints will come'
+# message = SlashlessCommandMessage(body='%s %s ' % (XmppHandler.TRACK_CMD,arg))
+
+
def test_track_command_fails_for_missing_term(self):
message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
handler = XmppHandler()
handler.track_command(message=message)
self.assertTrue(XmppHandler.TRACK_FAILED_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
handler.help_command(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.commands:
self.assertTrue(command in message.message_to_send, message.message_to_send)
diff --git a/xmpp.py b/xmpp.py
index b631b76..8a0b6a1 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,342 +1,363 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
"""
return (len(string) == 0) or string.isspace()
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return not Tracker.is_blank(self._extract_search_term(message_body))
def _extract_search_term(self, message_body):
search_term = message_body[len(XmppHandler.TRACK_CMD):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
- re
return None
@staticmethod
def is_number(id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len(XmppHandler.UNTRACK_CMD):]
if not Tracker.is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
+ def __init__(self, vars):
+ #super(xmpp.Message, self).__init__(vars) -- silently fails. #pythonwtf
+ xmpp.Message.__init__(self, vars)
+
+ #TODO make arg and command protected. because __arg and __command are hidden as private
+ #in xmpp.Message, we have to define our own separate instances of these variables
+ #even though all we do is change the property accessors for them.
+ # scm = slashless command message
+ # luckily __arg and __command aren't used elsewhere in Message but
+ # we can't guarantee this so it's a bit of a mess
+ self.__scm_arg = None
+ self.__scm_command = None
+ # END TODO
+
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
- """
-
+ """
# cache the values.
- if self.__arg != None:
+ if self.__scm_command != None:
return
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
- results = re.search(r"\s(\S*\b)\s*(.*)", self.__body)
- self.__command = results.group(1)
- self.__arg = results.group(2)
+ results = re.search(r"\s*(\S*\b)\s*(.*)", self.body)
+ if results != None:
+ self.__scm_command = results.group(1)
+ self.__scm_arg = results.group(2)
+
+ # we didn't find a command and an arg so maybe we'll just find the command
+ # some commands may not have args
+ else:
+ print "_ensure_command_and_args_extracted: command and args missing for body '%s' so trying just with command" % self.body
+ results = re.search(r"\s*(\S*\b)\s*", self.body)
+ if results != None:
+ self.__scm_command = results.group(1)
+ # these properties are redefined from that defined in xmpp.Message
@property
def command(self):
self.__ensure_command_and_args_extracted()
- #return super(xmpp.Message, self)
- return self.__command
+ return self.__scm_command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
- #return super(xmpp.Message, self)
- return self.__arg
+ return self.__scm_arg
-class SlashlessCommandHandlerMixin(xmpp_handlers.CommandHandlerMixin):
- """A command handler for XMPP bots that does not require a slash char '/' at beginning
- This makes the most sense when you're implementing a pure bot -- there's no context switch.
- TODO to do this right would mean overriding xmpp.Message.command as this code is now
- used but overridden.
- """
-
- def message_received(self, message):
- """Called when a message is sent to the XMPP bot.
- Args:
- message: Message: The message that was sent by the user.
- """
- if message.command:
- handler_name = '%s_command' % (message.command,)
- handler = getattr(self, handler_name, None)
- if handler:
- handler(message)
- else:
- self.unhandled_command(message)
-
-
-class XmppHandler(SlashlessCommandHandlerMixin, webapp.RequestHandler):
+class XmppHandler(webapp.RequestHandler):
+ ABOUT_CMD = 'about'
HELP_CMD = 'help'
- TRACK_CMD = 'track'
- UNTRACK_CMD = 'untrack'
LIST_CMD = 'list'
- ABOUT_CMD = 'about'
POST_CMD = 'post'
+ TRACK_CMD = 'track'
+ UNTRACK_CMD = 'untrack'
+
+ PERMITTED_COMMANDS = [ABOUT_CMD,HELP_CMD,LIST_CMD,POST_CMD,TRACK_CMD, UNTRACK_CMD]
+ #this should be called COMMAND_HELP_MSG_LIST but App Engine requires this specific name!
+ # make this dependency explicit.
commands = [
'%s Prints out this message' % HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
- TRACK_FAILED_MSG = 'Sorry there was a problem with your last track command '
-
+ TRACK_FAILED_MSG = 'Sorry there was a problem with your last track command '
+ UNKNOWN_COMMAND_MSG = "Sorry, '%s' was not understood."
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
print "XmppHandler.__init__"
self.buzz_wrapper = buzz_wrapper
+ def unhandled_command(self, message):
+ """ User entered a command that is not recognised. """
+ message.reply(UNKNOWN_COMMAND_MSG % message )
+
+ def message_received(self, message):
+ """ Take the message we've received and dispatch it to the appropriate command handler
+ using introspection. E.g. if the command is 'track' it will map to track_command.
+ Args:
+ message: Message: The message that was sent by the user.
+ """
+ if message.command and message.command in XmppHandler.PERMITTED_COMMANDS:
+ handler_name = '%s_command' % (message.command,)
+ handler = getattr(self, handler_name, None)
+ if handler:
+ handler(message)
+ self.unhandled_command(message)
+
+
def handle_exception(self, exception, debug_mode):
"""Called if this handler throws an exception during execution.
Args:
exception: the exception that was thrown
debug_mode: True if the web application is running in debug mode
"""
super(BaseHandler, self).handle_exception(exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply('Oops. Something went wrong.')
def post(self):
- sdfsdf
+ crash-here-please
print "XmppHandler.post"
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
super(xmpp_handlers.CommandHandler, self).handle_exception(exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply('Oops. Something went wrong.')
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(self.commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
message_body = message.body[len(XmppHandler.POST_CMD):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
ea54fd94fe8b0969c22afb2ffffe5f3dce7fba1f
|
Fixed broken test -- problem with my understanding of what one of the tests was testing. Still minimal coverage over handle_track.
|
diff --git a/functional_tests.py b/functional_tests.py
index f9f84d4..49c120b 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,256 +1,256 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
def test_admin_profile_link_is_on_front_page(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_track_command_fails_for_missing_term(self):
- message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
+ message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
handler = XmppHandler()
handler.track_command(message=message)
- self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
+ self.assertTrue(XmppHandler.TRACK_FAILED_MSG in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
- message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
+ message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
- expected_item = ' some message'
+ expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
handler.help_command(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.commands:
self.assertTrue(command in message.message_to_send, message.message_to_send)
diff --git a/xmpp.py b/xmpp.py
index a8d1504..b631b76 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,344 +1,342 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
@staticmethod
def is_blank(string):
""" utility function for determining whether a string is blank (just whitespace)
- TODO is there already a utility for this? I'm assuming so but couldn't find one
"""
- result = re.search( r"(\s*)", string)
- if result != None:
- print "is_blank: group(0) = '%s'" % result.group(0)
- return len(result.group(0)) == len(string)
-
+ return (len(string) == 0) or string.isspace()
+
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
- return self._extract_search_term(message_body) != ''
+ return not Tracker.is_blank(self._extract_search_term(message_body))
def _extract_search_term(self, message_body):
- search_term = message_body[len('/track'):]
+ search_term = message_body[len(XmppHandler.TRACK_CMD):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
+ re
return None
- def _is_number(self, id):
+ @staticmethod
+ def is_number(id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len(XmppHandler.UNTRACK_CMD):]
- if not self._is_number(id):
+ if not Tracker.is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if self.__arg != None:
return
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
results = re.search(r"\s(\S*\b)\s*(.*)", self.__body)
self.__command = results.group(1)
self.__arg = results.group(2)
@property
def command(self):
self.__ensure_command_and_args_extracted()
#return super(xmpp.Message, self)
return self.__command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
#return super(xmpp.Message, self)
return self.__arg
class SlashlessCommandHandlerMixin(xmpp_handlers.CommandHandlerMixin):
"""A command handler for XMPP bots that does not require a slash char '/' at beginning
This makes the most sense when you're implementing a pure bot -- there's no context switch.
TODO to do this right would mean overriding xmpp.Message.command as this code is now
used but overridden.
"""
def message_received(self, message):
"""Called when a message is sent to the XMPP bot.
Args:
message: Message: The message that was sent by the user.
"""
if message.command:
handler_name = '%s_command' % (message.command,)
handler = getattr(self, handler_name, None)
if handler:
handler(message)
else:
self.unhandled_command(message)
class XmppHandler(SlashlessCommandHandlerMixin, webapp.RequestHandler):
HELP_CMD = 'help'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
LIST_CMD = 'list'
ABOUT_CMD = 'about'
POST_CMD = 'post'
commands = [
'%s Prints out this message' % HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
+
+ TRACK_FAILED_MSG = 'Sorry there was a problem with your last track command '
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
print "XmppHandler.__init__"
self.buzz_wrapper = buzz_wrapper
def handle_exception(self, exception, debug_mode):
"""Called if this handler throws an exception during execution.
Args:
exception: the exception that was thrown
debug_mode: True if the web application is running in debug mode
"""
super(BaseHandler, self).handle_exception(exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply('Oops. Something went wrong.')
def post(self):
sdfsdf
print "XmppHandler.post"
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
return
self.message_received(self.xmpp_message)
def handle_exception(self, exception, debug_mode):
super(xmpp_handlers.CommandHandler, self).handle_exception(exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply('Oops. Something went wrong.')
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None):
- sdf
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(self.commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
- message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
+ message_builder.add('%s <%s>' % (XmppHandler.TRACK_FAILED_MSG, message.body))
reply(message_builder, message)
def untrack_command(self, message=None):
- sdf
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
- message_body = message.body[len('/post'):]
+ message_body = message.body[len(XmppHandler.POST_CMD):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
b8d249d28525df297ed2eb7d43d43977a5379ea7
|
Adding test coverage for track_command and function is_blank that's subsequently used in track_command for more robust checking of blank commands.
|
diff --git a/functional_tests.py b/functional_tests.py
index 12d504b..399db2d 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,223 +1,229 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
+ def test_track_command_fails_for_missing_term(self):
+ message = StubMessage(body='%s ' % XmppHandler.TRACK_CMD)
+ handler = XmppHandler()
+ handler.track_command(message=message)
+ self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
+
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
\ No newline at end of file
diff --git a/tracker_tests.py b/tracker_tests.py
index 45e1dc5..39f8aee 100644
--- a/tracker_tests.py
+++ b/tracker_tests.py
@@ -1,146 +1,157 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from xmpp import Subscription, Tracker, XmppHandler
import pshb
import settings
class StubHubSubscriber(pshb.HubSubscriber):
def subscribe(self, url, hub, callback_url):
self.callback_url = callback_url
def unsubscribe(self, url, hub, callback_url):
self.callback_url = callback_url
class TrackerTest(unittest.TestCase):
+ def test_is_blank_works_on_blank_strings(self):
+ self.assertTrue(Tracker.is_blank(" "))
+ self.assertTrue(Tracker.is_blank(" ")) # has a tab in it
+ self.assertTrue(Tracker.is_blank(""))
+
+ def test_is_blank_works_on_nonblank_strings(self):
+ self.assertFalse(Tracker.is_blank(" a"))
+ self.assertFalse(Tracker.is_blank("adf "))
+ self.assertFalse(Tracker.is_blank(" adfas "))
+ self.assertFalse(Tracker.is_blank("daf-sa"))
+
def test_tracker_rejects_empty_search_term(self):
sender = '[email protected]'
body = XmppHandler.TRACK_CMD
tracker = Tracker()
self.assertEquals(None, tracker.track(sender, body))
def test_tracker_rejects_padded_empty_string(self):
sender = '[email protected]'
body = '%s ' % XmppHandler.TRACK_CMD
tracker = Tracker()
self.assertEquals(None, tracker.track(sender, body))
def test_tracker_accepts_valid_string(self):
sender = '[email protected]'
search_term='somestring'
body = '%s %s' % (XmppHandler.TRACK_CMD, search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
expected_callback_url = 'http://%s.appspot.com/posts/%s/%s' % (settings.APP_NAME, sender, search_term)
expected_subscription = Subscription(url='https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, search_term=search_term, callback_url=expected_callback_url)
actual_subscription = tracker.track(sender, body)
self.assertEquals(expected_subscription.url, actual_subscription.url)
self.assertEquals(expected_subscription.search_term, actual_subscription.search_term)
def test_tracker_extracts_correct_search_term(self):
search_term = 'somestring'
body = '%s %s' % (XmppHandler.TRACK_CMD, search_term)
tracker = Tracker()
self.assertEquals(search_term, tracker._extract_search_term(body))
def test_tracker_builds_correct_pshb_url(self):
search_term = 'somestring'
tracker = Tracker()
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, tracker._build_subscription_url(search_term))
def test_tracker_url_encodes_search_term(self):
search_term = 'some string'
tracker = Tracker()
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=' + 'some%20string', tracker._build_subscription_url(search_term))
def _delete_all_subscriptions(self):
for subscription in Subscription.all().fetch(100):
subscription.delete()
def test_tracker_saves_subscription(self):
self._delete_all_subscriptions()
self.assertEquals(0, len(Subscription.all().fetch(100)))
sender = '[email protected]'
search_term='somestring'
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
tracker = Tracker()
subscription = tracker.track(sender, body)
self.assertEquals(1, len(Subscription.all().fetch(100)))
self.assertEquals(subscription, Subscription.all().fetch(1)[0])
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query(self):
sender = '[email protected]'
search_term='somestring'
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_urlencoded_callback_url(self):
sender = '[email protected]'
search_term='some string'
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query_without_xmpp_client_identifier(self):
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_rejects_invalid_id_for_untracking(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
body = '%s 1' % XmppHandler.UNTRACK_CMD
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.untrack(sender, body)
self.assertEquals(None, subscription)
def test_tracker_untracks_valid_id(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
track_subscription = tracker.track(sender, body)
body = '%s %s' % (XmppHandler.UNTRACK_CMD,track_subscription.id())
untrack_subscription = tracker.untrack(sender, body)
self.assertEquals(track_subscription, untrack_subscription)
self.assertFalse(Subscription.exists(track_subscription.id()))
self.assertEquals('http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, track_subscription.id()), hub_subscriber.callback_url)
diff --git a/xmpp.py b/xmpp.py
index 2a5b89b..61b7a5b 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,313 +1,338 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
+from google.appengine.ext import webapp
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
+ @staticmethod
+ def is_blank(string):
+ """ utility function for determining whether a string is blank (just whitespace)
+ TODO is there already a utility for this? I'm assuming so but couldn't find one
+ """
+ result = re.search( r"(\s*)", string)
+ if result != None:
+ print "is_blank: group(0) = '%s'" % result.group(0)
+ return len(result.group(0)) == len(string)
+
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len(XmppHandler.UNTRACK_CMD):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SlashlessCommandMessage(xmpp.Message):
""" The default message format with GAE xmpp identifies the command as the first non whitespace word.
The argument is whatever occurs after that.
Design notes: it uses re for tokenization which is a step up
from how Message works (that expects a single space character)
"""
def __ensure_command_and_args_extracted(self):
""" Take the message and identify the command and argument if there is one.
In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
"""
# cache the values.
if self.__arg != None:
return
# match any white space and then a word (cmd)
# then any white space then everything after that (arg).
results = re.search(r"\s(\S*\b)\s*(.*)", self.__body)
self.__command = results.group(1)
self.__arg = results.group(2)
@property
def command(self):
self.__ensure_command_and_args_extracted()
#return super(xmpp.Message, self)
return self.__command
@property
def arg(self):
self.__ensure_command_and_args_extracted()
#return super(xmpp.Message, self)
return self.__arg
class SlashlessCommandHandlerMixin(xmpp_handlers.CommandHandlerMixin):
"""A command handler for XMPP bots that does not require a slash char '/' at beginning
This makes the most sense when you're implementing a pure bot -- there's no context switch.
TODO to do this right would mean overriding xmpp.Message.command as this code is now
used but overridden.
"""
def message_received(self, message):
"""Called when a message is sent to the XMPP bot.
Args:
message: Message: The message that was sent by the user.
"""
if message.command:
handler_name = '%s_command' % (message.command,)
handler = getattr(self, handler_name, None)
if handler:
handler(message)
else:
self.unhandled_command(message)
-class XmppHandler(SlashlessCommandHandlerMixin, xmpp_handlers.BaseHandler):
+class XmppHandler(SlashlessCommandHandlerMixin, webapp.RequestHandler):
HELP_CMD = 'help'
TRACK_CMD = 'track'
UNTRACK_CMD = 'untrack'
LIST_CMD = 'list'
ABOUT_CMD = 'about'
POST_CMD = 'post'
commands = [
'%s Prints out this message' % HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
print "XmppHandler.__init__"
self.buzz_wrapper = buzz_wrapper
+ def handle_exception(self, exception, debug_mode):
+ """Called if this handler throws an exception during execution.
+
+ Args:
+ exception: the exception that was thrown
+ debug_mode: True if the web application is running in debug mode
+ """
+ super(BaseHandler, self).handle_exception(exception, debug_mode)
+ if self.xmpp_message:
+ self.xmpp_message.reply('Oops. Something went wrong.')
+
def post(self):
+ sdfsdf
print "XmppHandler.post"
""" Redefines post to create a message from our new SlashlessCommandMessage.
TODO xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
overridden this will avoid the code duplicated below
"""
try:
# CHANGE this is the only bit that has changed from xmpp_handlers.Message
self.xmpp_message = SlashlessCommandMessage(self.request.POST)
# END CHANGE
except xmpp.InvalidMessageError, e:
logging.error("Invalid XMPP request: Missing required field %s", e[0])
return
self.message_received(self.xmpp_message)
def help_command(self, message=None):
+ sdf
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
+ sdf
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
message_body = message.body[len('/post'):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
020d83e192282ac47b02fc842f402ec6ab0177e0
|
Added button with link to Admin's profile page
|
diff --git a/app.yaml b/app.yaml
index 522fb2a..e30bf45 100644
--- a/app.yaml
+++ b/app.yaml
@@ -1,15 +1,15 @@
-application: favedby
+application: buzzchatbot
version: 1
runtime: python
api_version: 1
handlers:
- url: /css
static_dir: css
- url: /images
static_dir: images
- url: /.*
script: main.py
inbound_services:
- xmpp_message
\ No newline at end of file
diff --git a/front_page.html b/front_page.html
index 84fd818..0464acc 100644
--- a/front_page.html
+++ b/front_page.html
@@ -1,37 +1,40 @@
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html> <head>
<title>Buzz Chat Bot - {{ jabber_id }}</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
</head>
<body>
<h1>Welcome to the Buzz Chat Bot - {{ jabber_id }}</h1>
<h3>What does it do?</h3>
<dl>At the moment it lets you ask for:
{% for command in commands %}
<li>{{ command }}</li>
{% endfor %}
</dl>
<h3>Why does it exist?</h3>
<dl><a href="http://jaiku.jaiku.com/">Jaiku</a> and <a href="http://friendfeed.com/">Friendfeed</a> have shown that chat interfaces have a number of advantages over web interfaces:
<li>they're always on</li>
<li>they're quicker since you can't beat the latency of just switching over to your chat client.</li>
<li>they're transient so you don't feel inundated if you track lots of keywords or see lots of posts because they all just flow by</li>
<li>they encourage <a href="http://www.designingsocialinterfaces.com/patterns/Statuscasting">statuscasting</a> which makes for a more conversational experience</li>
<li>they allow people and brands to conveniently track keywords without having to learn how <a href="http://pubsubhubbub.appspot.com/">PuSH</a> works</li>
</dl>
<h3>Usage: How to use the bot</h3>
<ol>
<li><a href="/start_dance">Give the bot access to your Buzz account via the magic of OAuth</a></li>
<li>Add the bot: {{ jabber_id }} to your Chat or IM client</li>
<li>Ask the bot for help by typing <i>{{help_command}}</i></li>
</ol>
<hr></hr>
+<a target="_blank" title="Follow me on Google Buzz" class="google-buzz-button" href="{{ admin_url }}" data-button-style="follow">
+ Follow me on Buzz</a>
+<script type="text/javascript" src="http://www.google.com/buzz/api/button.js"></script>
</body> </html>
diff --git a/functional_tests.py b/functional_tests.py
index bc8e838..985b41b 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,244 +1,250 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
APPLICATION = main.application
def test_front_page_can_be_viewed_without_being_logged_in(self):
response = self.get(settings.FRONT_PAGE_HANDLER_URL)
self.assertOK(response)
response.mustcontain("<title>Buzz Chat Bot")
response.mustcontain(settings.APP_NAME)
+ def test_admin_profile_link_is_on_front_page(self):
+ response = self.get(settings.FRONT_PAGE_HANDLER_URL)
+
+ self.assertOK(response)
+ response.mustcontain('href="%s"' % settings.ADMIN_PROFILE_URL)
+
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
handler.help_command(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.commands:
self.assertTrue(command in message.message_to_send, message.message_to_send)
diff --git a/main.py b/main.py
index 9931bfb..cd7a9d8 100644
--- a/main.py
+++ b/main.py
@@ -1,124 +1,125 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
import oauth_handlers
import os
import settings
import xmpp
import pshb
import simple_buzz_wrapper
class ProfileViewingHandler(webapp.RequestHandler):
@login_required
def get(self):
user_token = oauth_handlers.UserToken.get_current_user_token()
buzz_wrapper = simple_buzz_wrapper.SimpleBuzzWrapper(user_token)
user_profile_data = buzz_wrapper.get_profile()
template_values = {'user_profile_data': user_profile_data, 'access_token': user_token.access_token_string}
path = os.path.join(os.path.dirname(__file__), 'profile.html')
self.response.out.write(template.render(path, template_values))
class FrontPageHandler(webapp.RequestHandler):
def get(self):
template_values = {'commands' : xmpp.XmppHandler.commands,
'help_command' : xmpp.XmppHandler.HELP_CMD,
- 'jabber_id' : '%[email protected]' % settings.APP_NAME}
+ 'jabber_id' : '%[email protected]' % settings.APP_NAME,
+ 'admin_url' : settings.ADMIN_PROFILE_URL}
path = os.path.join(os.path.dirname(__file__), 'front_page.html')
self.response.out.write(template.render(path, template_values))
class PostsHandler(webapp.RequestHandler):
def _get_subscription(self):
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
return subscription
def get(self):
"""Show all the resources in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.debug("New content: %s" % self.request.body)
id = self.request.get('id')
# If this is a hub challenge
if self.request.get('hub.challenge'):
# If this subscription exists
mode = self.request.get('hub.mode')
topic = self.request.get('hub.topic')
if mode == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
elif mode == "unsubscribe" and not xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
else:
self.response.set_status(404)
self.response.out.write("Challenge failed")
logging.info("Challenge failed for feed: %s" % topic)
# Once a challenge has been issued there's no point in returning anything other than challenge passed or failed
return
def post(self):
"""Create a new resource in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.debug("New content: %s" % self.request.body)
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
if not subscription:
self.response.set_status(404)
self.response.out.write("No such subscription")
logging.warning('No subscription for %s' % id)
return
subscriber = subscription.subscriber
search_term = subscription.search_term
parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB)
url = parser.extractFeedUrl()
if not parser.dataValid():
parser.logErrors()
self.response.out.write("Bad entries: %s" % parser.data)
return
else:
posts = parser.extractPosts()
logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url))
xmpp.send_posts(posts, subscriber, search_term)
self.response.set_status(200)
application = webapp.WSGIApplication([
(settings.FRONT_PAGE_HANDLER_URL, FrontPageHandler),
(settings.PROFILE_HANDLER_URL, ProfileViewingHandler),
('/start_dance', oauth_handlers.DanceStartingHandler),
('/finish_dance', oauth_handlers.DanceFinishingHandler),
('/delete_tokens', oauth_handlers.TokenDeletionHandler),
('/posts', PostsHandler),
('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
diff --git a/settings.py b/settings.py
index 76b5206..9723e8b 100644
--- a/settings.py
+++ b/settings.py
@@ -1,53 +1,54 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-APP_NAME = "favedby"
+APP_NAME = 'buzzchatbot'
+ADMIN_PROFILE_URL = 'http://profiles.google.com/adewale'
#PSHB settings
# This is the token that will act as a shared secret to verify that this application is the one that registered the given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
# OAuth consumer key and secret - you should change these to 'anonymous' unless you really are buzzchatbot.appspot.com
# Alternatively you could go here: https://www.google.com/accounts/ManageDomains and register your instance so that you'll get your own consumer key and consumer secret
#CONSUMER_KEY = 'buzzchatbot.appspot.com'
#CONSUMER_SECRET = 'tcw1rCMgLVY556Y0Q4rW/RnK'
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
# OAuth callback URL
CALLBACK_URL = 'http://%s.appspot.com/finish_dance' % APP_NAME
PROFILE_HANDLER_URL = '/profile'
FRONT_PAGE_HANDLER_URL = '/'
# Installation specific config ends.
|
adewale/Buzz-Chat-Bot
|
0eb0f86513ad13c0fe338ccb0f61fd29cf20fb41
|
Added lame CSS drop-shadow to titles
|
diff --git a/css/style.css b/css/style.css
index 0997654..61e64a7 100755
--- a/css/style.css
+++ b/css/style.css
@@ -1,39 +1,42 @@
body {
/*background-color: #D5F1FF;original*/
/*background-color: #0099ff;warm blue*/
/*background-color: #9966cc;rich almost velvety purple*/
/*background-color: #339999;teal*/
/*background-color: #D4D0C8;smooth windows grey*/
/*background-color: #cc3300;clashing red*/
/*background-color: #ff9900;crass orange*/
/*background-color: #99cc33;Rich green*/
/*background-color: #EEEEE0;*/
/*background-color: #738059;*/
/*background-color: #B8CC8F;*/
background-color: #738059;
/*font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;*/
font-family: "Trebuchet MS", "Times New Roman", Serif;
}
+h1 {
+ border-width: 0px;
+ color: #000000;
+ padding: 5px;
+ margin: 5px 5px 5px 5px;
+ text-shadow: 2px 2px 2px #aaa;
+}
+
h3 {
/* Reduce the amount of space after section headings */
margin-bottom: -15px;
}
-h6 {
- font-size: 7pt;
- font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
-}
-
p {
- color: #000000;
- background-color: #ffffff;
+ color: #000000;
+ background-color: #ffffff;
}
a {
- color:#000000;
+ color:#000000;
}
a:hover {
- text-decoration: none;
+ text-decoration: none;
}
|
adewale/Buzz-Chat-Bot
|
e37226bf00a2b7e01cda3e887f60e130052f9d1c
|
Tidied up CSS. Added test to verify that people can now see the front-page without needing to be logged in. Extracted out some hardcoded references to URLs so they're now in the settings module. Tidied up the profile page a little.
|
diff --git a/app.yaml b/app.yaml
index d827c65..522fb2a 100644
--- a/app.yaml
+++ b/app.yaml
@@ -1,15 +1,15 @@
-application: kiwibuzzer
+application: favedby
version: 1
runtime: python
api_version: 1
handlers:
- url: /css
static_dir: css
- url: /images
static_dir: images
- url: /.*
script: main.py
inbound_services:
- xmpp_message
\ No newline at end of file
diff --git a/css/style.css b/css/style.css
index 1e26a91..0997654 100755
--- a/css/style.css
+++ b/css/style.css
@@ -1,103 +1,39 @@
body {
/*background-color: #D5F1FF;original*/
/*background-color: #0099ff;warm blue*/
/*background-color: #9966cc;rich almost velvety purple*/
/*background-color: #339999;teal*/
/*background-color: #D4D0C8;smooth windows grey*/
/*background-color: #cc3300;clashing red*/
/*background-color: #ff9900;crass orange*/
/*background-color: #99cc33;Rich green*/
- /*background-color: #EEEEE0;*/
- /*background-color: #738059;*/
- /*background-color: #B8CC8F;*/
+ /*background-color: #EEEEE0;*/
+ /*background-color: #738059;*/
+ /*background-color: #B8CC8F;*/
background-color: #738059;
/*font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;*/
font-family: "Trebuchet MS", "Times New Roman", Serif;
}
-th {
- background-color: #B8CC8F;
- border-width: 1px;
- border-style: solid;
- border-color: #000000;
- border-top: 0px;
- border-right: 0px;
- border-left: 0px;
+h3 {
+ /* Reduce the amount of space after section headings */
+ margin-bottom: -15px;
}
h6 {
font-size: 7pt;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
}
p {
color: #000000;
background-color: #ffffff;
}
a {
- color:#336699;
-}
-
-a:hover {
- text-decoration: underline !important;
- color: blue !important;
-}
-
-
-.menuItem {
- background: #ffffff;
- text-align: center;
- border-width: 1px;
- border-style: solid;
- border-color: #000000;
-}
-
-.sitelink {
- color: #000000;
-}
-
-.whatsNew {
- font-style: italic;
- font-weight: bold;
+ color:#000000;
}
-.mainText {
- margin-left: 5px;
- margin-right: 5px;
- margin-bottom: 5px;
-}
-
-.borderedTable {
- border-width: 1px;
- border-style: solid;
- border-color: #000000;
-}
-
-.borderedNavTable {
- border-width: 1px;
- border-style: solid;
- border-color: #000000;
- background-color:#ccccc0;
-}
-
-
-/*
-Custom list classes begin here
-*/
-.listHead {
- font-weight: bold;
- border-width: 1px;
- border-style: solid;
- border-color: #000000;
- border-top:1px;
- border-left:1px;
- border-right:1px;
- display:block;
- margin-top: 20px;
+a:hover {
+ text-decoration: none;
}
-
-.listItem {
- display: block;
- margin-left: 10px;
-}
\ No newline at end of file
diff --git a/front_page.html b/front_page.html
new file mode 100644
index 0000000..84fd818
--- /dev/null
+++ b/front_page.html
@@ -0,0 +1,37 @@
+<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
+<html> <head>
+<title>Buzz Chat Bot - {{ jabber_id }}</title>
+<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
+</head>
+
+<body>
+<h1>Welcome to the Buzz Chat Bot - {{ jabber_id }}</h1>
+
+
+<h3>What does it do?</h3>
+<dl>At the moment it lets you ask for:
+{% for command in commands %}
+<li>{{ command }}</li>
+{% endfor %}
+</dl>
+
+
+<h3>Why does it exist?</h3>
+<dl><a href="http://jaiku.jaiku.com/">Jaiku</a> and <a href="http://friendfeed.com/">Friendfeed</a> have shown that chat interfaces have a number of advantages over web interfaces:
+<li>they're always on</li>
+<li>they're quicker since you can't beat the latency of just switching over to your chat client.</li>
+<li>they're transient so you don't feel inundated if you track lots of keywords or see lots of posts because they all just flow by</li>
+<li>they encourage <a href="http://www.designingsocialinterfaces.com/patterns/Statuscasting">statuscasting</a> which makes for a more conversational experience</li>
+<li>they allow people and brands to conveniently track keywords without having to learn how <a href="http://pubsubhubbub.appspot.com/">PuSH</a> works</li>
+</dl>
+
+<h3>Usage: How to use the bot</h3>
+<ol>
+ <li><a href="/start_dance">Give the bot access to your Buzz account via the magic of OAuth</a></li>
+ <li>Add the bot: {{ jabber_id }} to your Chat or IM client</li>
+ <li>Ask the bot for help by typing <i>{{help_command}}</i></li>
+</ol>
+
+
+<hr></hr>
+</body> </html>
diff --git a/functional_tests.py b/functional_tests.py
index 1e0b380..bc8e838 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,234 +1,244 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
+class FrontPageHandlerFunctionalTest(FunctionalTestCase, unittest.TestCase):
+ APPLICATION = main.application
+ def test_front_page_can_be_viewed_without_being_logged_in(self):
+ response = self.get(settings.FRONT_PAGE_HANDLER_URL)
+
+ self.assertOK(response)
+ response.mustcontain("<title>Buzz Chat Bot")
+ response.mustcontain(settings.APP_NAME)
+
+
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
def test_help_command_lists_available_commands(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
handler.help_command(message=message)
self.assertTrue(len(message.message_to_send) > 0)
for command in handler.commands:
self.assertTrue(command in message.message_to_send, message.message_to_send)
diff --git a/main.py b/main.py
index 923c476..9931bfb 100644
--- a/main.py
+++ b/main.py
@@ -1,115 +1,124 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
import oauth_handlers
import os
import settings
import xmpp
import pshb
import simple_buzz_wrapper
class ProfileViewingHandler(webapp.RequestHandler):
@login_required
def get(self):
user_token = oauth_handlers.UserToken.get_current_user_token()
buzz_wrapper = simple_buzz_wrapper.SimpleBuzzWrapper(user_token)
user_profile_data = buzz_wrapper.get_profile()
template_values = {'user_profile_data': user_profile_data, 'access_token': user_token.access_token_string}
path = os.path.join(os.path.dirname(__file__), 'profile.html')
self.response.out.write(template.render(path, template_values))
+class FrontPageHandler(webapp.RequestHandler):
+ def get(self):
+ template_values = {'commands' : xmpp.XmppHandler.commands,
+ 'help_command' : xmpp.XmppHandler.HELP_CMD,
+ 'jabber_id' : '%[email protected]' % settings.APP_NAME}
+ path = os.path.join(os.path.dirname(__file__), 'front_page.html')
+ self.response.out.write(template.render(path, template_values))
+
class PostsHandler(webapp.RequestHandler):
def _get_subscription(self):
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
return subscription
def get(self):
"""Show all the resources in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.debug("New content: %s" % self.request.body)
id = self.request.get('id')
# If this is a hub challenge
if self.request.get('hub.challenge'):
# If this subscription exists
mode = self.request.get('hub.mode')
topic = self.request.get('hub.topic')
if mode == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
elif mode == "unsubscribe" and not xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
else:
self.response.set_status(404)
self.response.out.write("Challenge failed")
logging.info("Challenge failed for feed: %s" % topic)
# Once a challenge has been issued there's no point in returning anything other than challenge passed or failed
return
def post(self):
"""Create a new resource in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.debug("New content: %s" % self.request.body)
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
if not subscription:
self.response.set_status(404)
self.response.out.write("No such subscription")
logging.warning('No subscription for %s' % id)
return
subscriber = subscription.subscriber
search_term = subscription.search_term
parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB)
url = parser.extractFeedUrl()
if not parser.dataValid():
parser.logErrors()
self.response.out.write("Bad entries: %s" % parser.data)
return
else:
posts = parser.extractPosts()
logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url))
xmpp.send_posts(posts, subscriber, search_term)
self.response.set_status(200)
application = webapp.WSGIApplication([
- ('/', oauth_handlers.WelcomeHandler),
- ('/delete_tokens', oauth_handlers.TokenDeletionHandler),
+ (settings.FRONT_PAGE_HANDLER_URL, FrontPageHandler),
+ (settings.PROFILE_HANDLER_URL, ProfileViewingHandler),
+ ('/start_dance', oauth_handlers.DanceStartingHandler),
('/finish_dance', oauth_handlers.DanceFinishingHandler),
- ('/profile', ProfileViewingHandler),
+ ('/delete_tokens', oauth_handlers.TokenDeletionHandler),
('/posts', PostsHandler),
('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
diff --git a/oauth_handlers.py b/oauth_handlers.py
index fa525c9..26e6848 100644
--- a/oauth_handlers.py
+++ b/oauth_handlers.py
@@ -1,126 +1,126 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import users
import buzz_gae_client
import logging
import os
import settings
class UserToken(db.Model):
# The user_id is the key_name so we don't have to make it an explicit property
request_token_string = db.StringProperty()
access_token_string = db.StringProperty()
email_address = db.StringProperty()
def get_request_token(self):
"Returns request token as a dictionary of tokens including oauth_token, oauth_token_secret and oauth_callback_confirmed."
return eval(self.request_token_string)
def set_access_token(self, access_token):
access_token_string = repr(access_token)
self.access_token_string = access_token_string
def get_access_token(self):
"Returns access token as a dictionary of tokens including consumer_key, consumer_secret, oauth_token and oauth_token_secret"
return eval(self.access_token_string)
@staticmethod
def create_user_token(request_token):
user = users.get_current_user()
user_id = user.user_id()
request_token_string = repr(request_token)
# TODO(ade) Support users who sign in to AppEngine with a federated identity aka OpenId
email = user.email()
logging.info('Creating user token: key_name: %s request_token_string: %s email_address: %s' % (
user_id, request_token_string, email))
return UserToken(key_name=user_id, request_token_string=request_token_string, access_token_string='',
email_address=email)
@staticmethod
def get_current_user_token():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
return user_token
@staticmethod
def access_token_exists():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
logging.info('user_token: %s' % user_token)
return user_token and user_token.access_token_string
@staticmethod
def find_by_email_address(email_address):
user_tokens = UserToken.gql('WHERE email_address = :1', email_address).fetch(1)
if user_tokens:
return user_tokens[0] # The result of the query is a list
else:
return None
-class WelcomeHandler(webapp.RequestHandler):
+class DanceStartingHandler(webapp.RequestHandler):
@login_required
def get(self):
logging.info("Request body %s" % self.request.body)
template_values = {"jabber_id": ("%[email protected]" % settings.APP_NAME)}
if UserToken.access_token_exists():
template_values['access_token_exists'] = 'true'
else:
# Generate the request token
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
request_token = client.get_request_token(settings.CALLBACK_URL)
# Create the request token and associate it with the current user
user_token = UserToken.create_user_token(request_token)
UserToken.put(user_token)
authorisation_url = client.generate_authorisation_url(request_token)
logging.info('Authorisation URL is: %s' % authorisation_url)
template_values['destination'] = authorisation_url
- path = os.path.join(os.path.dirname(__file__), 'welcome.html')
+ path = os.path.join(os.path.dirname(__file__), 'start_dance.html')
self.response.out.write(template.render(path, template_values))
class TokenDeletionHandler(webapp.RequestHandler):
def post(self):
user_token = UserToken.get_current_user_token()
UserToken.delete(user_token)
- self.redirect('/')
+ self.redirect(settings.FRONT_PAGE_HANDLER_URL)
class DanceFinishingHandler(webapp.RequestHandler):
def get(self):
logging.info("Request body %s" % self.request.body)
oauth_verifier = self.request.get('oauth_verifier')
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
user_token = UserToken.get_current_user_token()
request_token = user_token.get_request_token()
access_token = client.upgrade_to_access_token(request_token, oauth_verifier)
logging.info('SUCCESS: Received access token.')
user_token.set_access_token(access_token)
UserToken.put(user_token)
logging.debug('Access token was: %s' % user_token.access_token_string)
- self.redirect('/profile')
\ No newline at end of file
+ self.redirect(settings.PROFILE_HANDLER_URL)
\ No newline at end of file
diff --git a/profile.html b/profile.html
index 35056dd..4ed9fad 100644
--- a/profile.html
+++ b/profile.html
@@ -1,21 +1,21 @@
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html> <head>
<title>Buzz Chat Bot</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
</head>
<body>
<div>
<h1>{{ user_profile_data.displayName }}'s settings for the Buzz Chat Bot</h1>
<img src="{{ user_profile_data.photos.1.value }}">
</div>
<hr></hr>
<hr></hr>
<h1>Access Token is: {{ access_token }}</h1>
-<h1>Profile Data: {{ user_profile_data }}</h1>
+<h1>Profile: {{ user_profile_data.aboutMe }}</h1>
<hr></hr>
</body> </html>
diff --git a/settings.py b/settings.py
index a8c276b..76b5206 100644
--- a/settings.py
+++ b/settings.py
@@ -1,52 +1,53 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-APP_NAME = "buzzchatbot"
+APP_NAME = "favedby"
#PSHB settings
# This is the token that will act as a shared secret to verify that this application is the one that registered the given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
# OAuth consumer key and secret - you should change these to 'anonymous' unless you really are buzzchatbot.appspot.com
# Alternatively you could go here: https://www.google.com/accounts/ManageDomains and register your instance so that you'll get your own consumer key and consumer secret
#CONSUMER_KEY = 'buzzchatbot.appspot.com'
#CONSUMER_SECRET = 'tcw1rCMgLVY556Y0Q4rW/RnK'
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
# OAuth callback URL
CALLBACK_URL = 'http://%s.appspot.com/finish_dance' % APP_NAME
-
+PROFILE_HANDLER_URL = '/profile'
+FRONT_PAGE_HANDLER_URL = '/'
# Installation specific config ends.
diff --git a/start_dance.html b/start_dance.html
new file mode 100644
index 0000000..feb5389
--- /dev/null
+++ b/start_dance.html
@@ -0,0 +1,21 @@
+<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
+<html> <head>
+<title>Buzz Chat Bot - {{ jabber_id }}</title>
+<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
+</head>
+
+<body>
+<h1>Control {{ jabber_id }}'s access to your Buzz account</h1>
+
+{% if access_token_exists %}
+<form action="/delete_tokens" method="post">
+<input type="submit" value="Remove the bot's access to your Buzz account"></input>
+</form>
+{% else %}
+<form action="{{ destination }}" method="post">
+<input type="submit" value="Start using the bot by giving it access to your Buzz account"></input>
+</form>
+{% endif %}
+
+<hr></hr>
+</body> </html>
diff --git a/welcome.html b/welcome.html
deleted file mode 100644
index 345f5e8..0000000
--- a/welcome.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
-<html> <head>
-<title>Buzz Chat Bot</title>
-<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
-</head>
-
-<body>
-<h1>Welcome to the Buzz Chat Bot</h1>
-
-<b>Usage: How to use the bot</b>
-<ol>
- <li>Give the bot access to your Buzz account via the magic of OAuth</li>
- <li>Add the bot {{ jabber_id }} to your Chat or IM client</li>
- <li>Ask the bot for help by typing <i>/help</i></li>
-</ol>
-
-
-{% if access_token_exists %}
-<form action="/delete_tokens" method="post">
-<input type="submit" value="Remove the bot's access to your account"></input>
-</form>
-{% else %}
-<form action="{{ destination }}" method="post">
-<input type="submit" value="Start using the bot by giving it access to your account"></input>
-</form>
-{% endif %}
-
-<hr></hr>
-</body> </html>
|
adewale/Buzz-Chat-Bot
|
918a800fb7d8065ae705b68f69695fde6705b997
|
Added test for help command
|
diff --git a/functional_tests.py b/functional_tests.py
index 12d504b..1e0b380 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,223 +1,234 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = ' some message'
- self.assertEquals(expected_item, stub.message)
\ No newline at end of file
+ self.assertEquals(expected_item, stub.message)
+
+ def test_help_command_lists_available_commands(self):
+ handler = XmppHandler()
+ sender = '[email protected]'
+ message = StubMessage(sender=sender, body='%s' % XmppHandler.HELP_CMD)
+ handler.help_command(message=message)
+
+ self.assertTrue(len(message.message_to_send) > 0)
+ for command in handler.commands:
+ self.assertTrue(command in message.message_to_send, message.message_to_send)
+
diff --git a/xmpp.py b/xmpp.py
index c0ca44c..040f14d 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,249 +1,249 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class XmppHandler(xmpp_handlers.CommandHandler):
HELP_CMD = '/help'
TRACK_CMD = '/track'
UNTRACK_CMD = '/untrack'
LIST_CMD = '/list'
ABOUT_CMD = '/about'
POST_CMD = '/post'
commands = [
'%s Prints out this message' % HELP_CMD,
'%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
'%s [id] Removes your subscription for that id' % UNTRACK_CMD,
'%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
'%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
'%s [some message] Posts that message to Buzz' % POST_CMD
]
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
self.buzz_wrapper = buzz_wrapper
def handle_exception(self, exception, debug_mode):
super(xmpp_handlers.CommandHandler, self).handle_exception(exception, debug_mode)
if self.xmpp_message:
self.xmpp_message.reply('Oops. Something went wrong.')
logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
- lines.extend(commands)
+ lines.extend(self.commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: /untrack [id]')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
message_body = message.body[len('/post'):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
738f10ac4ea263fa46a86f3452f08f202b0c6792
|
First rough attempt at support for 'slashless' commands. This is suprisingly involved due to GAE xmpp_handler doing a bunch of work in a fairly well hidden place to define a 'command'.
|
diff --git a/tracker_tests.py b/tracker_tests.py
index 2eda7cd..45e1dc5 100644
--- a/tracker_tests.py
+++ b/tracker_tests.py
@@ -1,146 +1,146 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
-from xmpp import Subscription, Tracker
+from xmpp import Subscription, Tracker, XmppHandler
import pshb
import settings
class StubHubSubscriber(pshb.HubSubscriber):
def subscribe(self, url, hub, callback_url):
self.callback_url = callback_url
def unsubscribe(self, url, hub, callback_url):
self.callback_url = callback_url
class TrackerTest(unittest.TestCase):
def test_tracker_rejects_empty_search_term(self):
sender = '[email protected]'
- body = '/track'
+ body = XmppHandler.TRACK_CMD
tracker = Tracker()
self.assertEquals(None, tracker.track(sender, body))
def test_tracker_rejects_padded_empty_string(self):
sender = '[email protected]'
- body = '/track '
+ body = '%s ' % XmppHandler.TRACK_CMD
tracker = Tracker()
self.assertEquals(None, tracker.track(sender, body))
def test_tracker_accepts_valid_string(self):
sender = '[email protected]'
search_term='somestring'
- body = '/track %s' % search_term
+ body = '%s %s' % (XmppHandler.TRACK_CMD, search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
expected_callback_url = 'http://%s.appspot.com/posts/%s/%s' % (settings.APP_NAME, sender, search_term)
expected_subscription = Subscription(url='https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, search_term=search_term, callback_url=expected_callback_url)
actual_subscription = tracker.track(sender, body)
self.assertEquals(expected_subscription.url, actual_subscription.url)
self.assertEquals(expected_subscription.search_term, actual_subscription.search_term)
def test_tracker_extracts_correct_search_term(self):
search_term = 'somestring'
- body = '/track %s' % search_term
+ body = '%s %s' % (XmppHandler.TRACK_CMD, search_term)
tracker = Tracker()
self.assertEquals(search_term, tracker._extract_search_term(body))
def test_tracker_builds_correct_pshb_url(self):
search_term = 'somestring'
tracker = Tracker()
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, tracker._build_subscription_url(search_term))
def test_tracker_url_encodes_search_term(self):
search_term = 'some string'
tracker = Tracker()
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=' + 'some%20string', tracker._build_subscription_url(search_term))
def _delete_all_subscriptions(self):
for subscription in Subscription.all().fetch(100):
subscription.delete()
def test_tracker_saves_subscription(self):
self._delete_all_subscriptions()
self.assertEquals(0, len(Subscription.all().fetch(100)))
sender = '[email protected]'
search_term='somestring'
- body = '/track %s' % search_term
+ body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
tracker = Tracker()
subscription = tracker.track(sender, body)
self.assertEquals(1, len(Subscription.all().fetch(100)))
self.assertEquals(subscription, Subscription.all().fetch(1)[0])
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query(self):
sender = '[email protected]'
search_term='somestring'
- body = '/track %s' % search_term
+ body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_urlencoded_callback_url(self):
sender = '[email protected]'
search_term='some string'
- body = '/track %s' % search_term
+ body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query_without_xmpp_client_identifier(self):
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
- body = '/track %s' % search_term
+ body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_rejects_invalid_id_for_untracking(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
- body = '/untrack 1'
+ body = '%s 1' % XmppHandler.UNTRACK_CMD
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.untrack(sender, body)
self.assertEquals(None, subscription)
def test_tracker_untracks_valid_id(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
- body = '/track %s' % search_term
+ body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
track_subscription = tracker.track(sender, body)
- body = '/untrack %s' % track_subscription.id()
+ body = '%s %s' % (XmppHandler.UNTRACK_CMD,track_subscription.id())
untrack_subscription = tracker.untrack(sender, body)
self.assertEquals(track_subscription, untrack_subscription)
self.assertFalse(Subscription.exists(track_subscription.id()))
self.assertEquals('http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, track_subscription.id()), hub_subscriber.callback_url)
diff --git a/xmpp.py b/xmpp.py
index 2de9a1b..2a5b89b 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,243 +1,313 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
+import re
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
- id = message_body[len('/untrack'):]
+ id = message_body[len(XmppHandler.UNTRACK_CMD):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
-
-
-class XmppHandler(xmpp_handlers.CommandHandler):
- HELP_CMD = '/help'
- TRACK_CMD = '/track'
- UNTRACK_CMD = '/untrack'
- LIST_CMD = '/list'
- ABOUT_CMD = '/about'
- POST_CMD = '/post'
+class SlashlessCommandMessage(xmpp.Message):
+ """ The default message format with GAE xmpp identifies the command as the first non whitespace word.
+ The argument is whatever occurs after that.
+ Design notes: it uses re for tokenization which is a step up
+ from how Message works (that expects a single space character)
+ """
+
+ def __ensure_command_and_args_extracted(self):
+ """ Take the message and identify the command and argument if there is one.
+ In the case of a SlashlessCommandMessage, there is always one -- the first word is the command.
+ """
+
+ # cache the values.
+ if self.__arg != None:
+ return
+ # match any white space and then a word (cmd)
+ # then any white space then everything after that (arg).
+ results = re.search(r"\s(\S*\b)\s*(.*)", self.__body)
+ self.__command = results.group(1)
+ self.__arg = results.group(2)
+
+ @property
+ def command(self):
+ self.__ensure_command_and_args_extracted()
+ #return super(xmpp.Message, self)
+ return self.__command
+
+ @property
+ def arg(self):
+ self.__ensure_command_and_args_extracted()
+ #return super(xmpp.Message, self)
+ return self.__arg
+
+
+class SlashlessCommandHandlerMixin(xmpp_handlers.CommandHandlerMixin):
+ """A command handler for XMPP bots that does not require a slash char '/' at beginning
+ This makes the most sense when you're implementing a pure bot -- there's no context switch.
+ TODO to do this right would mean overriding xmpp.Message.command as this code is now
+ used but overridden.
+ """
+
+ def message_received(self, message):
+ """Called when a message is sent to the XMPP bot.
+ Args:
+ message: Message: The message that was sent by the user.
+ """
+ if message.command:
+ handler_name = '%s_command' % (message.command,)
+ handler = getattr(self, handler_name, None)
+ if handler:
+ handler(message)
+ else:
+ self.unhandled_command(message)
+
+
+class XmppHandler(SlashlessCommandHandlerMixin, xmpp_handlers.BaseHandler):
+ HELP_CMD = 'help'
+ TRACK_CMD = 'track'
+ UNTRACK_CMD = 'untrack'
+ LIST_CMD = 'list'
+ ABOUT_CMD = 'about'
+ POST_CMD = 'post'
commands = [
- '%s Prints out this message' % HELP_CMD,
- '%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
- '%s [id] Removes your subscription for that id' % UNTRACK_CMD,
- '%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
- '%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
- '%s [some message] Posts that message to Buzz' % POST_CMD
+ '%s Prints out this message' % HELP_CMD,
+ '%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
+ '%s [id] Removes your subscription for that id' % UNTRACK_CMD,
+ '%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
+ '%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
+ '%s [some message] Posts that message to Buzz' % POST_CMD
]
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
+ print "XmppHandler.__init__"
self.buzz_wrapper = buzz_wrapper
+
+ def post(self):
+ print "XmppHandler.post"
+ """ Redefines post to create a message from our new SlashlessCommandMessage.
+ TODO xmpp_handlers: redefine the BaseHandler to have a function createMessage which can be
+ overridden this will avoid the code duplicated below
+ """
+ try:
+ # CHANGE this is the only bit that has changed from xmpp_handlers.Message
+ self.xmpp_message = SlashlessCommandMessage(self.request.POST)
+ # END CHANGE
+ except xmpp.InvalidMessageError, e:
+ logging.error("Invalid XMPP request: Missing required field %s", e[0])
+ return
+ self.message_received(self.xmpp_message)
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
- message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: /untrack [id]')
+ message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: %s [id]' % XmppHandler.UNTRACK_CMD)
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
message_body = message.body[len('/post'):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
cd1ab5fcd61f1ef7166a3354750fb182afeaffaf
|
Added a little bit more logging on XMPP errors so we can see the message that caused the error
|
diff --git a/xmpp.py b/xmpp.py
index 822f3a8..b1b7385 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,234 +1,240 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
commands = [
'/help Prints out this message',
'/track [search term] Starts tracking the given search term and returns the id for your subscription',
'/untrack [id] Removes your subscription for that id',
'/list Lists all search terms and ids currently being tracked by you',
'/about Tells you which instance of the Buzz Chat Bot you are using',
'/post [some message] Posts that message to Buzz'
]
class XmppHandler(xmpp_handlers.CommandHandler):
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
self.buzz_wrapper = buzz_wrapper
+ def handle_exception(self, exception, debug_mode):
+ super(xmpp_handlers.CommandHandler, self).handle_exception(exception, debug_mode)
+ if self.xmpp_message:
+ self.xmpp_message.reply('Oops. Something went wrong.')
+ logging.error('User visible oops for message: %s' % str(self.xmpp_message.body))
+
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: /untrack [id]')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
message_body = message.body[len('/post'):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
ac5bd24f11d0afc1fda6c604a576cdb9985491bc
|
Refactored commands Buzz Chat Bot supports into a list defined under XmppHandler.<COMMAND>_CMD (e.g. XmppHandler.UNTRACK_CMD). Updated functional_tests to directly refer to these constants (as it's testing that the functions work, not that the functions themselves are named in a specific way).
|
diff --git a/app.yaml b/app.yaml
index d5d62fb..d827c65 100644
--- a/app.yaml
+++ b/app.yaml
@@ -1,18 +1,15 @@
-application: buzzchatbot
+application: kiwibuzzer
version: 1
runtime: python
api_version: 1
handlers:
-- url: /google53de00654ebd3aa1.html
- static_files: staticverification/google53de00654ebd3aa1.html
- upload: staticverification/google53de00654ebd3aa1.html
- url: /css
static_dir: css
- url: /images
static_dir: images
- url: /.*
script: main.py
inbound_services:
- xmpp_message
\ No newline at end of file
diff --git a/functional_tests.py b/functional_tests.py
index 1696bce..12d504b 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,223 +1,223 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import oauth_handlers
import settings
import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
self.message = message_body
return self.url
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
- body = '/track %s' % search_term
+ body = '%s %s' % (XmppHandler.TRACK_CMD,search_term)
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_untrack_command_fails_for_missing_subscription_value(self):
- message = StubMessage(body='/untrack 777')
+ message = StubMessage(body='%s 777' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
- message = StubMessage(body='/untrack %s' % id)
+ message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
- message = StubMessage(body='/untrack %s' % id)
+ message = StubMessage(body='%s %s' % (XmppHandler.UNTRACK_CMD, id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
- message = StubMessage(sender='[email protected]', body='/untrack %s' % id)
+ message = StubMessage(sender='[email protected]', body='%s %s' % (XmppHandler.UNTRACK_CMD,id))
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
- message = StubMessage(body='/untrack jaiku')
+ message = StubMessage(body='%s jaiku' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
- message = StubMessage(body='/untrack')
+ message = StubMessage(body='%s' % XmppHandler.UNTRACK_CMD)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
- message = StubMessage(sender=sender, body='/list')
+ message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
- message = StubMessage(sender=sender, body='/list')
+ message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
- message = StubMessage(sender=sender, body='/list')
+ message = StubMessage(sender=sender, body='%s' % XmppHandler.LIST_CMD)
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
- message = StubMessage(sender=sender, body='/about')
+ message = StubMessage(sender=sender, body='%s' % XmppHandler.ABOUT_CMD)
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
- message = StubMessage(sender=sender, body='/post some message')
+ message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
- message = StubMessage(sender=sender, body='/post some message')
+ message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
- message = StubMessage(sender=sender, body='/post some message')
+ message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
self.assertEquals(expected_item, message.message_to_send)
def test_post_command_strips_command_from_posted_message(self):
stub = StubSimpleBuzzWrapper()
handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
- message = StubMessage(sender=sender, body='/post some message')
+ message = StubMessage(sender=sender, body='%s some message' % XmppHandler.POST_CMD)
handler.post_command(message=message)
expected_item = ' some message'
self.assertEquals(expected_item, stub.message)
\ No newline at end of file
diff --git a/oauth_handlers.py b/oauth_handlers.py
index f7e532e..fa525c9 100644
--- a/oauth_handlers.py
+++ b/oauth_handlers.py
@@ -1,126 +1,126 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import users
import buzz_gae_client
import logging
import os
import settings
class UserToken(db.Model):
# The user_id is the key_name so we don't have to make it an explicit property
request_token_string = db.StringProperty()
access_token_string = db.StringProperty()
email_address = db.StringProperty()
def get_request_token(self):
"Returns request token as a dictionary of tokens including oauth_token, oauth_token_secret and oauth_callback_confirmed."
return eval(self.request_token_string)
def set_access_token(self, access_token):
access_token_string = repr(access_token)
self.access_token_string = access_token_string
def get_access_token(self):
"Returns access token as a dictionary of tokens including consumer_key, consumer_secret, oauth_token and oauth_token_secret"
return eval(self.access_token_string)
@staticmethod
def create_user_token(request_token):
user = users.get_current_user()
user_id = user.user_id()
request_token_string = repr(request_token)
# TODO(ade) Support users who sign in to AppEngine with a federated identity aka OpenId
email = user.email()
logging.info('Creating user token: key_name: %s request_token_string: %s email_address: %s' % (
user_id, request_token_string, email))
return UserToken(key_name=user_id, request_token_string=request_token_string, access_token_string='',
email_address=email)
@staticmethod
def get_current_user_token():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
return user_token
@staticmethod
def access_token_exists():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
logging.info('user_token: %s' % user_token)
return user_token and user_token.access_token_string
@staticmethod
def find_by_email_address(email_address):
user_tokens = UserToken.gql('WHERE email_address = :1', email_address).fetch(1)
if user_tokens:
return user_tokens[0] # The result of the query is a list
else:
return None
class WelcomeHandler(webapp.RequestHandler):
@login_required
def get(self):
logging.info("Request body %s" % self.request.body)
- template_values = {}
+ template_values = {"jabber_id": ("%[email protected]" % settings.APP_NAME)}
if UserToken.access_token_exists():
template_values['access_token_exists'] = 'true'
else:
# Generate the request token
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
request_token = client.get_request_token(settings.CALLBACK_URL)
# Create the request token and associate it with the current user
user_token = UserToken.create_user_token(request_token)
UserToken.put(user_token)
authorisation_url = client.generate_authorisation_url(request_token)
logging.info('Authorisation URL is: %s' % authorisation_url)
template_values['destination'] = authorisation_url
path = os.path.join(os.path.dirname(__file__), 'welcome.html')
self.response.out.write(template.render(path, template_values))
class TokenDeletionHandler(webapp.RequestHandler):
def post(self):
user_token = UserToken.get_current_user_token()
UserToken.delete(user_token)
self.redirect('/')
class DanceFinishingHandler(webapp.RequestHandler):
def get(self):
logging.info("Request body %s" % self.request.body)
oauth_verifier = self.request.get('oauth_verifier')
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
user_token = UserToken.get_current_user_token()
request_token = user_token.get_request_token()
access_token = client.upgrade_to_access_token(request_token, oauth_verifier)
logging.info('SUCCESS: Received access token.')
user_token.set_access_token(access_token)
UserToken.put(user_token)
logging.debug('Access token was: %s' % user_token.access_token_string)
self.redirect('/profile')
\ No newline at end of file
diff --git a/welcome.html b/welcome.html
index 1edbc1b..345f5e8 100644
--- a/welcome.html
+++ b/welcome.html
@@ -1,29 +1,29 @@
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html> <head>
<title>Buzz Chat Bot</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
</head>
<body>
<h1>Welcome to the Buzz Chat Bot</h1>
<b>Usage: How to use the bot</b>
<ol>
<li>Give the bot access to your Buzz account via the magic of OAuth</li>
- <li>Add the bot [email protected] to your Chat or IM client</li>
+ <li>Add the bot {{ jabber_id }} to your Chat or IM client</li>
<li>Ask the bot for help by typing <i>/help</i></li>
</ol>
{% if access_token_exists %}
<form action="/delete_tokens" method="post">
<input type="submit" value="Remove the bot's access to your account"></input>
</form>
{% else %}
<form action="{{ destination }}" method="post">
<input type="submit" value="Start using the bot by giving it access to your account"></input>
</form>
{% endif %}
<hr></hr>
</body> </html>
diff --git a/xmpp.py b/xmpp.py
index 822f3a8..2de9a1b 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,234 +1,243 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
-commands = [
- '/help Prints out this message',
- '/track [search term] Starts tracking the given search term and returns the id for your subscription',
- '/untrack [id] Removes your subscription for that id',
- '/list Lists all search terms and ids currently being tracked by you',
- '/about Tells you which instance of the Buzz Chat Bot you are using',
- '/post [some message] Posts that message to Buzz'
-]
class XmppHandler(xmpp_handlers.CommandHandler):
+ HELP_CMD = '/help'
+ TRACK_CMD = '/track'
+ UNTRACK_CMD = '/untrack'
+ LIST_CMD = '/list'
+ ABOUT_CMD = '/about'
+ POST_CMD = '/post'
+
+ commands = [
+ '%s Prints out this message' % HELP_CMD,
+ '%s [search term] Starts tracking the given search term and returns the id for your subscription' % TRACK_CMD,
+ '%s [id] Removes your subscription for that id' % UNTRACK_CMD,
+ '%s Lists all search terms and ids currently being tracked by you' % LIST_CMD,
+ '%s Tells you which instance of the Buzz Chat Bot you are using' % ABOUT_CMD,
+ '%s [some message] Posts that message to Buzz' % POST_CMD
+ ]
+
+
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
self.buzz_wrapper = buzz_wrapper
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: /untrack [id]')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
message_body = message.body[len('/post'):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
495815c0feb6a0d2bbc35c1e6907fa5d1f4a0ccb
|
Added buzz client module
|
diff --git a/buzz_gae_client.py b/buzz_gae_client.py
new file mode 100644
index 0000000..ffc74c3
--- /dev/null
+++ b/buzz_gae_client.py
@@ -0,0 +1,105 @@
+# Copyright (C) 2010 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+__author__ = '[email protected]'
+
+import apiclient.discovery
+import logging
+import oauth_wrap
+import oauth2 as oauth
+import urllib
+import urlparse
+
+try:
+ from urlparse import parse_qs, parse_qsl, urlparse
+except ImportError:
+ from cgi import parse_qs, parse_qsl
+
+# TODO(ade) Replace user-agent with something specific
+HEADERS = {
+ 'user-agent': 'gdata-python-v3-sample-client/0.1',
+ 'content-type': 'application/x-www-form-urlencoded'
+ }
+
+REQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken?domain=anonymous&scope=https://www.googleapis.com/auth/buzz'
+AUTHORIZE_URL = 'https://www.google.com/buzz/api/auth/OAuthAuthorizeToken?domain=anonymous&scope=https://www.googleapis.com/auth/buzz'
+ACCESS_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetAccessToken'
+
+# TODO(ade) This class is really a BuzzGaeBuilder. Rename it.
+class BuzzGaeClient(object):
+ def __init__(self, consumer_key='anonymous', consumer_secret='anonymous'):
+ self.consumer = oauth.Consumer(consumer_key, consumer_secret)
+ self.consumer_key = consumer_key
+ self.consumer_secret = consumer_secret
+
+ def _make_post_request(self, client, url, parameters):
+ resp, content = client.request(url, 'POST', headers=HEADERS,
+ body=urllib.urlencode(parameters, True))
+
+ if resp['status'] != '200':
+ logging.warn('Request: %s failed with status: %s. Content was: %s' % (url, resp['status'], content))
+ raise Exception('Invalid response %s.' % resp['status'])
+ return resp, content
+
+ def get_request_token(self, callback_url, display_name = None):
+ parameters = {
+ 'oauth_callback': callback_url
+ }
+
+ if display_name is not None:
+ parameters['xoauth_displayname'] = display_name
+
+ client = oauth.Client(self.consumer)
+ resp, content = self._make_post_request(client, REQUEST_TOKEN_URL, parameters)
+
+ request_token = dict(parse_qsl(content))
+ return request_token
+
+ def generate_authorisation_url(self, request_token):
+ """Returns the URL the user should be redirected to in other to gain access to their account."""
+
+ base_url = urlparse.urlparse(AUTHORIZE_URL)
+ query = parse_qs(base_url.query)
+ query['oauth_token'] = request_token['oauth_token']
+
+ logging.info(urllib.urlencode(query, True))
+
+ url = (base_url.scheme, base_url.netloc, base_url.path, base_url.params,
+ urllib.urlencode(query, True), base_url.fragment)
+ authorisation_url = urlparse.urlunparse(url)
+ return authorisation_url
+
+ def upgrade_to_access_token(self, request_token, oauth_verifier):
+ token = oauth.Token(request_token['oauth_token'],
+ request_token['oauth_token_secret'])
+ token.set_verifier(oauth_verifier)
+ client = oauth.Client(self.consumer, token)
+
+ parameters = {}
+ resp, content = self._make_post_request(client, ACCESS_TOKEN_URL, parameters)
+ access_token = dict(parse_qsl(content))
+
+ d = {
+ 'consumer_key' : self.consumer_key,
+ 'consumer_secret' : self.consumer_secret
+ }
+ d.update(access_token)
+ return d
+
+ def build_api_client(self, oauth_params=None):
+ if oauth_params is not None:
+ http = oauth_wrap.get_authorised_http(oauth_params)
+ return apiclient.discovery.build('buzz', 'v1', http = http)
+ else:
+ return apiclient.discovery.build('buzz', 'v1')
|
adewale/Buzz-Chat-Bot
|
aaf14088d3d83e15691ffce608b7d496cdad3aaf
|
Added apiclient
|
diff --git a/apiclient/__init__.py b/apiclient/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/apiclient/contrib/__init__.py b/apiclient/contrib/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/apiclient/contrib/buzz/future.json b/apiclient/contrib/buzz/future.json
new file mode 100644
index 0000000..ed6f0f9
--- /dev/null
+++ b/apiclient/contrib/buzz/future.json
@@ -0,0 +1,147 @@
+{
+ "data": {
+ "buzz": {
+ "v1": {
+ "baseUrl": "https://www.googleapis.com/",
+ "auth": {
+ "request": {
+ "url": "https://www.google.com/accounts/OAuthGetRequestToken",
+ "parameters": {
+ "xoauth_displayname": {
+ "parameterType": "query",
+ "required": false
+ },
+ "domain": {
+ "parameterType": "query",
+ "required": true
+ },
+ "scope": {
+ "parameterType": "query",
+ "required": true
+ }
+ }
+ },
+ "authorize": {
+ "url": "https://www.google.com/buzz/api/auth/OAuthAuthorizeToken",
+ "parameters": {
+ "oauth_token": {
+ "parameterType": "query",
+ "required": true
+ },
+ "iconUrl": {
+ "parameterType": "query",
+ "required": false
+ },
+ "domain": {
+ "parameterType": "query",
+ "required": true
+ },
+ "scope": {
+ "parameterType": "query",
+ "required": true
+ }
+ }
+ },
+ "access": {
+ "url": "https://www.google.com/accounts/OAuthGetAccessToken",
+ "parameters": {
+ "domain": {
+ "parameterType": "query",
+ "required": true
+ },
+ "scope": {
+ "parameterType": "query",
+ "required": true
+ }
+ }
+ }
+ },
+ "resources": {
+ "activities": {
+ "methods": {
+ "delete": {},
+ "get": {},
+ "insert": {},
+ "list": {
+ "next": {
+ "type": "uri",
+ "location": ["links", "next", 0, "href"]
+ }
+ },
+ "search": {
+ "next": {
+ "type": "uri",
+ "location": ["links", "next", 0, "href"]
+ }
+ },
+ "update": {}
+ }
+ },
+ "comments": {
+ "methods": {
+ "delete": {},
+ "get": {},
+ "insert": {},
+ "list": {},
+ "update": {}
+ }
+ },
+ "feeds": {
+ "methods": {
+ "delete": {},
+ "insert": {},
+ "list": {},
+ "update": {}
+ }
+ },
+ "groups": {
+ "methods": {
+ "delete": {},
+ "get": {},
+ "insert": {},
+ "list": {
+ "next": {
+ "type": "uri",
+ "location": ["links", "next", 0, "href"]
+ }
+ },
+ "update": {}
+ }
+ },
+ "people": {
+ "methods": {
+ "delete": {},
+ "get": {},
+ "liked": {
+ "next": {
+ "type": "uri",
+ "location": ["links", "next", 0, "href"]
+ }
+ },
+ "list": {},
+ "relatedToUri": {},
+ "reshared": {},
+ "search": {},
+ "update": {}
+ }
+ },
+ "photos": {
+ "methods": {
+ "insert": {}
+ }
+ },
+ "related": {
+ "methods": {
+ "list": {}
+ }
+ },
+ "search": {
+ "methods": {
+ "extractPeople": {}
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/apiclient/contrib/latitude/future.json b/apiclient/contrib/latitude/future.json
new file mode 100644
index 0000000..e44d410
--- /dev/null
+++ b/apiclient/contrib/latitude/future.json
@@ -0,0 +1,79 @@
+{
+ "data": {
+ "latitude": {
+ "v1": {
+ "baseUrl": "https://www.googleapis.com/",
+ "auth": {
+ "request": {
+ "url": "https://www.google.com/accounts/OAuthGetRequestToken",
+ "parameters": {
+ "xoauth_displayname": {
+ "parameterType": "query",
+ "required": false
+ },
+ "domain": {
+ "parameterType": "query",
+ "required": true
+ },
+ "scope": {
+ "parameterType": "query",
+ "required": true
+ }
+ }
+ },
+ "authorize": {
+ "url": "https://www.google.com/latitude/apps/OAuthAuthorizeToken",
+ "parameters": {
+ "oauth_token": {
+ "parameterType": "query",
+ "required": true
+ },
+ "iconUrl": {
+ "parameterType": "query",
+ "required": false
+ },
+ "domain": {
+ "parameterType": "query",
+ "required": true
+ },
+ "scope": {
+ "parameterType": "query",
+ "required": true
+ }
+ }
+ },
+ "access": {
+ "url": "https://www.google.com/accounts/OAuthGetAccessToken",
+ "parameters": {
+ "domain": {
+ "parameterType": "query",
+ "required": true
+ },
+ "scope": {
+ "parameterType": "query",
+ "required": true
+ }
+ }
+ }
+ },
+ "resources": {
+ "currentLocation": {
+ "methods": {
+ "delete": {},
+ "get": {},
+ "insert": {}
+ }
+ },
+ "location": {
+ "methods": {
+ "delete": {},
+ "get": {},
+ "insert": {},
+ "list": {}
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/apiclient/contrib/moderator/future.json b/apiclient/contrib/moderator/future.json
new file mode 100644
index 0000000..7e3d978
--- /dev/null
+++ b/apiclient/contrib/moderator/future.json
@@ -0,0 +1,113 @@
+{
+ "data": {
+ "moderator": {
+ "v1": {
+ "baseUrl": "https://www.googleapis.com/",
+ "auth": {
+ "request": {
+ "url": "https://www.google.com/accounts/OAuthGetRequestToken",
+ "parameters": {
+ "xoauth_displayname": {
+ "parameterType": "query",
+ "required": false
+ },
+ "domain": {
+ "parameterType": "query",
+ "required": false
+ },
+ "scope": {
+ "parameterType": "query",
+ "required": true
+ }
+ }
+ },
+ "authorize": {
+ "url": "https://www.google.com/accounts/OAuthAuthorizeToken",
+ "parameters": {
+ "oauth_token": {
+ "parameterType": "query",
+ "required": true
+ },
+ "iconUrl": {
+ "parameterType": "query",
+ "required": false
+ },
+ "domain": {
+ "parameterType": "query",
+ "required": false
+ },
+ "scope": {
+ "parameterType": "query",
+ "required": true
+ }
+ }
+ },
+ "access": {
+ "url": "https://www.google.com/accounts/OAuthGetAccessToken",
+ "parameters": {
+ "domain": {
+ "parameterType": "query",
+ "required": false
+ },
+ "scope": {
+ "parameterType": "query",
+ "required": true
+ }
+ }
+ }
+ },
+ "resources": {
+ "profiles": {
+ "methods": {
+ "get": {},
+ "update": {}
+ }
+ },
+ "responses": {
+ "methods": {
+ "insert": {},
+ "list": {}
+ }
+ },
+ "series": {
+ "methods": {
+ "get": {},
+ "insert": {},
+ "list": {},
+ "update": {}
+ }
+ },
+ "submissions": {
+ "methods": {
+ "get": {},
+ "insert": {},
+ "list": {}
+ }
+ },
+ "tags": {
+ "methods": {
+ "delete": {},
+ "insert": {},
+ "list": {}
+ }
+ },
+ "topics": {
+ "methods": {
+ "get": {},
+ "insert": {},
+ "list": {}
+ }
+ },
+ "votes": {
+ "methods": {
+ "get": {},
+ "insert": {},
+ "list": {},
+ "update": {}
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/apiclient/discovery.py b/apiclient/discovery.py
new file mode 100644
index 0000000..0b441b1
--- /dev/null
+++ b/apiclient/discovery.py
@@ -0,0 +1,306 @@
+# Copyright (C) 2010 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Client for discovery based APIs
+
+A client library for Google's discovery
+based APIs.
+"""
+
+__author__ = '[email protected] (Joe Gregorio)'
+
+
+import httplib2
+import logging
+import os
+import re
+import uritemplate
+import urllib
+import urlparse
+try:
+ from urlparse import parse_qsl
+except ImportError:
+ from cgi import parse_qsl
+from apiclient.http import HttpRequest
+
+try: # pragma: no cover
+ import simplejson
+except ImportError: # pragma: no cover
+ try:
+ # Try to import from django, should work on App Engine
+ from django.utils import simplejson
+ except ImportError:
+ # Should work for Python2.6 and higher.
+ import json as simplejson
+
+
+class HttpError(Exception):
+ pass
+
+
+class UnknownLinkType(Exception):
+ pass
+
+DISCOVERY_URI = ('http://www.googleapis.com/discovery/0.1/describe'
+ '{?api,apiVersion}')
+
+
+def key2param(key):
+ """
+ max-results -> max_results
+ """
+ result = []
+ key = list(key)
+ if not key[0].isalpha():
+ result.append('x')
+ for c in key:
+ if c.isalnum():
+ result.append(c)
+ else:
+ result.append('_')
+
+ return ''.join(result)
+
+
+class JsonModel(object):
+
+ def request(self, headers, path_params, query_params, body_value):
+ query = self.build_query(query_params)
+ headers['accept'] = 'application/json'
+ if 'user-agent' in headers:
+ headers['user-agent'] += ' '
+ else:
+ headers['user-agent'] = ''
+ headers['user-agent'] += 'google-api-python-client/1.0'
+ if body_value is None:
+ return (headers, path_params, query, None)
+ else:
+ model = {'data': body_value}
+ headers['content-type'] = 'application/json'
+ return (headers, path_params, query, simplejson.dumps(model))
+
+ def build_query(self, params):
+ params.update({'alt': 'json', 'prettyprint': 'true'})
+ astuples = []
+ for key, value in params.iteritems():
+ if getattr(value, 'encode', False) and callable(value.encode):
+ value = value.encode('utf-8')
+ astuples.append((key, value))
+ return '?' + urllib.urlencode(astuples)
+
+ def response(self, resp, content):
+ # Error handling is TBD, for example, do we retry
+ # for some operation/error combinations?
+ if resp.status < 300:
+ return simplejson.loads(content)['data']
+ else:
+ logging.debug('Content from bad request was: %s' % content)
+ if resp.get('content-type', '') != 'application/json':
+ raise HttpError('%d %s' % (resp.status, resp.reason))
+ else:
+ raise HttpError(simplejson.loads(content)['error'])
+
+
+def build(serviceName, version, http=None,
+ discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=JsonModel()):
+ params = {
+ 'api': serviceName,
+ 'apiVersion': version
+ }
+
+ if http is None:
+ http = httplib2.Http()
+ requested_url = uritemplate.expand(discoveryServiceUrl, params)
+ logging.info('URL being requested: %s' % requested_url)
+ resp, content = http.request(requested_url)
+ d = simplejson.loads(content)
+ service = d['data'][serviceName][version]
+
+ fn = os.path.join(os.path.dirname(__file__), "contrib",
+ serviceName, "future.json")
+ f = file(fn, "r")
+ d = simplejson.load(f)
+ f.close()
+ future = d['data'][serviceName][version]['resources']
+ auth_discovery = d['data'][serviceName][version]['auth']
+
+ base = service['baseUrl']
+ resources = service['resources']
+
+ class Service(object):
+ """Top level interface for a service"""
+
+ def __init__(self, http=http):
+ self._http = http
+ self._baseUrl = base
+ self._model = model
+ self._developerKey = developerKey
+
+ def auth_discovery(self):
+ return auth_discovery
+
+ def createMethod(theclass, methodName, methodDesc, futureDesc):
+
+ def method(self, **kwargs):
+ return createResource(self._http, self._baseUrl, self._model,
+ methodName, self._developerKey, methodDesc, futureDesc)
+
+ setattr(method, '__doc__', 'A description of how to use this function')
+ setattr(theclass, methodName, method)
+
+ for methodName, methodDesc in resources.iteritems():
+ createMethod(Service, methodName, methodDesc, future[methodName])
+ return Service()
+
+
+def createResource(http, baseUrl, model, resourceName, developerKey,
+ resourceDesc, futureDesc):
+
+ class Resource(object):
+ """A class for interacting with a resource."""
+
+ def __init__(self):
+ self._http = http
+ self._baseUrl = baseUrl
+ self._model = model
+ self._developerKey = developerKey
+
+ def createMethod(theclass, methodName, methodDesc, futureDesc):
+ pathUrl = methodDesc['pathUrl']
+ pathUrl = re.sub(r'\{', r'{+', pathUrl)
+ httpMethod = methodDesc['httpMethod']
+
+ argmap = {}
+ if httpMethod in ['PUT', 'POST']:
+ argmap['body'] = 'body'
+
+
+ required_params = [] # Required parameters
+ pattern_params = {} # Parameters that must match a regex
+ query_params = [] # Parameters that will be used in the query string
+ path_params = {} # Parameters that will be used in the base URL
+ if 'parameters' in methodDesc:
+ for arg, desc in methodDesc['parameters'].iteritems():
+ param = key2param(arg)
+ argmap[param] = arg
+
+ if desc.get('pattern', ''):
+ pattern_params[param] = desc['pattern']
+ if desc.get('required', False):
+ required_params.append(param)
+ if desc.get('parameterType') == 'query':
+ query_params.append(param)
+ if desc.get('parameterType') == 'path':
+ path_params[param] = param
+
+ def method(self, **kwargs):
+ for name in kwargs.iterkeys():
+ if name not in argmap:
+ raise TypeError('Got an unexpected keyword argument "%s"' % name)
+
+ for name in required_params:
+ if name not in kwargs:
+ raise TypeError('Missing required parameter "%s"' % name)
+
+ for name, regex in pattern_params.iteritems():
+ if name in kwargs:
+ if re.match(regex, kwargs[name]) is None:
+ raise TypeError(
+ 'Parameter "%s" value "%s" does not match the pattern "%s"' %
+ (name, kwargs[name], regex))
+
+ actual_query_params = {}
+ actual_path_params = {}
+ for key, value in kwargs.iteritems():
+ if key in query_params:
+ actual_query_params[argmap[key]] = value
+ if key in path_params:
+ actual_path_params[argmap[key]] = value
+ body_value = kwargs.get('body', None)
+
+ if self._developerKey:
+ actual_query_params['key'] = self._developerKey
+
+ headers = {}
+ headers, params, query, body = self._model.request(headers,
+ actual_path_params, actual_query_params, body_value)
+
+ expanded_url = uritemplate.expand(pathUrl, params)
+ url = urlparse.urljoin(self._baseUrl, expanded_url + query)
+
+ logging.info('URL being requested: %s' % url)
+ return HttpRequest(self._http, url, method=httpMethod, body=body,
+ headers=headers, postproc=self._model.response)
+
+ docs = ['A description of how to use this function\n\n']
+ for arg in argmap.iterkeys():
+ required = ""
+ if arg in required_params:
+ required = " (required)"
+ docs.append('%s - A parameter%s\n' % (arg, required))
+
+ setattr(method, '__doc__', ''.join(docs))
+ setattr(theclass, methodName, method)
+
+ def createNextMethod(theclass, methodName, methodDesc):
+
+ def method(self, previous):
+ """
+ Takes a single argument, 'body', which is the results
+ from the last call, and returns the next set of items
+ in the collection.
+
+ Returns None if there are no more items in
+ the collection.
+ """
+ if methodDesc['type'] != 'uri':
+ raise UnknownLinkType(methodDesc['type'])
+
+ try:
+ p = previous
+ for key in methodDesc['location']:
+ p = p[key]
+ url = p
+ except (KeyError, TypeError):
+ return None
+
+ if self._developerKey:
+ parsed = list(urlparse.urlparse(url))
+ q = parse_qsl(parsed[4])
+ q.append(('key', self._developerKey))
+ parsed[4] = urllib.urlencode(q)
+ url = urlparse.urlunparse(parsed)
+
+ headers = {}
+ headers, params, query, body = self._model.request(headers, {}, {}, None)
+
+ logging.info('URL being requested: %s' % url)
+ resp, content = self._http.request(url, method='GET', headers=headers)
+
+ return HttpRequest(self._http, url, method='GET',
+ headers=headers, postproc=self._model.response)
+
+ setattr(theclass, methodName, method)
+
+ # Add basic methods to Resource
+ for methodName, methodDesc in resourceDesc['methods'].iteritems():
+ future = futureDesc['methods'].get(methodName, {})
+ createMethod(Resource, methodName, methodDesc, future)
+
+ # Add <m>_next() methods to Resource
+ for methodName, methodDesc in futureDesc['methods'].iteritems():
+ if 'next' in methodDesc and methodName in resourceDesc['methods']:
+ createNextMethod(Resource, methodName + "_next", methodDesc['next'])
+
+ return Resource()
diff --git a/apiclient/ext/__init__.py b/apiclient/ext/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/apiclient/ext/appengine.py b/apiclient/ext/appengine.py
new file mode 100644
index 0000000..a780d0e
--- /dev/null
+++ b/apiclient/ext/appengine.py
@@ -0,0 +1,90 @@
+# Copyright (C) 2010 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Utilities for Google App Engine
+
+Utilities for making it easier to use the
+Google API Client for Python on Google App Engine.
+"""
+
+__author__ = '[email protected] (Joe Gregorio)'
+
+import pickle
+
+from google.appengine.ext import db
+from apiclient.oauth import OAuthCredentials
+from apiclient.oauth import FlowThreeLegged
+
+
+class FlowThreeLeggedProperty(db.Property):
+ """Utility property that allows easy
+ storage and retreival of an
+ apiclient.oauth.FlowThreeLegged"""
+
+ # Tell what the user type is.
+ data_type = FlowThreeLegged
+
+ # For writing to datastore.
+ def get_value_for_datastore(self, model_instance):
+ flow = super(FlowThreeLeggedProperty,
+ self).get_value_for_datastore(model_instance)
+ return db.Blob(pickle.dumps(flow))
+
+ # For reading from datastore.
+ def make_value_from_datastore(self, value):
+ if value is None:
+ return None
+ return pickle.loads(value)
+
+ def validate(self, value):
+ if value is not None and not isinstance(value, FlowThreeLegged):
+ raise BadValueError('Property %s must be convertible '
+ 'to a FlowThreeLegged instance (%s)' %
+ (self.name, value))
+ return super(FlowThreeLeggedProperty, self).validate(value)
+
+ def empty(self, value):
+ return not value
+
+
+class OAuthCredentialsProperty(db.Property):
+ """Utility property that allows easy
+ storage and retrieval of
+ apiclient.oath.OAuthCredentials
+ """
+
+ # Tell what the user type is.
+ data_type = OAuthCredentials
+
+ # For writing to datastore.
+ def get_value_for_datastore(self, model_instance):
+ cred = super(OAuthCredentialsProperty,
+ self).get_value_for_datastore(model_instance)
+ return db.Blob(pickle.dumps(cred))
+
+ # For reading from datastore.
+ def make_value_from_datastore(self, value):
+ if value is None:
+ return None
+ return pickle.loads(value)
+
+ def validate(self, value):
+ if value is not None and not isinstance(value, OAuthCredentials):
+ raise BadValueError('Property %s must be convertible '
+ 'to an OAuthCredentials instance (%s)' %
+ (self.name, value))
+ return super(OAuthCredentialsProperty, self).validate(value)
+
+ def empty(self, value):
+ return not value
diff --git a/apiclient/http.py b/apiclient/http.py
new file mode 100644
index 0000000..25d646e
--- /dev/null
+++ b/apiclient/http.py
@@ -0,0 +1,35 @@
+# Copyright 2010 Google Inc. All Rights Reserved.
+
+"""One-line documentation for http module.
+
+A detailed description of http.
+"""
+
+__author__ = '[email protected] (Joe Gregorio)'
+
+
+class HttpRequest(object):
+ """Encapsulate an HTTP request.
+ """
+
+ def __init__(self, http, uri, method="GET", body=None, headers=None,
+ postproc=None):
+ self.uri = uri
+ self.method = method
+ self.body = body
+ self.headers = headers or {}
+ self.http = http
+ self.postproc = postproc
+
+ def execute(self, http=None):
+ """Execute the request.
+
+ If an http object is passed in it is used instead of the
+ httplib2.Http object that the request was constructed with.
+ """
+ if http is None:
+ http = self.http
+ resp, content = http.request(self.uri, self.method,
+ body=self.body,
+ headers=self.headers)
+ return self.postproc(resp, content)
diff --git a/apiclient/oauth.py b/apiclient/oauth.py
new file mode 100644
index 0000000..8b827c6
--- /dev/null
+++ b/apiclient/oauth.py
@@ -0,0 +1,232 @@
+#!/usr/bin/python2.4
+#
+# Copyright 2010 Google Inc. All Rights Reserved.
+
+"""Utilities for OAuth.
+
+Utilities for making it easier to work with OAuth.
+"""
+
+__author__ = '[email protected] (Joe Gregorio)'
+
+import copy
+import httplib2
+import oauth2 as oauth
+import urllib
+import logging
+
+try:
+ from urlparse import parse_qs, parse_qsl
+except ImportError:
+ from cgi import parse_qs, parse_qsl
+
+
+class MissingParameter(Exception):
+ pass
+
+
+def _abstract():
+ raise NotImplementedError('You need to override this function')
+
+
+def _oauth_uri(name, discovery, params):
+ """Look up the OAuth UR from the discovery
+ document and add query parameters based on
+ params.
+
+ name - The name of the OAuth URI to lookup, one
+ of 'request', 'access', or 'authorize'.
+ discovery - Portion of discovery document the describes
+ the OAuth endpoints.
+ params - Dictionary that is used to form the query parameters
+ for the specified URI.
+ """
+ if name not in ['request', 'access', 'authorize']:
+ raise KeyError(name)
+ keys = discovery[name]['parameters'].keys()
+ query = {}
+ for key in keys:
+ if key in params:
+ query[key] = params[key]
+ return discovery[name]['url'] + '?' + urllib.urlencode(query)
+
+
+class Credentials(object):
+ """Base class for all Credentials objects.
+
+ Subclasses must define an authorize() method
+ that applies the credentials to an HTTP transport.
+ """
+
+ def authorize(self, http):
+ """Take an httplib2.Http instance (or equivalent) and
+ authorizes it for the set of credentials, usually by
+ replacing http.request() with a method that adds in
+ the appropriate headers and then delegates to the original
+ Http.request() method.
+ """
+ _abstract()
+
+
+class OAuthCredentials(Credentials):
+ """Credentials object for OAuth 1.0a
+ """
+
+ def __init__(self, consumer, token, user_agent):
+ """
+ consumer - An instance of oauth.Consumer.
+ token - An instance of oauth.Token constructed with
+ the access token and secret.
+ user_agent - The HTTP User-Agent to provide for this application.
+ """
+ self.consumer = consumer
+ self.token = token
+ self.user_agent = user_agent
+
+ def authorize(self, http):
+ """
+ Args:
+ http - An instance of httplib2.Http
+ or something that acts like it.
+
+ Returns:
+ A modified instance of http that was passed in.
+
+ Example:
+
+ h = httplib2.Http()
+ h = credentials.authorize(h)
+
+ You can't create a new OAuth
+ subclass of httplib2.Authenication because
+ it never gets passed the absolute URI, which is
+ needed for signing. So instead we have to overload
+ 'request' with a closure that adds in the
+ Authorization header and then calls the original version
+ of 'request()'.
+ """
+ request_orig = http.request
+ signer = oauth.SignatureMethod_HMAC_SHA1()
+
+ # The closure that will replace 'httplib2.Http.request'.
+ def new_request(uri, method='GET', body=None, headers=None,
+ redirections=httplib2.DEFAULT_MAX_REDIRECTS,
+ connection_type=None):
+ """Modify the request headers to add the appropriate
+ Authorization header."""
+ req = oauth.Request.from_consumer_and_token(
+ self.consumer, self.token, http_method=method, http_url=uri)
+ req.sign_request(signer, self.consumer, self.token)
+ if headers == None:
+ headers = {}
+ headers.update(req.to_header())
+ if 'user-agent' not in headers:
+ headers['user-agent'] = self.user_agent
+ return request_orig(uri, method, body, headers,
+ redirections, connection_type)
+
+ http.request = new_request
+ return http
+
+
+class FlowThreeLegged(object):
+ """Does the Three Legged Dance for OAuth 1.0a.
+ """
+
+ def __init__(self, discovery, consumer_key, consumer_secret, user_agent,
+ **kwargs):
+ """
+ discovery - Section of the API discovery document that describes
+ the OAuth endpoints.
+ consumer_key - OAuth consumer key
+ consumer_secret - OAuth consumer secret
+ user_agent - The HTTP User-Agent that identifies the application.
+ **kwargs - The keyword arguments are all optional and required
+ parameters for the OAuth calls.
+ """
+ self.discovery = discovery
+ self.consumer_key = consumer_key
+ self.consumer_secret = consumer_secret
+ self.user_agent = user_agent
+ self.params = kwargs
+ self.request_token = {}
+ required = {}
+ for uriinfo in discovery.itervalues():
+ for name, value in uriinfo['parameters'].iteritems():
+ if value['required'] and not name.startswith('oauth_'):
+ required[name] = 1
+ for key in required.iterkeys():
+ if key not in self.params:
+ raise MissingParameter('Required parameter %s not supplied' % key)
+
+ def step1_get_authorize_url(self, oauth_callback='oob'):
+ """Returns a URI to redirect to the provider.
+
+ oauth_callback - Either the string 'oob' for a non-web-based application,
+ or a URI that handles the callback from the authorization
+ server.
+
+ If oauth_callback is 'oob' then pass in the
+ generated verification code to step2_exchange,
+ otherwise pass in the query parameters received
+ at the callback uri to step2_exchange.
+ """
+ consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
+ client = oauth.Client(consumer)
+
+ headers = {
+ 'user-agent': self.user_agent,
+ 'content-type': 'application/x-www-form-urlencoded'
+ }
+ body = urllib.urlencode({'oauth_callback': oauth_callback})
+ uri = _oauth_uri('request', self.discovery, self.params)
+
+ resp, content = client.request(uri, 'POST', headers=headers,
+ body=body)
+ if resp['status'] != '200':
+ logging.error('Failed to retrieve temporary authorization: %s' % content)
+ raise Exception('Invalid response %s.' % resp['status'])
+
+ self.request_token = dict(parse_qsl(content))
+
+ auth_params = copy.copy(self.params)
+ auth_params['oauth_token'] = self.request_token['oauth_token']
+
+ return _oauth_uri('authorize', self.discovery, auth_params)
+
+ def step2_exchange(self, verifier):
+ """Exhanges an authorized request token
+ for OAuthCredentials.
+
+ verifier - either the verifier token, or a dictionary
+ of the query parameters to the callback, which contains
+ the oauth_verifier.
+ """
+
+ if not (isinstance(verifier, str) or isinstance(verifier, unicode)):
+ verifier = verifier['oauth_verifier']
+
+ token = oauth.Token(
+ self.request_token['oauth_token'],
+ self.request_token['oauth_token_secret'])
+ token.set_verifier(verifier)
+ consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
+ client = oauth.Client(consumer, token)
+
+ headers = {
+ 'user-agent': self.user_agent,
+ 'content-type': 'application/x-www-form-urlencoded'
+ }
+
+ uri = _oauth_uri('access', self.discovery, self.params)
+ resp, content = client.request(uri, 'POST', headers=headers)
+ if resp['status'] != '200':
+ logging.error('Failed to retrieve access token: %s' % content)
+ raise Exception('Invalid response %s.' % resp['status'])
+
+ oauth_params = dict(parse_qsl(content))
+ token = oauth.Token(
+ oauth_params['oauth_token'],
+ oauth_params['oauth_token_secret'])
+
+ return OAuthCredentials(consumer, token, self.user_agent)
diff --git a/app.yaml b/app.yaml
index e30bf45..d5d62fb 100644
--- a/app.yaml
+++ b/app.yaml
@@ -1,15 +1,18 @@
application: buzzchatbot
version: 1
runtime: python
api_version: 1
handlers:
+- url: /google53de00654ebd3aa1.html
+ static_files: staticverification/google53de00654ebd3aa1.html
+ upload: staticverification/google53de00654ebd3aa1.html
- url: /css
static_dir: css
- url: /images
static_dir: images
- url: /.*
script: main.py
inbound_services:
- xmpp_message
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
2f031ed2c2d3be689ac7fcbbf70e62a34bd01676
|
Add bugs file and buzz_gae_client
|
diff --git a/BUGS b/BUGS
new file mode 100644
index 0000000..e49705e
--- /dev/null
+++ b/BUGS
@@ -0,0 +1,4 @@
+According to Brian Rose: posts that contain @mentions cause an error.
+According to Robert C Sanchez the bot doesn't work with Empathy on Ubuntu. I suspect this is to do with either the formatting of the messages or the structure of the JID. Although Michael Bernstein has a theory that the /commands are being intercepted by the chat client. However commands like /post and /track aren't working for him so there may be something else wrong.
+
+
diff --git a/buzz_gae_client.py b/buzz_gae_client.py
new file mode 120000
index 0000000..0037dd2
--- /dev/null
+++ b/buzz_gae_client.py
@@ -0,0 +1 @@
+../google-api-python-client/buzz_gae_client.py
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
8f47ab428e87541dc3cc05e10ec3fdd61b2c75b0
|
Added Python API client
|
diff --git a/apiclient b/apiclient
new file mode 120000
index 0000000..a7054c5
--- /dev/null
+++ b/apiclient
@@ -0,0 +1 @@
+../google-api-python-client/apiclient
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
d41547b62ecdcc2e36154d3ee4523054f7fb9802
|
Tweaked logging and consumer key/secret pair
|
diff --git a/TODO b/TODO
index fb73ce4..36f49cc 100644
--- a/TODO
+++ b/TODO
@@ -1,18 +1,21 @@
Buzz Chat Bot
============
Add a sensible explanation of what this bot does and why anyone would want to use it:
- mention the low-latency of using chat clients, which are always on, versus the web
- mention that GChat saves messages that you received whilst you were offline
- mention statuscasting: http://www.designingsocialinterfaces.com/patterns/Statuscasting
-Verify that phrase search works and add tests for it
-/search [some search]
Register the app so that people don't have to trust anonymous
Fix the Welcome page so that people can see it without needing to be logged in
Update the web page so that it's more informative and doesn't require you login before it tells you anything
-Update the PRD - describing this
+When someone adds the bot to their roster, send them a link to the app's website so that they can do the oauth dance
+When someone visits the website and does the OAuth dance, send them a chat invite
+Profile page should show the email address of the current user.
+
+Verify that phrase search works and add tests for it
+/search [some search]
+Update the PRD - describing this bot
Work out how to handle location-based Track and complex searches. Perhaps using the web interface?
Use Bob Wyman's trick where /track initially does a /search and gives you the first 10 results to verify that it's worked
File a bug for language indexing in search
File a bug for search by actor.id
-When someone adds the bot to their roster, send them a link to the app's website so that they can do the oauth dance
-When someone visits the website and does the OAuth dance, send them a chat invite
+
diff --git a/main.py b/main.py
index e283f43..923c476 100644
--- a/main.py
+++ b/main.py
@@ -1,115 +1,115 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
import oauth_handlers
import os
import settings
import xmpp
import pshb
import simple_buzz_wrapper
class ProfileViewingHandler(webapp.RequestHandler):
@login_required
def get(self):
user_token = oauth_handlers.UserToken.get_current_user_token()
buzz_wrapper = simple_buzz_wrapper.SimpleBuzzWrapper(user_token)
user_profile_data = buzz_wrapper.get_profile()
template_values = {'user_profile_data': user_profile_data, 'access_token': user_token.access_token_string}
path = os.path.join(os.path.dirname(__file__), 'profile.html')
self.response.out.write(template.render(path, template_values))
class PostsHandler(webapp.RequestHandler):
def _get_subscription(self):
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
return subscription
def get(self):
"""Show all the resources in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
- logging.info("New content: %s" % self.request.body)
+ logging.debug("New content: %s" % self.request.body)
id = self.request.get('id')
# If this is a hub challenge
if self.request.get('hub.challenge'):
# If this subscription exists
mode = self.request.get('hub.mode')
topic = self.request.get('hub.topic')
if mode == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
elif mode == "unsubscribe" and not xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
else:
self.response.set_status(404)
self.response.out.write("Challenge failed")
logging.info("Challenge failed for feed: %s" % topic)
# Once a challenge has been issued there's no point in returning anything other than challenge passed or failed
return
def post(self):
"""Create a new resource in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
- logging.info("New content: %s" % self.request.body)
+ logging.debug("New content: %s" % self.request.body)
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
if not subscription:
self.response.set_status(404)
self.response.out.write("No such subscription")
logging.warning('No subscription for %s' % id)
return
subscriber = subscription.subscriber
search_term = subscription.search_term
parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB)
url = parser.extractFeedUrl()
if not parser.dataValid():
parser.logErrors()
self.response.out.write("Bad entries: %s" % parser.data)
return
else:
posts = parser.extractPosts()
logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url))
xmpp.send_posts(posts, subscriber, search_term)
self.response.set_status(200)
application = webapp.WSGIApplication([
('/', oauth_handlers.WelcomeHandler),
('/delete_tokens', oauth_handlers.TokenDeletionHandler),
('/finish_dance', oauth_handlers.DanceFinishingHandler),
('/profile', ProfileViewingHandler),
('/posts', PostsHandler),
('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
diff --git a/settings.py b/settings.py
index 644a5a0..a8c276b 100644
--- a/settings.py
+++ b/settings.py
@@ -1,49 +1,52 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
APP_NAME = "buzzchatbot"
#PSHB settings
# This is the token that will act as a shared secret to verify that this application is the one that registered the given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
-# OAuth consumer key and secret - you should probably leave these alone
+# OAuth consumer key and secret - you should change these to 'anonymous' unless you really are buzzchatbot.appspot.com
+# Alternatively you could go here: https://www.google.com/accounts/ManageDomains and register your instance so that you'll get your own consumer key and consumer secret
+#CONSUMER_KEY = 'buzzchatbot.appspot.com'
+#CONSUMER_SECRET = 'tcw1rCMgLVY556Y0Q4rW/RnK'
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
# OAuth callback URL
CALLBACK_URL = 'http://%s.appspot.com/finish_dance' % APP_NAME
-# Installation specific config ends.
\ No newline at end of file
+# Installation specific config ends.
|
adewale/Buzz-Chat-Bot
|
642ffa5ca2c00483fa800aff9e332a71dc2d0014
|
Added a rationale for the bot to the README
|
diff --git a/README b/README
index 226e3ee..5fb7360 100644
--- a/README
+++ b/README
@@ -1,42 +1,55 @@
This is an experimental jaiku-style chat bot for Google Buzz.
If it breaks you get to keep both pieces.
What does it do?
================
At the moment it lets you ask for:
/help Prints out this message
/track [search term] Starts tracking the given search term and returns the id for your subscription
/untrack [id] Removes your subscription for that id
/list Lists all search terms and ids currently being tracked by you
/about Tells you which instance of the Buzz Chat Bot you are using
/post [some message] Posts that message to Buzz
+Why does it exist?
+==================
+There are 2 sets of reasons why this bot exists.
+
+1- I wanted to create a demo app (using the new Python client library: http://code.google.com/p/google-api-python-client/ ) which would show people a different kind of Buzz app. It's not trying to be a slightly different clone of the existing UI.
+2- My experience with Jaiku and Friendfeed taught me that chat interfaces have a number of advantage over web interfaces:
+- they're quicker since you can't beat the latency of alt-tabbing to Adium
+- they're always on
+- they're transient so you don't feel inundated if you track lots of keywords or see lots of posts because they all just flow by
+- they encourage statuscasting: http://www.designingsocialinterfaces.com/patterns/Statuscasting which makes for a more conversational experience
+- they allow people and brands to conveniently track keywords without having to learn how PSHB works
+
What does it require?
=====================
App Engine
Python
Tests
=====
To run the tests you need gae-testbed, nose and nose-gae. So...
sudo easy_install gaetestbed
sudo easy_install nose
sudo easy_install nosegae
They can be run like this:
nosetests --with-gae tracker_tests.py
Although I prefer to do something like this:
nosetests --with-gae *test*py
INSTALLATION
+============
This isn't yet ready for installation by people who don't feel like changing the Python code. However if you feel brave you should:
- Register an AppEngine application at http://appengine.google.com/start/createapp?
- Change the app.yaml file to have the same Application Identifier as your application.
- Take a look at settings.py
-- Change the settings.APP_NAME constant to have the same Application Identifier as your application.
-- Change the settings.SECRET_TOKEN from the default
- Use the Google App Engine Launcher: http://code.google.com/appengine/downloads.html#Google_App_Engine_SDK_for_Python to deploy the application.
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
a62ba0f4bfb6ce3f6b52101c858aa884d4b182e9
|
Added a TODO list
|
diff --git a/TODO b/TODO
new file mode 100644
index 0000000..7f8e22f
--- /dev/null
+++ b/TODO
@@ -0,0 +1,14 @@
+Buzz Chat Bot
+============
+Verify that phrase search works and add tests for it
+/search [some search]
+Register the app so that people don't have to trust anonymous
+Fix the Welcome page so that people can see it without needing to be logged in
+Update the web page so that it's more informative and doesn't require you login before it tells you anything
+Update the PRD - describing this
+Work out how to handle location-based Track and complex searches. Perhaps using the web interface?
+Use Bob Wyman's trick where /track initially does a /search and gives you the first 10 results to verify that it's worked
+File a bug for language indexing in search
+File a bug for search by actor.id
+When someone adds the bot to their roster, send them a link to the app's website so that they can do the oauth dance
+When someone visits the website and does the OAuth dance, send them a chat invite
diff --git a/app.yaml b/app.yaml
index 522fb2a..e30bf45 100644
--- a/app.yaml
+++ b/app.yaml
@@ -1,15 +1,15 @@
-application: favedby
+application: buzzchatbot
version: 1
runtime: python
api_version: 1
handlers:
- url: /css
static_dir: css
- url: /images
static_dir: images
- url: /.*
script: main.py
inbound_services:
- xmpp_message
\ No newline at end of file
diff --git a/settings.py b/settings.py
index fa97faa..644a5a0 100644
--- a/settings.py
+++ b/settings.py
@@ -1,49 +1,49 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-APP_NAME = "favedby"
+APP_NAME = "buzzchatbot"
#PSHB settings
# This is the token that will act as a shared secret to verify that this application is the one that registered the given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
# OAuth consumer key and secret - you should probably leave these alone
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
# OAuth callback URL
CALLBACK_URL = 'http://%s.appspot.com/finish_dance' % APP_NAME
# Installation specific config ends.
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
64cca83f862e092bb5d848268c3c0fabb8163fe3
|
Added documentation line for /post which allows people to post messages to Buzz from the chat bot
|
diff --git a/xmpp.py b/xmpp.py
index 6882cb8..822f3a8 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,233 +1,234 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
import logging
import urllib
import oauth_handlers
import pshb
import settings
import simple_buzz_wrapper
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
commands = [
'/help Prints out this message',
'/track [search term] Starts tracking the given search term and returns the id for your subscription',
'/untrack [id] Removes your subscription for that id',
'/list Lists all search terms and ids currently being tracked by you',
- '/about Tells you which instance of the Buzz Chat Bot you are using'
+ '/about Tells you which instance of the Buzz Chat Bot you are using',
+ '/post [some message] Posts that message to Buzz'
]
class XmppHandler(xmpp_handlers.CommandHandler):
def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
self.buzz_wrapper = buzz_wrapper
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: /untrack [id]')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
message_body = message.body[len('/post'):]
url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
c2b7bf904b5e21e1b70ecfef7d1c53c90e044785
|
Extracted out a simple buzz wrapper and added basic validation since empty title or content strings cause the Buzz servers to return a 503.
|
diff --git a/functional_tests.py b/functional_tests.py
index 7b5a419..1696bce 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,207 +1,223 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
-from xmpp import Tracker, XmppHandler, SimpleBuzzClient
+from xmpp import Tracker, XmppHandler
import oauth_handlers
import settings
+import simple_buzz_wrapper
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
-class StubSimpleBuzzClient(SimpleBuzzClient):
+class StubSimpleBuzzWrapper(simple_buzz_wrapper.SimpleBuzzWrapper):
def __init__(self):
self.url = 'some fake url'
def post(self, sender, message_body):
+ self.message = message_body
return self.url
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '/track %s' % search_term
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='/untrack 777')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
- subscription = self._setup_subscription()
+ self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='/untrack jaiku')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='/untrack')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='/about')
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_oauth_token(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='/post some message')
handler.post_command(message=message)
expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_post_command_warns_users_with_no_access_token(self):
- stub = StubSimpleBuzzClient()
- handler = XmppHandler(buzz_client=stub)
+ stub = StubSimpleBuzzWrapper()
+ handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.put()
message = StubMessage(sender=sender, body='/post some message')
handler.post_command(message=message)
expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
self.assertEquals(expected_item, message.message_to_send)
self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
def test_post_command_posts_message_for_user_with_oauth_token(self):
- stub = StubSimpleBuzzClient()
- handler = XmppHandler(buzz_client=stub)
+ stub = StubSimpleBuzzWrapper()
+ handler = XmppHandler(buzz_wrapper=stub)
sender = '[email protected]'
user_token = oauth_handlers.UserToken(email_address=sender)
user_token.access_token_string = 'some thing that looks like an access token from a distance'
user_token.put()
message = StubMessage(sender=sender, body='/post some message')
handler.post_command(message=message)
expected_item = 'Posted: %s' % stub.url
- self.assertEquals(expected_item, message.message_to_send)
\ No newline at end of file
+ self.assertEquals(expected_item, message.message_to_send)
+
+ def test_post_command_strips_command_from_posted_message(self):
+ stub = StubSimpleBuzzWrapper()
+ handler = XmppHandler(buzz_wrapper=stub)
+ sender = '[email protected]'
+
+ user_token = oauth_handlers.UserToken(email_address=sender)
+ user_token.access_token_string = 'some thing that looks like an access token from a distance'
+ user_token.put()
+ message = StubMessage(sender=sender, body='/post some message')
+
+ handler.post_command(message=message)
+ expected_item = ' some message'
+ self.assertEquals(expected_item, stub.message)
\ No newline at end of file
diff --git a/main.py b/main.py
index 9f73dc1..e283f43 100644
--- a/main.py
+++ b/main.py
@@ -1,115 +1,115 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
-import buzz_gae_client
import logging
import oauth_handlers
import os
import settings
import xmpp
import pshb
+import simple_buzz_wrapper
class ProfileViewingHandler(webapp.RequestHandler):
@login_required
def get(self):
user_token = oauth_handlers.UserToken.get_current_user_token()
- simple_buzz_client = xmpp.SimpleBuzzClient(user_token)
- user_profile_data = simple_buzz_client.get_profile()
+ buzz_wrapper = simple_buzz_wrapper.SimpleBuzzWrapper(user_token)
+ user_profile_data = buzz_wrapper.get_profile()
template_values = {'user_profile_data': user_profile_data, 'access_token': user_token.access_token_string}
path = os.path.join(os.path.dirname(__file__), 'profile.html')
self.response.out.write(template.render(path, template_values))
class PostsHandler(webapp.RequestHandler):
def _get_subscription(self):
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
return subscription
def get(self):
"""Show all the resources in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.info("New content: %s" % self.request.body)
id = self.request.get('id')
# If this is a hub challenge
if self.request.get('hub.challenge'):
# If this subscription exists
mode = self.request.get('hub.mode')
topic = self.request.get('hub.topic')
if mode == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
elif mode == "unsubscribe" and not xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
else:
self.response.set_status(404)
self.response.out.write("Challenge failed")
logging.info("Challenge failed for feed: %s" % topic)
# Once a challenge has been issued there's no point in returning anything other than challenge passed or failed
return
def post(self):
"""Create a new resource in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.info("New content: %s" % self.request.body)
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
if not subscription:
self.response.set_status(404)
self.response.out.write("No such subscription")
logging.warning('No subscription for %s' % id)
return
subscriber = subscription.subscriber
search_term = subscription.search_term
parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB)
url = parser.extractFeedUrl()
if not parser.dataValid():
parser.logErrors()
self.response.out.write("Bad entries: %s" % parser.data)
return
else:
posts = parser.extractPosts()
logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url))
xmpp.send_posts(posts, subscriber, search_term)
self.response.set_status(200)
application = webapp.WSGIApplication([
('/', oauth_handlers.WelcomeHandler),
('/delete_tokens', oauth_handlers.TokenDeletionHandler),
('/finish_dance', oauth_handlers.DanceFinishingHandler),
('/profile', ProfileViewingHandler),
('/posts', PostsHandler),
('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
diff --git a/settings.py b/settings.py
index 57b6339..fa97faa 100644
--- a/settings.py
+++ b/settings.py
@@ -1,37 +1,49 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
-
+# Copyright (C) 2010 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
APP_NAME = "favedby"
#PSHB settings
# This is the token that will act as a shared secret to verify that this application is the one that registered the given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
# OAuth consumer key and secret - you should probably leave these alone
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
# OAuth callback URL
CALLBACK_URL = 'http://%s.appspot.com/finish_dance' % APP_NAME
# Installation specific config ends.
\ No newline at end of file
diff --git a/simple_buzz_wrapper.py b/simple_buzz_wrapper.py
new file mode 100644
index 0000000..0257d4f
--- /dev/null
+++ b/simple_buzz_wrapper.py
@@ -0,0 +1,55 @@
+# Copyright (C) 2010 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import buzz_gae_client
+import settings
+import oauth_handlers
+import logging
+
+class SimpleBuzzWrapper(object):
+ "Simple client that exposes the bare minimum set of Buzz operations"
+
+ def __init__(self, user_token=None):
+ if user_token:
+ self.current_user_token = user_token
+ self.builder = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
+
+ def post(self, sender, message_body):
+ if message_body is None or message_body.strip() is '':
+ return None
+
+ user_token = oauth_handlers.UserToken.find_by_email_address(sender)
+ api_client = self.builder.build_api_client(user_token.get_access_token())
+
+ #TODO(ade) What happens with users who have hidden their email address?
+ # Switch to @me so it won't matter
+ user_id = sender.split('@')[0]
+
+ activities = api_client.activities()
+ logging.info('Retrieved activities for: %s' % user_id)
+ activity = activities.insert(userId=user_id, body={
+ 'title': message_body,
+ 'object': {
+ 'content': message_body,
+ 'type': 'note'}
+ }
+ ).execute()
+ url = activity['links']['alternate'][0]['href']
+ logging.info('Just created: %s' % url)
+ return url
+
+ def get_profile(self):
+ api_client = self.builder.build_api_client(self.current_user_token.get_access_token())
+ user_profile_data = api_client.people().get(userId='@me').execute()
+ return user_profile_data
+
diff --git a/simple_buzz_wrapper_tests.py b/simple_buzz_wrapper_tests.py
new file mode 100644
index 0000000..e1c1cf3
--- /dev/null
+++ b/simple_buzz_wrapper_tests.py
@@ -0,0 +1,29 @@
+# Copyright (C) 2010 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import simple_buzz_wrapper
+import unittest
+
+class SimpleBuzzWrapperTest(unittest.TestCase):
+ def test_wrapper_rejects_empty_message(self):
+ wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
+ self.assertEquals(None, wrapper.post('[email protected]', ''))
+
+ def test_wrapper_rejects_messsage_containing_only_whitespace(self):
+ wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
+ self.assertEquals(None, wrapper.post('[email protected]', ' '))
+
+ def test_wrapper_rejects_none_message(self):
+ wrapper = simple_buzz_wrapper.SimpleBuzzWrapper()
+ self.assertEquals(None, wrapper.post('[email protected]', None))
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index 08718cd..6882cb8 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,266 +1,233 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
-import buzz_gae_client
import logging
import urllib
import oauth_handlers
import pshb
import settings
+import simple_buzz_wrapper
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
-class SimpleBuzzClient(object):
- "Simple client that exposes the bare minimum set of Buzz operations"
-
- def __init__(self, user_token=None):
- if user_token:
- self.current_user_token = user_token
- self.builder = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
-
- def post(self, sender, message_body):
- user_token = oauth_handlers.UserToken.find_by_email_address(sender)
- api_client = self.builder.build_api_client(user_token.get_access_token())
-
- #TODO(ade) What happens with users who have hidden their email address?
- user_id = sender.split('@')[0]
-
- activities = api_client.activities()
- logging.info('Retrieved activities for: %s' % user_id)
- activity = activities.insert(userId=user_id, body={
- 'title': message_body,
- 'object': {
- 'content': message_body,
- 'type': 'note'}
- }
- ).execute()
- url = activity['links']['alternate'][0]['href']
- logging.info('Just created: %s' % url)
- return url
-
- def get_profile(self):
- api_client = self.builder.build_api_client(self.current_user_token.get_access_token())
- user_profile_data = api_client.people().get(userId='@me').execute()
- return user_profile_data
-
-
commands = [
'/help Prints out this message',
'/track [search term] Starts tracking the given search term and returns the id for your subscription',
'/untrack [id] Removes your subscription for that id',
'/list Lists all search terms and ids currently being tracked by you',
'/about Tells you which instance of the Buzz Chat Bot you are using'
]
class XmppHandler(xmpp_handlers.CommandHandler):
- def __init__(self, buzz_client=SimpleBuzzClient()):
- self.buzz_client = buzz_client
+ def __init__(self, buzz_wrapper=simple_buzz_wrapper.SimpleBuzzWrapper()):
+ self.buzz_wrapper = buzz_wrapper
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: /untrack [id]')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
- url = self.buzz_client.post(sender, message.body)
+ message_body = message.body[len('/post'):]
+ url = self.buzz_wrapper.post(sender, message_body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
a6c2b1c283ff389984b610b2a27fac8dd4abca84
|
Can post from chat bot. Messages turn up as both the body and the content of the post identica-style.
|
diff --git a/main.py b/main.py
index 181c2e0..9f73dc1 100644
--- a/main.py
+++ b/main.py
@@ -1,116 +1,115 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
import buzz_gae_client
import logging
import oauth_handlers
import os
import settings
import xmpp
import pshb
class ProfileViewingHandler(webapp.RequestHandler):
@login_required
def get(self):
user_token = oauth_handlers.UserToken.get_current_user_token()
- client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
- api_client = client.build_api_client(user_token.get_access_token())
- user_profile_data = api_client.people().get(userId='@me')
+ simple_buzz_client = xmpp.SimpleBuzzClient(user_token)
+ user_profile_data = simple_buzz_client.get_profile()
template_values = {'user_profile_data': user_profile_data, 'access_token': user_token.access_token_string}
path = os.path.join(os.path.dirname(__file__), 'profile.html')
self.response.out.write(template.render(path, template_values))
class PostsHandler(webapp.RequestHandler):
def _get_subscription(self):
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
return subscription
def get(self):
"""Show all the resources in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.info("New content: %s" % self.request.body)
id = self.request.get('id')
# If this is a hub challenge
if self.request.get('hub.challenge'):
# If this subscription exists
mode = self.request.get('hub.mode')
topic = self.request.get('hub.topic')
if mode == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
elif mode == "unsubscribe" and not xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
else:
self.response.set_status(404)
self.response.out.write("Challenge failed")
logging.info("Challenge failed for feed: %s" % topic)
# Once a challenge has been issued there's no point in returning anything other than challenge passed or failed
return
def post(self):
"""Create a new resource in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.info("New content: %s" % self.request.body)
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
if not subscription:
self.response.set_status(404)
self.response.out.write("No such subscription")
logging.warning('No subscription for %s' % id)
return
subscriber = subscription.subscriber
search_term = subscription.search_term
parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB)
url = parser.extractFeedUrl()
if not parser.dataValid():
parser.logErrors()
self.response.out.write("Bad entries: %s" % parser.data)
return
else:
posts = parser.extractPosts()
logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url))
xmpp.send_posts(posts, subscriber, search_term)
self.response.set_status(200)
application = webapp.WSGIApplication([
('/', oauth_handlers.WelcomeHandler),
('/delete_tokens', oauth_handlers.TokenDeletionHandler),
('/finish_dance', oauth_handlers.DanceFinishingHandler),
('/profile', ProfileViewingHandler),
('/posts', PostsHandler),
('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
diff --git a/xmpp.py b/xmpp.py
index a550e31..08718cd 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,257 +1,266 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
import buzz_gae_client
import logging
import urllib
import oauth_handlers
import pshb
import settings
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
class SimpleBuzzClient(object):
"Simple client that exposes the bare minimum set of Buzz operations"
- def __init__(self):
+ def __init__(self, user_token=None):
+ if user_token:
+ self.current_user_token = user_token
self.builder = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
def post(self, sender, message_body):
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
api_client = self.builder.build_api_client(user_token.get_access_token())
#TODO(ade) What happens with users who have hidden their email address?
user_id = sender.split('@')[0]
activities = api_client.activities()
+ logging.info('Retrieved activities for: %s' % user_id)
activity = activities.insert(userId=user_id, body={
'title': message_body,
'object': {
- 'content': u'',
+ 'content': message_body,
'type': 'note'}
}
).execute()
url = activity['links']['alternate'][0]['href']
logging.info('Just created: %s' % url)
return url
+ def get_profile(self):
+ api_client = self.builder.build_api_client(self.current_user_token.get_access_token())
+ user_profile_data = api_client.people().get(userId='@me').execute()
+ return user_profile_data
+
+
commands = [
'/help Prints out this message',
'/track [search term] Starts tracking the given search term and returns the id for your subscription',
'/untrack [id] Removes your subscription for that id',
'/list Lists all search terms and ids currently being tracked by you',
'/about Tells you which instance of the Buzz Chat Bot you are using'
]
class XmppHandler(xmpp_handlers.CommandHandler):
def __init__(self, buzz_client=SimpleBuzzClient()):
self.buzz_client = buzz_client
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: /untrack [id]')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
message_builder.add(about_message)
reply(message_builder, message)
def post_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
user_token = oauth_handlers.UserToken.find_by_email_address(sender)
if not user_token:
message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
elif not user_token.access_token_string:
# User didn't finish the OAuth dance so we make them start again
user_token.delete()
message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
else:
url = self.buzz_client.post(sender, message.body)
message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
8e84be2d3dbc4d8daa112cf92566a834d4ac4181
|
Extracted out oauth_handlers.py. Added the start of Buzz support although I'm currently getting 503s from Buzz's back-end and the profile page is broken since the new Buzz libraries are now using the command pattern.
|
diff --git a/functional_tests.py b/functional_tests.py
index 69d9f0e..7b5a419 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,161 +1,207 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
-from xmpp import Tracker, XmppHandler
-import logging
+from xmpp import Tracker, XmppHandler, SimpleBuzzClient
+
+import oauth_handlers
import settings
+class StubMessage(object):
+ def __init__(self, sender='[email protected]', body=''):
+ self.sender = sender
+ self.body = body
+
+ def reply(self, message_to_send, raw_xml=False):
+ self.message_to_send = message_to_send
+
+class StubSimpleBuzzClient(SimpleBuzzClient):
+ def __init__(self):
+ self.url = 'some fake url'
+ def post(self, sender, message_body):
+ return self.url
+
+
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '/track %s' % search_term
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
-class StubMessage(object):
- def __init__(self, sender='[email protected]', body=''):
- self.sender = sender
- self.body = body
-
- def reply(self, message_to_send, raw_xml=False):
- self.message_to_send = message_to_send
-
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='/untrack 777')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
subscription = self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='/untrack jaiku')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='/untrack')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_show_exactly_one_subscription(self):
handler = XmppHandler()
sender = '[email protected]'
subscription = self._setup_subscription(sender=sender, search_term='searchA')
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertEquals(expected_item, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='/about')
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
- self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
\ No newline at end of file
+ self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
+
+ def test_post_command_warns_users_with_no_oauth_token(self):
+ handler = XmppHandler()
+ sender = '[email protected]'
+ message = StubMessage(sender=sender, body='/post some message')
+
+ handler.post_command(message=message)
+
+ expected_item = 'You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
+ self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
+
+ def test_post_command_warns_users_with_no_access_token(self):
+ stub = StubSimpleBuzzClient()
+ handler = XmppHandler(buzz_client=stub)
+ sender = '[email protected]'
+
+ user_token = oauth_handlers.UserToken(email_address=sender)
+ user_token.put()
+ message = StubMessage(sender=sender, body='/post some message')
+
+ handler.post_command(message=message)
+ expected_item = 'You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME)
+ self.assertEquals(expected_item, message.message_to_send)
+ self.assertEquals(None, oauth_handlers.UserToken.find_by_email_address(sender))
+
+ def test_post_command_posts_message_for_user_with_oauth_token(self):
+ stub = StubSimpleBuzzClient()
+ handler = XmppHandler(buzz_client=stub)
+ sender = '[email protected]'
+
+ user_token = oauth_handlers.UserToken(email_address=sender)
+ user_token.access_token_string = 'some thing that looks like an access token from a distance'
+ user_token.put()
+ message = StubMessage(sender=sender, body='/post some message')
+
+ handler.post_command(message=message)
+ expected_item = 'Posted: %s' % stub.url
+ self.assertEquals(expected_item, message.message_to_send)
\ No newline at end of file
diff --git a/main.py b/main.py
index 5d3d531..181c2e0 100644
--- a/main.py
+++ b/main.py
@@ -1,217 +1,116 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-from google.appengine.api import users
-from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
-from google.appengine.api import users
import buzz_gae_client
import logging
+import oauth_handlers
import os
import settings
import xmpp
import pshb
-
-class UserToken(db.Model):
-# The user_id is the key_name so we don't have to make it an explicit property
- request_token_string = db.StringProperty()
- access_token_string = db.StringProperty()
- email_address = db.StringProperty()
-
- def get_request_token(self):
- "Returns request token as a dictionary of tokens including oauth_token, oauth_token_secret and oauth_callback_confirmed."
- return eval(self.request_token_string)
-
- def set_access_token(self, access_token):
- access_token_string = repr(access_token)
- self.access_token_string = access_token_string
-
- def get_access_token(self):
- "Returns access token as a dictionary of tokens including consumer_key, consumer_secret, oauth_token and oauth_token_secret"
- return eval(self.access_token_string)
-
- @staticmethod
- def create_user_token(request_token):
- user = users.get_current_user()
- user_id = user.user_id()
- request_token_string = repr(request_token)
-
- # TODO(ade) Support users who sign in to AppEngine with a federated identity aka OpenId
- email = user.email()
-
- logging.info('Creating user token: key_name: %s request_token_string: %s email_address: %s' % (
- user_id, request_token_string, email))
-
- return UserToken(key_name=user_id, request_token_string=request_token_string, access_token_string='',
- email_address=email)
-
- @staticmethod
- def get_current_user_token():
- user = users.get_current_user()
- user_token = UserToken.get_by_key_name(user.user_id())
- return user_token
-
- @staticmethod
- def access_token_exists():
- user = users.get_current_user()
- user_token = UserToken.get_by_key_name(user.user_id())
- logging.info('user_token: %s' % user_token)
- return user_token and user_token.access_token_string
-
-
-class WelcomeHandler(webapp.RequestHandler):
- @login_required
- def get(self):
- logging.info("Request body %s" % self.request.body)
- template_values = {}
- if UserToken.access_token_exists():
- template_values['access_token_exists'] = 'true'
- else:
- # Generate the request token
- client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
- request_token = client.get_request_token(settings.CALLBACK_URL)
-
- # Create the request token and associate it with the current user
- user_token = UserToken.create_user_token(request_token)
- UserToken.put(user_token)
-
- authorisation_url = client.generate_authorisation_url(request_token)
- logging.info('Authorisation URL is: %s' % authorisation_url)
- template_values['destination'] = authorisation_url
-
- path = os.path.join(os.path.dirname(__file__), 'welcome.html')
- self.response.out.write(template.render(path, template_values))
-
-
-class TokenDeletionHandler(webapp.RequestHandler):
- def post(self):
- user_token = UserToken.get_current_user_token()
- UserToken.delete(user_token)
- self.redirect('/')
-
-
-class DanceFinishingHandler(webapp.RequestHandler):
- def get(self):
- logging.info("Request body %s" % self.request.body)
- oauth_verifier = self.request.get('oauth_verifier')
-
- client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
- user_token = UserToken.get_current_user_token()
- request_token = user_token.get_request_token()
- access_token = client.upgrade_to_access_token(request_token, oauth_verifier)
- logging.info('SUCCESS: Received access token.')
-
- user_token.set_access_token(access_token)
- UserToken.put(user_token)
- logging.debug('Access token was: %s' % user_token.access_token_string)
-
- self.redirect('/profile')
-
-
class ProfileViewingHandler(webapp.RequestHandler):
@login_required
def get(self):
- user_token = UserToken.get_current_user_token()
+ user_token = oauth_handlers.UserToken.get_current_user_token()
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
api_client = client.build_api_client(user_token.get_access_token())
user_profile_data = api_client.people().get(userId='@me')
- template_values = {}
- template_values['user_profile_data'] = user_profile_data
- template_values['access_token'] = user_token.access_token_string
+ template_values = {'user_profile_data': user_profile_data, 'access_token': user_token.access_token_string}
path = os.path.join(os.path.dirname(__file__), 'profile.html')
self.response.out.write(template.render(path, template_values))
class PostsHandler(webapp.RequestHandler):
def _get_subscription(self):
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
return subscription
def get(self):
"""Show all the resources in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.info("New content: %s" % self.request.body)
id = self.request.get('id')
# If this is a hub challenge
if self.request.get('hub.challenge'):
# If this subscription exists
mode = self.request.get('hub.mode')
topic = self.request.get('hub.topic')
if mode == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
elif mode == "unsubscribe" and not xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
else:
self.response.set_status(404)
self.response.out.write("Challenge failed")
logging.info("Challenge failed for feed: %s" % topic)
# Once a challenge has been issued there's no point in returning anything other than challenge passed or failed
return
def post(self):
"""Create a new resource in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.info("New content: %s" % self.request.body)
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
if not subscription:
self.response.set_status(404)
self.response.out.write("No such subscription")
logging.warning('No subscription for %s' % id)
return
subscriber = subscription.subscriber
search_term = subscription.search_term
parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB)
url = parser.extractFeedUrl()
if not parser.dataValid():
parser.logErrors()
self.response.out.write("Bad entries: %s" % parser.data)
return
else:
posts = parser.extractPosts()
logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url))
xmpp.send_posts(posts, subscriber, search_term)
self.response.set_status(200)
application = webapp.WSGIApplication([
- ('/', WelcomeHandler),
- ('/delete_tokens', TokenDeletionHandler),
- ('/finish_dance', DanceFinishingHandler),
+ ('/', oauth_handlers.WelcomeHandler),
+ ('/delete_tokens', oauth_handlers.TokenDeletionHandler),
+ ('/finish_dance', oauth_handlers.DanceFinishingHandler),
('/profile', ProfileViewingHandler),
('/posts', PostsHandler),
('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
diff --git a/oauth_handlers.py b/oauth_handlers.py
new file mode 100644
index 0000000..f7e532e
--- /dev/null
+++ b/oauth_handlers.py
@@ -0,0 +1,126 @@
+# Copyright (C) 2010 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from google.appengine.ext import db
+from google.appengine.ext import webapp
+from google.appengine.ext.webapp import template
+from google.appengine.ext.webapp.util import login_required
+from google.appengine.api import users
+
+import buzz_gae_client
+import logging
+import os
+import settings
+
+class UserToken(db.Model):
+# The user_id is the key_name so we don't have to make it an explicit property
+ request_token_string = db.StringProperty()
+ access_token_string = db.StringProperty()
+ email_address = db.StringProperty()
+
+ def get_request_token(self):
+ "Returns request token as a dictionary of tokens including oauth_token, oauth_token_secret and oauth_callback_confirmed."
+ return eval(self.request_token_string)
+
+ def set_access_token(self, access_token):
+ access_token_string = repr(access_token)
+ self.access_token_string = access_token_string
+
+ def get_access_token(self):
+ "Returns access token as a dictionary of tokens including consumer_key, consumer_secret, oauth_token and oauth_token_secret"
+ return eval(self.access_token_string)
+
+ @staticmethod
+ def create_user_token(request_token):
+ user = users.get_current_user()
+ user_id = user.user_id()
+ request_token_string = repr(request_token)
+
+ # TODO(ade) Support users who sign in to AppEngine with a federated identity aka OpenId
+ email = user.email()
+
+ logging.info('Creating user token: key_name: %s request_token_string: %s email_address: %s' % (
+ user_id, request_token_string, email))
+
+ return UserToken(key_name=user_id, request_token_string=request_token_string, access_token_string='',
+ email_address=email)
+
+ @staticmethod
+ def get_current_user_token():
+ user = users.get_current_user()
+ user_token = UserToken.get_by_key_name(user.user_id())
+ return user_token
+
+ @staticmethod
+ def access_token_exists():
+ user = users.get_current_user()
+ user_token = UserToken.get_by_key_name(user.user_id())
+ logging.info('user_token: %s' % user_token)
+ return user_token and user_token.access_token_string
+
+ @staticmethod
+ def find_by_email_address(email_address):
+ user_tokens = UserToken.gql('WHERE email_address = :1', email_address).fetch(1)
+ if user_tokens:
+ return user_tokens[0] # The result of the query is a list
+ else:
+ return None
+
+class WelcomeHandler(webapp.RequestHandler):
+ @login_required
+ def get(self):
+ logging.info("Request body %s" % self.request.body)
+ template_values = {}
+ if UserToken.access_token_exists():
+ template_values['access_token_exists'] = 'true'
+ else:
+ # Generate the request token
+ client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
+ request_token = client.get_request_token(settings.CALLBACK_URL)
+
+ # Create the request token and associate it with the current user
+ user_token = UserToken.create_user_token(request_token)
+ UserToken.put(user_token)
+
+ authorisation_url = client.generate_authorisation_url(request_token)
+ logging.info('Authorisation URL is: %s' % authorisation_url)
+ template_values['destination'] = authorisation_url
+
+ path = os.path.join(os.path.dirname(__file__), 'welcome.html')
+ self.response.out.write(template.render(path, template_values))
+
+
+class TokenDeletionHandler(webapp.RequestHandler):
+ def post(self):
+ user_token = UserToken.get_current_user_token()
+ UserToken.delete(user_token)
+ self.redirect('/')
+
+
+class DanceFinishingHandler(webapp.RequestHandler):
+ def get(self):
+ logging.info("Request body %s" % self.request.body)
+ oauth_verifier = self.request.get('oauth_verifier')
+
+ client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
+ user_token = UserToken.get_current_user_token()
+ request_token = user_token.get_request_token()
+ access_token = client.upgrade_to_access_token(request_token, oauth_verifier)
+ logging.info('SUCCESS: Received access token.')
+
+ user_token.set_access_token(access_token)
+ UserToken.put(user_token)
+ logging.debug('Access token was: %s' % user_token.access_token_string)
+
+ self.redirect('/profile')
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index 19eb0f0..a550e31 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,211 +1,257 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-from django.utils import html
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
+import buzz_gae_client
import logging
import urllib
+import oauth_handlers
import pshb
import settings
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
- return Subscription.get_by_id(int(id)) != None
+ return Subscription.get_by_id(int(id)) is not None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
+class SimpleBuzzClient(object):
+ "Simple client that exposes the bare minimum set of Buzz operations"
+
+ def __init__(self):
+ self.builder = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
+
+ def post(self, sender, message_body):
+ user_token = oauth_handlers.UserToken.find_by_email_address(sender)
+ api_client = self.builder.build_api_client(user_token.get_access_token())
+
+ #TODO(ade) What happens with users who have hidden their email address?
+ user_id = sender.split('@')[0]
+
+ activities = api_client.activities()
+ activity = activities.insert(userId=user_id, body={
+ 'title': message_body,
+ 'object': {
+ 'content': u'',
+ 'type': 'note'}
+ }
+ ).execute()
+ url = activity['links']['alternate'][0]['href']
+ logging.info('Just created: %s' % url)
+ return url
+
+
commands = [
'/help Prints out this message',
'/track [search term] Starts tracking the given search term and returns the id for your subscription',
'/untrack [id] Removes your subscription for that id',
'/list Lists all search terms and ids currently being tracked by you',
'/about Tells you which instance of the Buzz Chat Bot you are using'
]
class XmppHandler(xmpp_handlers.CommandHandler):
+ def __init__(self, buzz_client=SimpleBuzzClient()):
+ self.buzz_client = buzz_client
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: /untrack [id]')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
if subscriptions_query.count() > 0:
for subscription in subscriptions_query:
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
- message_builder.add('Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME))
+ about_message = 'Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME)
+ message_builder.add(about_message)
+ reply(message_builder, message)
+
+ def post_command(self, message):
+ logging.info('Received message from: %s' % message.sender)
+ message_builder = MessageBuilder()
+ sender = extract_sender_email_address(message.sender)
+ user_token = oauth_handlers.UserToken.find_by_email_address(sender)
+ if not user_token:
+ message_builder.add('You (%s) have not given access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
+ elif not user_token.access_token_string:
+ # User didn't finish the OAuth dance so we make them start again
+ user_token.delete()
+ message_builder.add('You (%s) did not complete the process for giving access to your Google Buzz account. Please do so at: http://%s.appspot.com' % (sender, settings.APP_NAME))
+ else:
+ url = self.buzz_client.post(sender, message.body)
+ message_builder.add('Posted: %s' % url)
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
911e9dbf13fa6b9b127d9178a52937bc28573b18
|
Fixed spurious 'no subsciptions' line when using /list
|
diff --git a/functional_tests.py b/functional_tests.py
index 70bfd50..69d9f0e 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,152 +1,161 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import logging
import settings
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '/track %s' % search_term
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
def test_can_validate_hub_challenge_for_unsubscribe(self):
subscription = self._setup_subscription()
subscription.delete()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='/untrack 777')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
subscription = self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='/untrack jaiku')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='/untrack')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
+ def test_list_command_can_show_exactly_one_subscription(self):
+ handler = XmppHandler()
+ sender = '[email protected]'
+ subscription = self._setup_subscription(sender=sender, search_term='searchA')
+ message = StubMessage(sender=sender, body='/list')
+ handler.list_command(message=message)
+ expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
+ self.assertEquals(expected_item, message.message_to_send)
+
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='/about')
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index 6f544e4..19eb0f0 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,209 +1,211 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.utils import html
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
import logging
import urllib
import pshb
import settings
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) != None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
commands = [
'/help Prints out this message',
'/track [search term] Starts tracking the given search term and returns the id for your subscription',
'/untrack [id] Removes your subscription for that id',
'/list Lists all search terms and ids currently being tracked by you',
'/about Tells you which instance of the Buzz Chat Bot you are using'
]
class XmppHandler(xmpp_handlers.CommandHandler):
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: /untrack [id]')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
- for subscription in Subscription.gql('WHERE subscriber = :1', sender):
- message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
+ subscriptions_query = Subscription.gql('WHERE subscriber = :1', sender)
+ if subscriptions_query.count() > 0:
+ for subscription in subscriptions_query:
+ message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
def about_command(self, message):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
message_builder.add('Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME))
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
373634d6baad6ef8dba4b7aba5ee17bb6688944a
|
Added ability to handle hub challenges for unsubscriptions
|
diff --git a/functional_tests.py b/functional_tests.py
index 8e52358..70bfd50 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,143 +1,152 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import logging
import settings
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '/track %s' % search_term
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
- def test_can_validate_hub_challenges(self):
+ def test_can_validate_hub_challenge_for_subscribe(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
+ def test_can_validate_hub_challenge_for_unsubscribe(self):
+ subscription = self._setup_subscription()
+ subscription.delete()
+ challenge = 'somechallengetoken'
+ topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
+ response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'unsubscribe', topic, subscription.id()))
+ self.assertOK(response)
+ response.mustcontain(challenge)
+
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='/untrack 777')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
subscription = self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='/untrack jaiku')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='/untrack')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_about_command_says_what_bot_is_running(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='/about')
handler.about_command(message=message)
expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
\ No newline at end of file
diff --git a/main.py b/main.py
index d239dd0..5d3d531 100644
--- a/main.py
+++ b/main.py
@@ -1,213 +1,217 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
import buzz_gae_client
import logging
import os
import settings
import xmpp
import pshb
class UserToken(db.Model):
# The user_id is the key_name so we don't have to make it an explicit property
request_token_string = db.StringProperty()
access_token_string = db.StringProperty()
email_address = db.StringProperty()
def get_request_token(self):
"Returns request token as a dictionary of tokens including oauth_token, oauth_token_secret and oauth_callback_confirmed."
return eval(self.request_token_string)
def set_access_token(self, access_token):
access_token_string = repr(access_token)
self.access_token_string = access_token_string
def get_access_token(self):
"Returns access token as a dictionary of tokens including consumer_key, consumer_secret, oauth_token and oauth_token_secret"
return eval(self.access_token_string)
@staticmethod
def create_user_token(request_token):
user = users.get_current_user()
user_id = user.user_id()
request_token_string = repr(request_token)
# TODO(ade) Support users who sign in to AppEngine with a federated identity aka OpenId
email = user.email()
logging.info('Creating user token: key_name: %s request_token_string: %s email_address: %s' % (
user_id, request_token_string, email))
return UserToken(key_name=user_id, request_token_string=request_token_string, access_token_string='',
email_address=email)
@staticmethod
def get_current_user_token():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
return user_token
@staticmethod
def access_token_exists():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
logging.info('user_token: %s' % user_token)
return user_token and user_token.access_token_string
class WelcomeHandler(webapp.RequestHandler):
@login_required
def get(self):
logging.info("Request body %s" % self.request.body)
template_values = {}
if UserToken.access_token_exists():
template_values['access_token_exists'] = 'true'
else:
# Generate the request token
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
request_token = client.get_request_token(settings.CALLBACK_URL)
# Create the request token and associate it with the current user
user_token = UserToken.create_user_token(request_token)
UserToken.put(user_token)
authorisation_url = client.generate_authorisation_url(request_token)
logging.info('Authorisation URL is: %s' % authorisation_url)
template_values['destination'] = authorisation_url
path = os.path.join(os.path.dirname(__file__), 'welcome.html')
self.response.out.write(template.render(path, template_values))
class TokenDeletionHandler(webapp.RequestHandler):
def post(self):
user_token = UserToken.get_current_user_token()
UserToken.delete(user_token)
self.redirect('/')
class DanceFinishingHandler(webapp.RequestHandler):
def get(self):
logging.info("Request body %s" % self.request.body)
oauth_verifier = self.request.get('oauth_verifier')
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
user_token = UserToken.get_current_user_token()
request_token = user_token.get_request_token()
access_token = client.upgrade_to_access_token(request_token, oauth_verifier)
logging.info('SUCCESS: Received access token.')
user_token.set_access_token(access_token)
UserToken.put(user_token)
logging.debug('Access token was: %s' % user_token.access_token_string)
self.redirect('/profile')
class ProfileViewingHandler(webapp.RequestHandler):
@login_required
def get(self):
user_token = UserToken.get_current_user_token()
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
api_client = client.build_api_client(user_token.get_access_token())
user_profile_data = api_client.people().get(userId='@me')
template_values = {}
template_values['user_profile_data'] = user_profile_data
template_values['access_token'] = user_token.access_token_string
path = os.path.join(os.path.dirname(__file__), 'profile.html')
self.response.out.write(template.render(path, template_values))
class PostsHandler(webapp.RequestHandler):
def _get_subscription(self):
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
return subscription
def get(self):
"""Show all the resources in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.info("New content: %s" % self.request.body)
id = self.request.get('id')
- # TODO(ade) Must also correctly handle unsubscription
# If this is a hub challenge
if self.request.get('hub.challenge'):
# If this subscription exists
- if self.request.get('hub.mode') == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
+ mode = self.request.get('hub.mode')
+ topic = self.request.get('hub.topic')
+ if mode == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
- logging.info("Successfully accepted challenge for feed: %s" % self.request.get('hub.topic'))
+ logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
+ elif mode == "unsubscribe" and not xmpp.Subscription.get_by_id(int(id)):
+ self.response.out.write(self.request.get('hub.challenge'))
+ logging.info("Successfully accepted %s challenge for feed: %s" % (mode, topic))
else:
self.response.set_status(404)
self.response.out.write("Challenge failed")
- logging.info("Challenge failed for feed: %s" % self.request.get('hub.topic'))
+ logging.info("Challenge failed for feed: %s" % topic)
# Once a challenge has been issued there's no point in returning anything other than challenge passed or failed
return
def post(self):
"""Create a new resource in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.info("New content: %s" % self.request.body)
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
if not subscription:
self.response.set_status(404)
self.response.out.write("No such subscription")
logging.warning('No subscription for %s' % id)
return
subscriber = subscription.subscriber
search_term = subscription.search_term
parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB)
url = parser.extractFeedUrl()
if not parser.dataValid():
parser.logErrors()
self.response.out.write("Bad entries: %s" % parser.data)
return
else:
posts = parser.extractPosts()
logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url))
xmpp.send_posts(posts, subscriber, search_term)
self.response.set_status(200)
application = webapp.WSGIApplication([
('/', WelcomeHandler),
('/delete_tokens', TokenDeletionHandler),
('/finish_dance', DanceFinishingHandler),
('/profile', ProfileViewingHandler),
('/posts', PostsHandler),
('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
|
adewale/Buzz-Chat-Bot
|
e1b1cb1c2d30942236bfdf4a42a21bd154f136aa
|
Added /about to help people work out which bot they're talking to
|
diff --git a/functional_tests.py b/functional_tests.py
index 309897a..8e52358 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,134 +1,143 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import logging
+import settings
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '/track %s' % search_term
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenges(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='/untrack 777')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
subscription = self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='/untrack jaiku')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='/untrack')
handler = XmppHandler()
handler.untrack_command(message=message)
self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
def test_list_command_can_handle_empty_set_of_search_terms(self):
handler = XmppHandler()
sender = '[email protected]'
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
expected_item = 'No subscriptions'
self.assertTrue(len(message.message_to_send) > 0)
+ self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
+
+ def test_about_command_says_what_bot_is_running(self):
+ handler = XmppHandler()
+ sender = '[email protected]'
+ message = StubMessage(sender=sender, body='/about')
+ handler.about_command(message=message)
+ expected_item = 'Welcome to %[email protected]. A bot for Google Buzz' % settings.APP_NAME
self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index f21244a..6f544e4 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,202 +1,209 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.utils import html
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
import logging
import urllib
import pshb
import settings
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) != None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
commands = [
'/help Prints out this message',
'/track [search term] Starts tracking the given search term and returns the id for your subscription',
'/untrack [id] Removes your subscription for that id',
- '/list Lists all search terms and ids currently being tracked by you'
+ '/list Lists all search terms and ids currently being tracked by you',
+ '/about Tells you which instance of the Buzz Chat Bot you are using'
]
class XmppHandler(xmpp_handlers.CommandHandler):
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: /untrack [id]')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
for subscription in Subscription.gql('WHERE subscriber = :1', sender):
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('No subscriptions')
reply(message_builder, message)
+ def about_command(self, message):
+ logging.info('Received message from: %s' % message.sender)
+ message_builder = MessageBuilder()
+ message_builder.add('Welcome to %[email protected]. A bot for Google Buzz. Find out more at: http://%s.appspot.com' % (settings.APP_NAME, settings.APP_NAME))
+ reply(message_builder, message)
+
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
4e5ae095a6bbab488a78ff4c64bef96643c42e35
|
Fixed bug where doing /list when you have no subscriptions causes error
|
diff --git a/functional_tests.py b/functional_tests.py
index 1161574..309897a 100644
--- a/functional_tests.py
+++ b/functional_tests.py
@@ -1,125 +1,134 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import main
import unittest
from gaetestbed import FunctionalTestCase
from tracker_tests import StubHubSubscriber
from xmpp import Tracker, XmppHandler
import logging
class BuzzChatBotFunctionalTestCase(FunctionalTestCase, unittest.TestCase):
def _setup_subscription(self, sender='[email protected]',search_term='somestring'):
search_term = search_term
body = '/track %s' % search_term
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
return subscription
class PostsHandlerTest(BuzzChatBotFunctionalTestCase):
APPLICATION = main.application
def test_can_validate_hub_challenges(self):
subscription = self._setup_subscription()
challenge = 'somechallengetoken'
topic = 'https://www.googleapis.com/buzz/v1/activities/track?q=somestring'
response = self.get('/posts?hub.challenge=%s&hub.mode=%s&hub.topic=%s&id=%s' % (challenge, 'subscribe', topic, subscription.id()))
self.assertOK(response)
response.mustcontain(challenge)
class StubMessage(object):
def __init__(self, sender='[email protected]', body=''):
self.sender = sender
self.body = body
def reply(self, message_to_send, raw_xml=False):
self.message_to_send = message_to_send
class XmppHandlerTest(BuzzChatBotFunctionalTestCase):
def test_untrack_command_fails_for_missing_subscription_value(self):
message = StubMessage(body='/untrack 777')
handler = XmppHandler()
handler.untrack_command(message=message)
- self.assertTrue('Untrack failed' in message.message_to_send)
+ self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_missing_subscription_argument(self):
subscription = self._setup_subscription()
message = StubMessage()
handler = XmppHandler()
handler.untrack_command(message=message)
- self.assertTrue('Untrack failed' in message.message_to_send)
+ self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_wrong_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id() + 1
message = StubMessage(body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
- self.assertTrue('Untrack failed' in message.message_to_send)
+ self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_succeeds_for_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
- self.assertTrue('No longer tracking' in message.message_to_send)
+ self.assertTrue('No longer tracking' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_other_peoples_valid_subscription_id(self):
subscription = self._setup_subscription()
id = subscription.id()
message = StubMessage(sender='[email protected]', body='/untrack %s' % id)
handler = XmppHandler()
handler.untrack_command(message=message)
- self.assertTrue('Untrack failed' in message.message_to_send)
+ self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_malformed_subscription_id(self):
message = StubMessage(body='/untrack jaiku')
handler = XmppHandler()
handler.untrack_command(message=message)
- self.assertTrue('Untrack failed' in message.message_to_send)
+ self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_untrack_command_fails_for_empty_subscription_id(self):
message = StubMessage(body='/untrack')
handler = XmppHandler()
handler.untrack_command(message=message)
- self.assertTrue('Untrack failed' in message.message_to_send)
+ self.assertTrue('Untrack failed' in message.message_to_send, message.message_to_send)
def test_list_command_lists_existing_search_terms_and_ids_for_each_user(self):
sender1 = '[email protected]'
subscription1 = self._setup_subscription(sender=sender1, search_term='searchA')
sender2 = '[email protected]'
subscription2 = self._setup_subscription(sender=sender2, search_term='searchB')
handler = XmppHandler()
for people in [(sender1, subscription1), (sender2, subscription2)]:
sender = people[0]
message = StubMessage(sender=sender, body='/list')
handler.list_command(message=message)
subscription = people[1]
self.assertTrue(str(subscription.id()) in message.message_to_send)
expected_item = 'Search term: %s with id: %s' % (subscription.search_term, subscription.id())
- self.assertTrue(expected_item in message.message_to_send, expected_item)
\ No newline at end of file
+ self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
+
+ def test_list_command_can_handle_empty_set_of_search_terms(self):
+ handler = XmppHandler()
+ sender = '[email protected]'
+ message = StubMessage(sender=sender, body='/list')
+ handler.list_command(message=message)
+ expected_item = 'No subscriptions'
+ self.assertTrue(len(message.message_to_send) > 0)
+ self.assertTrue(expected_item in message.message_to_send, message.message_to_send)
\ No newline at end of file
diff --git a/main.py b/main.py
index d46097f..d239dd0 100644
--- a/main.py
+++ b/main.py
@@ -1,212 +1,213 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
import buzz_gae_client
import logging
import os
import settings
import xmpp
import pshb
class UserToken(db.Model):
# The user_id is the key_name so we don't have to make it an explicit property
request_token_string = db.StringProperty()
access_token_string = db.StringProperty()
email_address = db.StringProperty()
def get_request_token(self):
"Returns request token as a dictionary of tokens including oauth_token, oauth_token_secret and oauth_callback_confirmed."
return eval(self.request_token_string)
def set_access_token(self, access_token):
access_token_string = repr(access_token)
self.access_token_string = access_token_string
def get_access_token(self):
"Returns access token as a dictionary of tokens including consumer_key, consumer_secret, oauth_token and oauth_token_secret"
return eval(self.access_token_string)
@staticmethod
def create_user_token(request_token):
user = users.get_current_user()
user_id = user.user_id()
request_token_string = repr(request_token)
# TODO(ade) Support users who sign in to AppEngine with a federated identity aka OpenId
email = user.email()
logging.info('Creating user token: key_name: %s request_token_string: %s email_address: %s' % (
user_id, request_token_string, email))
return UserToken(key_name=user_id, request_token_string=request_token_string, access_token_string='',
email_address=email)
@staticmethod
def get_current_user_token():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
return user_token
@staticmethod
def access_token_exists():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
logging.info('user_token: %s' % user_token)
return user_token and user_token.access_token_string
class WelcomeHandler(webapp.RequestHandler):
@login_required
def get(self):
logging.info("Request body %s" % self.request.body)
template_values = {}
if UserToken.access_token_exists():
template_values['access_token_exists'] = 'true'
else:
# Generate the request token
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
request_token = client.get_request_token(settings.CALLBACK_URL)
# Create the request token and associate it with the current user
user_token = UserToken.create_user_token(request_token)
UserToken.put(user_token)
authorisation_url = client.generate_authorisation_url(request_token)
logging.info('Authorisation URL is: %s' % authorisation_url)
template_values['destination'] = authorisation_url
path = os.path.join(os.path.dirname(__file__), 'welcome.html')
self.response.out.write(template.render(path, template_values))
class TokenDeletionHandler(webapp.RequestHandler):
def post(self):
user_token = UserToken.get_current_user_token()
UserToken.delete(user_token)
self.redirect('/')
class DanceFinishingHandler(webapp.RequestHandler):
def get(self):
logging.info("Request body %s" % self.request.body)
oauth_verifier = self.request.get('oauth_verifier')
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
user_token = UserToken.get_current_user_token()
request_token = user_token.get_request_token()
access_token = client.upgrade_to_access_token(request_token, oauth_verifier)
logging.info('SUCCESS: Received access token.')
user_token.set_access_token(access_token)
UserToken.put(user_token)
logging.debug('Access token was: %s' % user_token.access_token_string)
self.redirect('/profile')
class ProfileViewingHandler(webapp.RequestHandler):
@login_required
def get(self):
user_token = UserToken.get_current_user_token()
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
api_client = client.build_api_client(user_token.get_access_token())
user_profile_data = api_client.people().get(userId='@me')
template_values = {}
template_values['user_profile_data'] = user_profile_data
template_values['access_token'] = user_token.access_token_string
path = os.path.join(os.path.dirname(__file__), 'profile.html')
self.response.out.write(template.render(path, template_values))
class PostsHandler(webapp.RequestHandler):
def _get_subscription(self):
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
return subscription
def get(self):
"""Show all the resources in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.info("New content: %s" % self.request.body)
id = self.request.get('id')
+ # TODO(ade) Must also correctly handle unsubscription
# If this is a hub challenge
if self.request.get('hub.challenge'):
# If this subscription exists
if self.request.get('hub.mode') == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted challenge for feed: %s" % self.request.get('hub.topic'))
else:
self.response.set_status(404)
self.response.out.write("Challenge failed")
logging.info("Challenge failed for feed: %s" % self.request.get('hub.topic'))
# Once a challenge has been issued there's no point in returning anything other than challenge passed or failed
return
def post(self):
"""Create a new resource in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.info("New content: %s" % self.request.body)
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
if not subscription:
self.response.set_status(404)
self.response.out.write("No such subscription")
logging.warning('No subscription for %s' % id)
return
subscriber = subscription.subscriber
search_term = subscription.search_term
parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB)
url = parser.extractFeedUrl()
if not parser.dataValid():
parser.logErrors()
self.response.out.write("Bad entries: %s" % parser.data)
return
else:
posts = parser.extractPosts()
logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url))
xmpp.send_posts(posts, subscriber, search_term)
self.response.set_status(200)
application = webapp.WSGIApplication([
('/', WelcomeHandler),
('/delete_tokens', TokenDeletionHandler),
('/finish_dance', DanceFinishingHandler),
('/profile', ProfileViewingHandler),
('/posts', PostsHandler),
('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
diff --git a/xmpp.py b/xmpp.py
index da12375..f21244a 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,200 +1,202 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.utils import html
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
import logging
import urllib
import pshb
import settings
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) != None
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += line
if (index+1) < len(self.lines):
text += '\n'
return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
commands = [
'/help Prints out this message',
'/track [search term] Starts tracking the given search term and returns the id for your subscription',
'/untrack [id] Removes your subscription for that id',
'/list Lists all search terms and ids currently being tracked by you'
]
class XmppHandler(xmpp_handlers.CommandHandler):
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
- message_builder.add('Untrack failed. That subscription does not exist for you')
+ message_builder.add('Untrack failed. That subscription does not exist for you. Remember the syntax is: /untrack [id]')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
for subscription in Subscription.gql('WHERE subscriber = :1', sender):
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
+ else:
+ message_builder.add('No subscriptions')
reply(message_builder, message)
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=False)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
1c55e9cbcbeecd4b2204c598613c9da143552ef7
|
Checking that app can work at other endpoints besides buzzchatbot.appspot.com
|
diff --git a/app.yaml b/app.yaml
index e30bf45..522fb2a 100644
--- a/app.yaml
+++ b/app.yaml
@@ -1,15 +1,15 @@
-application: buzzchatbot
+application: favedby
version: 1
runtime: python
api_version: 1
handlers:
- url: /css
static_dir: css
- url: /images
static_dir: images
- url: /.*
script: main.py
inbound_services:
- xmpp_message
\ No newline at end of file
diff --git a/settings.py b/settings.py
index 280c846..57b6339 100644
--- a/settings.py
+++ b/settings.py
@@ -1,37 +1,37 @@
# These are the settings that tend to differ between installations. Tweak these for your installation.
-APP_NAME = "buzzchatbot"
+APP_NAME = "favedby"
#PSHB settings
# This is the token that will act as a shared secret to verify that this application is the one that registered the given subscription. The hub will send us a challenge containing this token.
SECRET_TOKEN = "SOME_SECRET_TOKEN"
# Should we ignore the hubs defined in the feeds we're consuming
ALWAYS_USE_DEFAULT_HUB = False
# What PSHB hub should we use for feeds that don't support PSHB. pollinghub.appspot.com is a hub I've set up that does polling.
DEFAULT_HUB = "http://pollinghub.appspot.com/"
# Should anyone be able to add/delete subscriptions or should access be restricted to admins
OPEN_ACCESS = False
# How often should a task, such as registering a subscription, be retried before we give up
MAX_TASK_RETRIES = 10
# Maximum number of items to be fetched for any part of the system that wants everything of a given data model type
MAX_FETCH = 500
# Should Streamer check that posts it receives from a putative hub are for feeds it's actually subscribed to
SHOULD_VERIFY_INCOMING_POSTS = False
# Buzz Chat Bot settings
# OAuth consumer key and secret - you should probably leave these alone
CONSUMER_KEY = 'anonymous'
CONSUMER_SECRET = 'anonymous'
# OAuth callback URL
CALLBACK_URL = 'http://%s.appspot.com/finish_dance' % APP_NAME
# Installation specific config ends.
\ No newline at end of file
diff --git a/tracker_tests.py b/tracker_tests.py
index d920c9c..2eda7cd 100644
--- a/tracker_tests.py
+++ b/tracker_tests.py
@@ -1,146 +1,146 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from xmpp import Subscription, Tracker
import pshb
import settings
class StubHubSubscriber(pshb.HubSubscriber):
def subscribe(self, url, hub, callback_url):
self.callback_url = callback_url
def unsubscribe(self, url, hub, callback_url):
self.callback_url = callback_url
class TrackerTest(unittest.TestCase):
def test_tracker_rejects_empty_search_term(self):
sender = '[email protected]'
body = '/track'
tracker = Tracker()
self.assertEquals(None, tracker.track(sender, body))
def test_tracker_rejects_padded_empty_string(self):
sender = '[email protected]'
body = '/track '
tracker = Tracker()
self.assertEquals(None, tracker.track(sender, body))
def test_tracker_accepts_valid_string(self):
sender = '[email protected]'
search_term='somestring'
body = '/track %s' % search_term
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
expected_callback_url = 'http://%s.appspot.com/posts/%s/%s' % (settings.APP_NAME, sender, search_term)
expected_subscription = Subscription(url='https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, search_term=search_term, callback_url=expected_callback_url)
actual_subscription = tracker.track(sender, body)
self.assertEquals(expected_subscription.url, actual_subscription.url)
self.assertEquals(expected_subscription.search_term, actual_subscription.search_term)
def test_tracker_extracts_correct_search_term(self):
search_term = 'somestring'
body = '/track %s' % search_term
tracker = Tracker()
self.assertEquals(search_term, tracker._extract_search_term(body))
def test_tracker_builds_correct_pshb_url(self):
search_term = 'somestring'
tracker = Tracker()
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term, tracker._build_subscription_url(search_term))
def test_tracker_url_encodes_search_term(self):
search_term = 'some string'
tracker = Tracker()
self.assertEquals('https://www.googleapis.com/buzz/v1/activities/track?q=' + 'some%20string', tracker._build_subscription_url(search_term))
def _delete_all_subscriptions(self):
for subscription in Subscription.all().fetch(100):
subscription.delete()
def test_tracker_saves_subscription(self):
self._delete_all_subscriptions()
self.assertEquals(0, len(Subscription.all().fetch(100)))
sender = '[email protected]'
search_term='somestring'
body = '/track %s' % search_term
tracker = Tracker()
subscription = tracker.track(sender, body)
self.assertEquals(1, len(Subscription.all().fetch(100)))
self.assertEquals(subscription, Subscription.all().fetch(1)[0])
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query(self):
sender = '[email protected]'
search_term='somestring'
body = '/track %s' % search_term
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_urlencoded_callback_url(self):
sender = '[email protected]'
search_term='some string'
body = '/track %s' % search_term
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_subscribes_with_callback_url_that_identifies_subscriber_and_query_without_xmpp_client_identifier(self):
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
body = '/track %s' % search_term
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.track(sender, body)
expected_callback_url = 'http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, subscription.id())
self.assertEquals(expected_callback_url, hub_subscriber.callback_url)
def test_tracker_rejects_invalid_id_for_untracking(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
body = '/untrack 1'
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
subscription = tracker.untrack(sender, body)
self.assertEquals(None, subscription)
def test_tracker_untracks_valid_id(self):
self._delete_all_subscriptions()
sender = '[email protected]/Adium380DADCD'
search_term='somestring'
body = '/track %s' % search_term
hub_subscriber = StubHubSubscriber()
tracker = Tracker(hub_subscriber=hub_subscriber)
track_subscription = tracker.track(sender, body)
body = '/untrack %s' % track_subscription.id()
untrack_subscription = tracker.untrack(sender, body)
self.assertEquals(track_subscription, untrack_subscription)
self.assertFalse(Subscription.exists(track_subscription.id()))
- self.assertEquals('http://buzzchatbot.appspot.com/posts?id=%s' % track_subscription.id(), hub_subscriber.callback_url)
+ self.assertEquals('http://%s.appspot.com/posts?id=%s' % (settings.APP_NAME, track_subscription.id()), hub_subscriber.callback_url)
|
adewale/Buzz-Chat-Bot
|
5fd4a53964ab919d97770e0f7b8195085089c66c
|
Removed xhtml-im support since GMail doesn't support it
|
diff --git a/main.py b/main.py
index 3b7c522..d46097f 100644
--- a/main.py
+++ b/main.py
@@ -1,206 +1,212 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
import buzz_gae_client
import logging
import os
import settings
import xmpp
import pshb
class UserToken(db.Model):
# The user_id is the key_name so we don't have to make it an explicit property
request_token_string = db.StringProperty()
access_token_string = db.StringProperty()
email_address = db.StringProperty()
def get_request_token(self):
"Returns request token as a dictionary of tokens including oauth_token, oauth_token_secret and oauth_callback_confirmed."
return eval(self.request_token_string)
def set_access_token(self, access_token):
access_token_string = repr(access_token)
self.access_token_string = access_token_string
def get_access_token(self):
"Returns access token as a dictionary of tokens including consumer_key, consumer_secret, oauth_token and oauth_token_secret"
return eval(self.access_token_string)
@staticmethod
def create_user_token(request_token):
user = users.get_current_user()
user_id = user.user_id()
request_token_string = repr(request_token)
# TODO(ade) Support users who sign in to AppEngine with a federated identity aka OpenId
email = user.email()
logging.info('Creating user token: key_name: %s request_token_string: %s email_address: %s' % (
user_id, request_token_string, email))
return UserToken(key_name=user_id, request_token_string=request_token_string, access_token_string='',
email_address=email)
@staticmethod
def get_current_user_token():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
return user_token
@staticmethod
def access_token_exists():
user = users.get_current_user()
user_token = UserToken.get_by_key_name(user.user_id())
logging.info('user_token: %s' % user_token)
return user_token and user_token.access_token_string
class WelcomeHandler(webapp.RequestHandler):
@login_required
def get(self):
logging.info("Request body %s" % self.request.body)
template_values = {}
if UserToken.access_token_exists():
template_values['access_token_exists'] = 'true'
else:
# Generate the request token
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
request_token = client.get_request_token(settings.CALLBACK_URL)
# Create the request token and associate it with the current user
user_token = UserToken.create_user_token(request_token)
UserToken.put(user_token)
authorisation_url = client.generate_authorisation_url(request_token)
logging.info('Authorisation URL is: %s' % authorisation_url)
template_values['destination'] = authorisation_url
path = os.path.join(os.path.dirname(__file__), 'welcome.html')
self.response.out.write(template.render(path, template_values))
class TokenDeletionHandler(webapp.RequestHandler):
def post(self):
user_token = UserToken.get_current_user_token()
UserToken.delete(user_token)
self.redirect('/')
class DanceFinishingHandler(webapp.RequestHandler):
def get(self):
logging.info("Request body %s" % self.request.body)
oauth_verifier = self.request.get('oauth_verifier')
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
user_token = UserToken.get_current_user_token()
request_token = user_token.get_request_token()
access_token = client.upgrade_to_access_token(request_token, oauth_verifier)
logging.info('SUCCESS: Received access token.')
user_token.set_access_token(access_token)
UserToken.put(user_token)
logging.debug('Access token was: %s' % user_token.access_token_string)
self.redirect('/profile')
class ProfileViewingHandler(webapp.RequestHandler):
@login_required
def get(self):
user_token = UserToken.get_current_user_token()
client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET)
api_client = client.build_api_client(user_token.get_access_token())
user_profile_data = api_client.people().get(userId='@me')
template_values = {}
template_values['user_profile_data'] = user_profile_data
template_values['access_token'] = user_token.access_token_string
path = os.path.join(os.path.dirname(__file__), 'profile.html')
self.response.out.write(template.render(path, template_values))
class PostsHandler(webapp.RequestHandler):
def _get_subscription(self):
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
return subscription
def get(self):
"""Show all the resources in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.info("New content: %s" % self.request.body)
id = self.request.get('id')
# If this is a hub challenge
if self.request.get('hub.challenge'):
# If this subscription exists
if self.request.get('hub.mode') == "subscribe" and xmpp.Subscription.get_by_id(int(id)):
self.response.out.write(self.request.get('hub.challenge'))
logging.info("Successfully accepted challenge for feed: %s" % self.request.get('hub.topic'))
else:
self.response.set_status(404)
self.response.out.write("Challenge failed")
logging.info("Challenge failed for feed: %s" % self.request.get('hub.topic'))
# Once a challenge has been issued there's no point in returning anything other than challenge passed or failed
return
def post(self):
"""Create a new resource in this collection"""
logging.info("Headers were: %s" % str(self.request.headers))
logging.info('Request: %s' % str(self.request))
logging.info("New content: %s" % self.request.body)
id = self.request.get('id')
subscription = xmpp.Subscription.get_by_id(int(id))
+ if not subscription:
+ self.response.set_status(404)
+ self.response.out.write("No such subscription")
+ logging.warning('No subscription for %s' % id)
+ return
+
subscriber = subscription.subscriber
search_term = subscription.search_term
parser = pshb.ContentParser(self.request.body, settings.DEFAULT_HUB, settings.ALWAYS_USE_DEFAULT_HUB)
url = parser.extractFeedUrl()
if not parser.dataValid():
parser.logErrors()
self.response.out.write("Bad entries: %s" % parser.data)
return
else:
posts = parser.extractPosts()
logging.info("Successfully received %s posts for subscription: %s" % (len(posts), url))
xmpp.send_posts(posts, subscriber, search_term)
self.response.set_status(200)
application = webapp.WSGIApplication([
('/', WelcomeHandler),
('/delete_tokens', TokenDeletionHandler),
('/finish_dance', DanceFinishingHandler),
('/profile', ProfileViewingHandler),
('/posts', PostsHandler),
('/_ah/xmpp/message/chat/', xmpp.XmppHandler), ],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
diff --git a/message_builder_tests.py b/message_builder_tests.py
index f5fa5fc..a93ed40 100644
--- a/message_builder_tests.py
+++ b/message_builder_tests.py
@@ -1,86 +1,59 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from xml.sax import make_parser, handler
from xmpp import MessageBuilder
import unittest
import pshb
import feedparser
class MessageBuilderTest(unittest.TestCase):
- def assertValid(self, string):
- self.assertTrue('<body' in string, 'Did not contain required string <body')
- self.assertTrue('</body>' in string, 'Did not contain required string </body>')
-
- parser = make_parser()
- parser.setFeature(handler.feature_namespaces,True)
- parser.setContentHandler(handler.ContentHandler())
-
- import StringIO
- f = StringIO.StringIO(string)
-
- # This will raise an exception if the string is invalid
- parser.parse(f)
def test_builds_valid_message_for_simple_string(self):
text = 'Tracking: some complex search'
message_builder = MessageBuilder()
message_builder.add(text)
message = message_builder.build_message()
- expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">%s
- </body>
- </html>''' % text
- self.assertEquals(expected, message)
- self.assertValid(message)
+ self.assertEquals(text, message)
def test_builds_valid_message_for_track_message(self):
- # Note that this can easily become </track> if we use <> for messages
message_builder = MessageBuilder()
message_builder.add('</track>')
message = message_builder.build_message()
- expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">%s
- </body>
- </html>''' % '</track>'
+ expected = '%s' % '</track>'
self.assertEquals(expected, message)
- self.assertValid(message)
def test_builds_valid_message_for_list(self):
items = ['1', '2', '3', '4']
message_builder = MessageBuilder()
for item in items:
message_builder.add(item)
message = message_builder.build_message()
- expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">1<br></br>2<br></br>3<br></br>4
- </body>
- </html>'''
+ expected = '1\n2\n3\n4'
self.assertEquals(expected, message)
- self.assertValid(message)
def test_builds_valid_message_for_post(self):
search_term = 'some search'
url = 'http://example.com/item1'
feedUrl = 'http://example.com/feed'
title = 'some title'
content = 'some content'
date_published = None
author = 'some guy'
entry = feedparser.FeedParserDict({'id':feedUrl})
post = pshb.PostFactory.createPost(url, feedUrl, title, content, date_published, author, entry)
message_builder = MessageBuilder()
message = message_builder.build_message_from_post(post, search_term)
- expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">%s matched: <a href='%s'>%s</a>
- </body>
- </html>''' % (search_term, url, title)
- self.assertEquals(expected, message)
- self.assertValid(message)
\ No newline at end of file
+ expected = '[%s] matched post: [%s] with URL: [%s]' % (search_term, title, url)
+ self.assertEquals(expected, message)
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index 6485371..da12375 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,208 +1,200 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.utils import html
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
import logging
import urllib
import pshb
import settings
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) != None
-def extract_sender_email_address(message_sender):
- return message_sender.split('/')[0]
-
-def reply(message_builder, message):
- message_to_send = message_builder.build_message()
- logging.info('Message that will be sent: %s' % message_to_send)
- message.reply(message_to_send, raw_xml=True)
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
- def _build_raw_message(self, text):
- message = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">%s
- </body>
- </html>''' % text
- message = message.strip()
- message = message.encode('ascii', 'xmlcharrefreplace')
- return message
-
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
- text += html.escape(line)
+ text += line
if (index+1) < len(self.lines):
- text += '<br></br>'
-
- return self._build_raw_message(text)
+ text += '\n'
+ return text
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
- text = '''%s matched: <a href='%s'>%s</a>''' % (search_term, post.url, post.title)
- return self._build_raw_message(text)
+ return '''[%s] matched post: [%s] with URL: [%s]''' % (search_term, post.title, post.url)
commands = [
- '/help Prints out this message\n',
- '/track [search term] Starts tracking the given search term and returns the id for your subscription\n',
- '/untrack [id] Removes your subscription for that id\n',
+ '/help Prints out this message',
+ '/track [search term] Starts tracking the given search term and returns the id for your subscription',
+ '/untrack [id] Removes your subscription for that id',
'/list Lists all search terms and ids currently being tracked by you'
]
class XmppHandler(xmpp_handlers.CommandHandler):
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
for subscription in Subscription.gql('WHERE subscriber = :1', sender):
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
reply(message_builder, message)
+
+def extract_sender_email_address(message_sender):
+ return message_sender.split('/')[0]
+
+def reply(message_builder, message):
+ message_to_send = message_builder.build_message()
+ logging.info('Message that will be sent: %s' % message_to_send)
+ message.reply(message_to_send, raw_xml=False)
+
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
- xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=True)
\ No newline at end of file
+ xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=False)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
f0870486ef3d1e8b1fd4ea9a5a417d57f0de9f10
|
Fixed formatting problem with generating xhtml-im lists
|
diff --git a/message_builder_tests.py b/message_builder_tests.py
index 688e3f0..f5fa5fc 100644
--- a/message_builder_tests.py
+++ b/message_builder_tests.py
@@ -1,86 +1,86 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from xml.sax import make_parser, handler
from xmpp import MessageBuilder
import unittest
import pshb
import feedparser
class MessageBuilderTest(unittest.TestCase):
def assertValid(self, string):
self.assertTrue('<body' in string, 'Did not contain required string <body')
self.assertTrue('</body>' in string, 'Did not contain required string </body>')
parser = make_parser()
parser.setFeature(handler.feature_namespaces,True)
parser.setContentHandler(handler.ContentHandler())
import StringIO
f = StringIO.StringIO(string)
# This will raise an exception if the string is invalid
parser.parse(f)
def test_builds_valid_message_for_simple_string(self):
text = 'Tracking: some complex search'
message_builder = MessageBuilder()
message_builder.add(text)
message = message_builder.build_message()
expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">%s
</body>
</html>''' % text
self.assertEquals(expected, message)
self.assertValid(message)
def test_builds_valid_message_for_track_message(self):
# Note that this can easily become </track> if we use <> for messages
message_builder = MessageBuilder()
message_builder.add('</track>')
message = message_builder.build_message()
expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">%s
</body>
</html>''' % '</track>'
self.assertEquals(expected, message)
self.assertValid(message)
def test_builds_valid_message_for_list(self):
- items = ['1', '2', '3']
+ items = ['1', '2', '3', '4']
message_builder = MessageBuilder()
for item in items:
message_builder.add(item)
message = message_builder.build_message()
- expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">1<br></br>2<br></br>3
+ expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">1<br></br>2<br></br>3<br></br>4
</body>
</html>'''
self.assertEquals(expected, message)
self.assertValid(message)
def test_builds_valid_message_for_post(self):
search_term = 'some search'
url = 'http://example.com/item1'
feedUrl = 'http://example.com/feed'
title = 'some title'
content = 'some content'
date_published = None
author = 'some guy'
entry = feedparser.FeedParserDict({'id':feedUrl})
post = pshb.PostFactory.createPost(url, feedUrl, title, content, date_published, author, entry)
message_builder = MessageBuilder()
message = message_builder.build_message_from_post(post, search_term)
expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">%s matched: <a href='%s'>%s</a>
</body>
</html>''' % (search_term, url, title)
self.assertEquals(expected, message)
self.assertValid(message)
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index 7466014..6485371 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,209 +1,208 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.utils import html
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
import logging
import urllib
import pshb
import settings
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) != None
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=True)
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def _build_raw_message(self, text):
message = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">%s
</body>
</html>''' % text
message = message.strip()
message = message.encode('ascii', 'xmlcharrefreplace')
return message
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
-
text += html.escape(line)
- if (index+1) !=len(self.lines):
+ if (index+1) < len(self.lines):
text += '<br></br>'
return self._build_raw_message(text)
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
text = '''%s matched: <a href='%s'>%s</a>''' % (search_term, post.url, post.title)
return self._build_raw_message(text)
commands = [
'/help Prints out this message\n',
- '/track [search term] Starts tracking the given search term and returns the id for your subscription\n'
- '/untrack [id] Removes your subscription for that id\n'
+ '/track [search term] Starts tracking the given search term and returns the id for your subscription\n',
+ '/untrack [id] Removes your subscription for that id\n',
'/list Lists all search terms and ids currently being tracked by you'
]
class XmppHandler(xmpp_handlers.CommandHandler):
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
for subscription in Subscription.gql('WHERE subscriber = :1', sender):
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
reply(message_builder, message)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=True)
\ No newline at end of file
|
adewale/Buzz-Chat-Bot
|
8ae72ed9e99431484711e889f27f9bd05160c913
|
Fixed formatting problems with the xhtml-im messages
|
diff --git a/message_builder_tests.py b/message_builder_tests.py
index 0820f0d..688e3f0 100644
--- a/message_builder_tests.py
+++ b/message_builder_tests.py
@@ -1,95 +1,86 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from xml.sax import make_parser, handler
from xmpp import MessageBuilder
import unittest
import pshb
import feedparser
class MessageBuilderTest(unittest.TestCase):
def assertValid(self, string):
self.assertTrue('<body' in string, 'Did not contain required string <body')
self.assertTrue('</body>' in string, 'Did not contain required string </body>')
parser = make_parser()
parser.setFeature(handler.feature_namespaces,True)
parser.setContentHandler(handler.ContentHandler())
import StringIO
f = StringIO.StringIO(string)
# This will raise an exception if the string is invalid
parser.parse(f)
def test_builds_valid_message_for_simple_string(self):
text = 'Tracking: some complex search'
message_builder = MessageBuilder()
message_builder.add(text)
message = message_builder.build_message()
- expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'>
- <body xmlns="http://www.w3.org/1999/xhtml">
- %s
+ expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">%s
</body>
</html>''' % text
self.assertEquals(expected, message)
self.assertValid(message)
def test_builds_valid_message_for_track_message(self):
# Note that this can easily become </track> if we use <> for messages
- text = '</track>'
message_builder = MessageBuilder()
- message_builder.add(text)
+ message_builder.add('</track>')
message = message_builder.build_message()
- expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'>
- <body xmlns="http://www.w3.org/1999/xhtml">
- %s
+ expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">%s
</body>
- </html>''' % text
- #self.assertEquals(expected, message)
+ </html>''' % '</track>'
+ self.assertEquals(expected, message)
self.assertValid(message)
def test_builds_valid_message_for_list(self):
items = ['1', '2', '3']
message_builder = MessageBuilder()
for item in items:
message_builder.add(item)
message = message_builder.build_message()
- expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'>
- <body xmlns="http://www.w3.org/1999/xhtml">
- 1<br></br>2<br></br>3
+ expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">1<br></br>2<br></br>3
</body>
</html>'''
self.assertEquals(expected, message)
self.assertValid(message)
def test_builds_valid_message_for_post(self):
search_term = 'some search'
url = 'http://example.com/item1'
feedUrl = 'http://example.com/feed'
title = 'some title'
content = 'some content'
date_published = None
author = 'some guy'
entry = feedparser.FeedParserDict({'id':feedUrl})
post = pshb.PostFactory.createPost(url, feedUrl, title, content, date_published, author, entry)
message_builder = MessageBuilder()
message = message_builder.build_message_from_post(post, search_term)
- expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'>
- <body xmlns="http://www.w3.org/1999/xhtml">
- %s matched: <a href='%s'>%s</a>
+ expected = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">%s matched: <a href='%s'>%s</a>
</body>
</html>''' % (search_term, url, title)
self.assertEquals(expected, message)
self.assertValid(message)
\ No newline at end of file
diff --git a/xmpp.py b/xmpp.py
index bb49ac3..7466014 100644
--- a/xmpp.py
+++ b/xmpp.py
@@ -1,211 +1,209 @@
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.utils import html
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers
import logging
import urllib
import pshb
import settings
class Subscription(db.Model):
url = db.StringProperty(required=True)
search_term = db.StringProperty(required=True)
subscriber = db.StringProperty()
def id(self):
return self.key().id()
def __eq__(self, other):
if not other:
return False
return self.id() == other.id()
@staticmethod
def exists(id):
"""Return True or False to indicate if a subscription with the given id exists"""
if not id:
return False
return Subscription.get_by_id(int(id)) != None
def extract_sender_email_address(message_sender):
return message_sender.split('/')[0]
def reply(message_builder, message):
message_to_send = message_builder.build_message()
logging.info('Message that will be sent: %s' % message_to_send)
message.reply(message_to_send, raw_xml=True)
class Tracker(object):
def __init__(self, hub_subscriber=pshb.HubSubscriber()):
self.hub_subscriber = hub_subscriber
def _valid_subscription(self, message_body):
return self._extract_search_term(message_body) != ''
def _extract_search_term(self, message_body):
search_term = message_body[len('/track'):]
return search_term.strip()
def _subscribe(self, message_sender, message_body):
message_sender = extract_sender_email_address(message_sender)
search_term = self._extract_search_term(message_body)
url = self._build_subscription_url(search_term)
logging.info('Subscribing to: %s for user: %s' % (url, message_sender))
subscription = Subscription(url=url, search_term=search_term, subscriber=message_sender)
db.put(subscription)
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.subscribe(url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
def _build_callback_url(self, subscription):
return "http://%s.appspot.com/posts?id=%s" % (settings.APP_NAME, subscription.id())
def _build_subscription_url(self, search_term):
search_term = urllib.quote(search_term)
return 'https://www.googleapis.com/buzz/v1/activities/track?q=%s' % search_term
def track(self, message_sender, message_body):
if self._valid_subscription(message_body):
return self._subscribe(message_sender, message_body)
else:
return None
def _is_number(self, id):
if not id:
return False
id = id.strip()
for char in id:
if not char.isdigit():
return False
return True
def untrack(self, message_sender, message_body):
logging.info('Message is: %s' % message_body)
id = message_body[len('/untrack'):]
if not self._is_number(id):
return None
id = id.strip()
subscription = Subscription.get_by_id(int(id))
logging.info('Subscripton: %s' % str(subscription))
if not subscription:
return None
if subscription.subscriber != extract_sender_email_address(message_sender):
return None
subscription.delete()
callback_url = self._build_callback_url(subscription)
logging.info('Callback URL was: %s' % callback_url)
self.hub_subscriber.unsubscribe(subscription.url, 'http://pubsubhubbub.appspot.com/', callback_url)
return subscription
class MessageBuilder(object):
def __init__(self):
self.lines = []
def _build_raw_message(self, text):
- message = '''<html xmlns='http://jabber.org/protocol/xhtml-im'>
- <body xmlns="http://www.w3.org/1999/xhtml">
- %s
+ message = '''<html xmlns='http://jabber.org/protocol/xhtml-im'><body xmlns="http://www.w3.org/1999/xhtml">%s
</body>
</html>''' % text
message = message.strip()
message = message.encode('ascii', 'xmlcharrefreplace')
return message
def build_message(self):
text = ''
for index,line in enumerate(self.lines):
text += html.escape(line)
if (index+1) !=len(self.lines):
text += '<br></br>'
return self._build_raw_message(text)
def add(self, line):
self.lines.append(line)
def build_message_from_post(self, post, search_term):
text = '''%s matched: <a href='%s'>%s</a>''' % (search_term, post.url, post.title)
return self._build_raw_message(text)
commands = [
'/help Prints out this message\n',
'/track [search term] Starts tracking the given search term and returns the id for your subscription\n'
'/untrack [id] Removes your subscription for that id\n'
'/list Lists all search terms and ids currently being tracked by you'
]
class XmppHandler(xmpp_handlers.CommandHandler):
def help_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
lines = ['We all need a little help sometimes']
lines.extend(commands)
message_builder = MessageBuilder()
for line in lines:
message_builder.add(line)
reply(message_builder, message)
def track_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.track(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('Tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Sorry there was a problem with your last track command <%s>' % message.body)
reply(message_builder, message)
def untrack_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
tracker = Tracker()
subscription = tracker.untrack(message.sender, message.body)
message_builder = MessageBuilder()
if subscription:
message_builder.add('No longer tracking: %s with id: %s' % (subscription.search_term, subscription.id()))
else:
message_builder.add('Untrack failed. That subscription does not exist for you')
reply(message_builder, message)
def list_command(self, message=None):
logging.info('Received message from: %s' % message.sender)
message_builder = MessageBuilder()
sender = extract_sender_email_address(message.sender)
logging.info('Sender: %s' % sender)
for subscription in Subscription.gql('WHERE subscriber = :1', sender):
message_builder.add('Search term: %s with id: %s' % (subscription.search_term, subscription.id()))
reply(message_builder, message)
def send_posts(posts, subscriber, search_term):
message_builder = MessageBuilder()
for post in posts:
xmpp.send_message(subscriber, message_builder.build_message_from_post(post, search_term), raw_xml=True)
\ No newline at end of file
|
monkeyoperator/greasemonkey-scripts
|
f8d320fed48324069ec2721d0d47b5386252a9f3
|
Minimize window before closing, non-debug version of ext-js
|
diff --git a/imagefap_lightroom.user.js b/imagefap_lightroom.user.js
index 53f724b..7adb495 100644
--- a/imagefap_lightroom.user.js
+++ b/imagefap_lightroom.user.js
@@ -1,306 +1,305 @@
// ==UserScript==
// @name ImageFap Lightroom
// @description Show content from Imagefap.com
// @include *imagefap.com/*
// @unwrap
// ==/UserScript==
document.cookie='popundr=1; path=/; expires='+new Date(Date.now()+24*60*60*1000*356).toGMTString();
(function(window) {
function loadScript(url) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'utf-8';
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
}
function loadCss( url ) {
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
document.getElementsByTagName('head')[0].appendChild(link);
}
function addStyle( style ) {
var tag = document.createElement('style');
tag.innerHTML=style;
document.getElementsByTagName('head')[0].appendChild(tag);
}
- loadScript('http://extjs.cachefly.net/ext-3.2.0/adapter/ext/ext-base-debug.js');
- loadScript('http://extjs.cachefly.net/ext-3.2.0/ext-all-debug.js');
+ loadScript('http://extjs.cachefly.net/ext-3.2.0/adapter/ext/ext-base.js');
+ loadScript('http://extjs.cachefly.net/ext-3.2.0/ext-all.js');
loadCss('http://extjs.cachefly.net/ext-3.2.0/resources/css/ext-all.css');
addStyle('.thumb-loading { background: transparent url(data:image/gif;base64,R0lGODlhEAAQAPQAAP///wAAAPj4+Dg4OISEhAYGBiYmJtbW1qioqBYWFnZ2dmZmZuTk5JiYmMbGxkhISFZWVgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFUCAgjmRpnqUwFGwhKoRgqq2YFMaRGjWA8AbZiIBbjQQ8AmmFUJEQhQGJhaKOrCksgEla+KIkYvC6SJKQOISoNSYdeIk1ayA8ExTyeR3F749CACH5BAkKAAAALAAAAAAQABAAAAVoICCKR9KMaCoaxeCoqEAkRX3AwMHWxQIIjJSAZWgUEgzBwCBAEQpMwIDwY1FHgwJCtOW2UDWYIDyqNVVkUbYr6CK+o2eUMKgWrqKhj0FrEM8jQQALPFA3MAc8CQSAMA5ZBjgqDQmHIyEAIfkECQoAAAAsAAAAABAAEAAABWAgII4j85Ao2hRIKgrEUBQJLaSHMe8zgQo6Q8sxS7RIhILhBkgumCTZsXkACBC+0cwF2GoLLoFXREDcDlkAojBICRaFLDCOQtQKjmsQSubtDFU/NXcDBHwkaw1cKQ8MiyEAIfkECQoAAAAsAAAAABAAEAAABVIgII5kaZ6AIJQCMRTFQKiDQx4GrBfGa4uCnAEhQuRgPwCBtwK+kCNFgjh6QlFYgGO7baJ2CxIioSDpwqNggWCGDVVGphly3BkOpXDrKfNm/4AhACH5BAkKAAAALAAAAAAQABAAAAVgICCOZGmeqEAMRTEQwskYbV0Yx7kYSIzQhtgoBxCKBDQCIOcoLBimRiFhSABYU5gIgW01pLUBYkRItAYAqrlhYiwKjiWAcDMWY8QjsCf4DewiBzQ2N1AmKlgvgCiMjSQhACH5BAkKAAAALAAAAAAQABAAAAVfICCOZGmeqEgUxUAIpkA0AMKyxkEiSZEIsJqhYAg+boUFSTAkiBiNHks3sg1ILAfBiS10gyqCg0UaFBCkwy3RYKiIYMAC+RAxiQgYsJdAjw5DN2gILzEEZgVcKYuMJiEAOwAAAAAAAAAAAA==) no-repeat center center; }'+
'.thumb-loading img {opacity:0.5}'+
'.thumb-current img { outline: 3px solid green }'+
'.thumb-wrap{ padding:3px; float:left; }'+
'.thumb{ padding:0px;}');
extjs_wait();
function extjs_wait() {
if( typeof window.Ext == 'undefined' || typeof window.Ext.Window == 'undefined') {
- window.setTimeout( extjs_wait,100 );
+ window.setTimeout( extjs_wait,50 );
} else {
var dummy = new Array();
dummy.push('foo');
window.Ext.each(dummy,main,window.Ext);
}
}
var main = function() {
var Ext=this;
var showDetailTimer;
Ext.apply(Function.prototype,{createInterceptor:function(fcn,scope){var method=this;return!Ext.isFunction(fcn)?this:function(){var me=this,args=arguments;fcn.target=me;fcn.method=method;return(fcn.apply(scope||me||window,args)!==false)?method.apply(me||window,args):null;};},createCallback:function(){var args=arguments,method=this;return function(){return method.apply(window,args);};},createDelegate:function(obj,args,appendArgs){var method=this;return function(){var callArgs=args||arguments;if(appendArgs===true){callArgs=Array.prototype.slice.call(arguments,0);callArgs=callArgs.concat(args);}else if(Ext.isNumber(appendArgs)){callArgs=Array.prototype.slice.call(arguments,0);var applyArgs=[appendArgs,0].concat(args);Array.prototype.splice.apply(callArgs,applyArgs);} return method.apply(obj||window,callArgs);};},defer:function(millis,obj,args,appendArgs){var fn=this.createDelegate(obj,args,appendArgs);if(millis>0){return setTimeout(fn,millis);} fn();return 0;}});Ext.applyIf(String,{format:function(format){var args=Ext.toArray(arguments,1);return format.replace(/\{(\d+)\}/g,function(m,i){return args[i];});}});
Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
expires: new Date(new Date().getTime()+(1000*60*60*24*7)) //7 days from now
}));
var picStore=new Ext.data.ArrayStore({
storeId: 'picStore',
fields:['imgUrl','thumbUrl','thumbImg','img','current','loaded']
});
var Templates = {};
var Bus = new Ext.util.Observable();
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
function resize_thumbs() {
Ext.each(Ext.query('img'),function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
var newImage = new Image();
newImage.src=this.src.replace(/images\/mini\//, "images/thumb/");
Ext.get(this).replaceWith(newImage);
}
});
}
function collect_Images() {
Ext.each(Ext.query('a[href*=image.php?id=] img'),function(){
var Img=new Image();
var ExtImg= Ext.get(Img);
ExtImg.on('load', function(e,t) {
var index = picStore.findExact('imgUrl',t.src);
if( index != -1 ) {
record=picStore.getAt(index);
record.set('loaded',true);
}
})
Img.src=this.src.replace(/thumb/,"full" );
var element={thumbUrl:this.src,imgUrl:this.src.replace(/thumb/,"full" ),thumbImg:this,img:Img};
picStore.addSorted( new picStore.recordType(element) );
});
}
function initTemplates() {
Templates.thumbTemplate = new Ext.XTemplate(
'<tpl for=".">',
'<div class="thumb-wrap">',
'<div class="thumb {[values.loaded? "thumb-done": "thumb-loading"]} {[values.current ? "thumb-current" : ""]}"><img src="{thumbUrl}"></div>',
'</div>',
'</tpl>'
);
Templates.thumbTemplate.compile();
Templates.detailsTemplate = new Ext.XTemplate(
'<tpl for=".">',
'<a href="{imgUrl}" target="_blank"><img style="max-width:{maxW}px; max-height:{maxH}px;" src="{imgUrl}"></a>',
'</tpl>'
);
Templates.detailsTemplate.compile();
}
function create_alternate_gallery() {
collect_Images();
initTemplates();
var storeView = new Ext.grid.GridPanel({
region: 'center',
store: picStore,
title: 'debug',
colModel:new Ext.grid.ColumnModel({
defaults: {
width: 120,
sortable: true
},
columns: [
{header:'URL',width:100,dataIndex:'imgUrl'},
{header:'thumbURL',width:100,dataIndex:'thumbUrl',hidden:true},
{header:'thumb',width:100,dataIndex:'thumbImg',hidden:true},
{header:'img',width:100,dataIndex:'img',hidden:true},
{header:'current',width:100,dataIndex:'current'},
{header:'loaded',width:100,dataIndex:'loaded'}
]
})
});
var thumbView=new Ext.DataView({
region:'center',
tpl: Templates.thumbTemplate,
singleSelect: true,
overClass:'x-view-over',
itemSelector: 'div.thumb-wrap',
emptyText : '<div style="padding:10px;">No images match the specified filter</div>',
store: picStore,
listeners: {
'mouseenter':{fn:function(dv,index){
if(showDetailTimer) {
clearTimeout(showDetailTimer);
}
showDetailTimer=showDetail.defer(200,this,[index]);}},
'beforeselect' : {fn:function(view){
return thumbView.store.getRange().length > 0;
}}
}
});
function showDetail(index){
var bigPic=Ext.getCmp('big-pic');
var record;
var currentIndex=picStore.findExact('current',true);
if(currentIndex != -1) {
record=picStore.getAt(currentIndex);
record.set('current',false);
}
record=picStore.getAt(index);
if( record == undefined )
return showDetail( 0 );
record.set('current',true);
picStore.commitChanges();
data=record.data;
data.maxW=Ext.getCmp('main-panel').getWidth();
data.maxH=Ext.getCmp('main-panel').getHeight();
bigPic.update(Templates.detailsTemplate.apply( data ));
}
function showNext( ) {
var currentIndex=picStore.findExact('current',true);
var nextIndex = currentIndex +1;
if( nextIndex > picStore.getCount() || currentIndex == -1 )
- nextIndex = 0;
-
- showDetail( nextIndex );
-
+ nextIndex = 0;
+
+ showDetail( nextIndex );
}
function showPrev( ) {
var currentIndex=picStore.findExact('current',true);
var nextIndex = currentIndex -1;
if( nextIndex < 0 || currentIndex == -1 )
- nextIndex = picStore.getCount();
+ nextIndex = picStore.getCount()-1;
- showDetail( nextIndex );
-
+ showDetail( nextIndex );
}
Bus.on('showNext', showNext );
Bus.on('showPrev', showPrev );
var win = new Ext.Window({
width:800,
height:600,
border:false,
id:'lightroom-window',
stateful:true,
layout:'border',
title:'Lightroom',
maximizable:true,
defaults: {
collapsible: true,
split: true,
collapseMode: 'mini',
collapsed:true
},
items: [
{
title: 'North',
region: 'north',
html: 'North',
id:'north-panel',
margins: '5 5 0 5',
height: 70
},{
header: false,
split: false,
region: 'south',
collapseMode: 'mini',
titleCollapse: false,
margins: '0 0 0 0',
height: 30,
id:'south-panel',
layout: {type: 'hbox', align: 'stretch'},
items:[ {
xtype: 'button',
text: '<',
flex: 1,
clickEvent: 'click',
handler: function(){ Bus.fireEvent('showPrev'); }
},{
xtype: 'button',
text: '>',
flex: 1,
clickEvent: 'click',
handler: function(){ Bus.fireEvent('showNext'); }
}
]
},{
region: 'west',
html: 'West',
margins: '0 0 0 5',
width: 300,
id:'west-panel',
layout:'border',
collapsed:false,
items:[ {xtype:'tabpanel',region:'center',activeTab:0,items:[storeView ]} ]
},{
title:'thumbs',
region: 'east',
html: 'East',
margins: '0 5 0 0',
width: 250,
id:'east-panel',
collapsed:false,
layout:'border',
items:[ {
region: 'center',
autoScroll: true,
items: thumbView },
{region:'south', height:25,id:'pager-panel',collapsible:false}]
},{
region: 'center',
collapsible: false,
collapsed:false,
id:'main-panel',
layout:'fit',
items: [{id:'big-pic'}]
}
]
});
win.show();
win.maximize();
showDetail.defer(250,this,[0]);
Ext.getCmp('pager-panel').body.appendChild(Ext.DomQuery.selectNode('div[id=gallery]').firstElementChild); // server paging
+ win.on('close',function() {this.restore();return true;});
};
}})(unsafeWindow);
|
monkeyoperator/greasemonkey-scripts
|
6461f5518892a2356aeb7dc55a2fa39231f609c3
|
added prev-next buttons
|
diff --git a/imagefap_lightroom.user.js b/imagefap_lightroom.user.js
index 6c0d69b..53f724b 100644
--- a/imagefap_lightroom.user.js
+++ b/imagefap_lightroom.user.js
@@ -1,263 +1,306 @@
// ==UserScript==
// @name ImageFap Lightroom
// @description Show content from Imagefap.com
// @include *imagefap.com/*
// @unwrap
// ==/UserScript==
document.cookie='popundr=1; path=/; expires='+new Date(Date.now()+24*60*60*1000*356).toGMTString();
(function(window) {
function loadScript(url) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'utf-8';
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
}
function loadCss( url ) {
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
document.getElementsByTagName('head')[0].appendChild(link);
}
function addStyle( style ) {
var tag = document.createElement('style');
tag.innerHTML=style;
document.getElementsByTagName('head')[0].appendChild(tag);
}
loadScript('http://extjs.cachefly.net/ext-3.2.0/adapter/ext/ext-base-debug.js');
loadScript('http://extjs.cachefly.net/ext-3.2.0/ext-all-debug.js');
loadCss('http://extjs.cachefly.net/ext-3.2.0/resources/css/ext-all.css');
addStyle('.thumb-loading { background: transparent url(data:image/gif;base64,R0lGODlhEAAQAPQAAP///wAAAPj4+Dg4OISEhAYGBiYmJtbW1qioqBYWFnZ2dmZmZuTk5JiYmMbGxkhISFZWVgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFUCAgjmRpnqUwFGwhKoRgqq2YFMaRGjWA8AbZiIBbjQQ8AmmFUJEQhQGJhaKOrCksgEla+KIkYvC6SJKQOISoNSYdeIk1ayA8ExTyeR3F749CACH5BAkKAAAALAAAAAAQABAAAAVoICCKR9KMaCoaxeCoqEAkRX3AwMHWxQIIjJSAZWgUEgzBwCBAEQpMwIDwY1FHgwJCtOW2UDWYIDyqNVVkUbYr6CK+o2eUMKgWrqKhj0FrEM8jQQALPFA3MAc8CQSAMA5ZBjgqDQmHIyEAIfkECQoAAAAsAAAAABAAEAAABWAgII4j85Ao2hRIKgrEUBQJLaSHMe8zgQo6Q8sxS7RIhILhBkgumCTZsXkACBC+0cwF2GoLLoFXREDcDlkAojBICRaFLDCOQtQKjmsQSubtDFU/NXcDBHwkaw1cKQ8MiyEAIfkECQoAAAAsAAAAABAAEAAABVIgII5kaZ6AIJQCMRTFQKiDQx4GrBfGa4uCnAEhQuRgPwCBtwK+kCNFgjh6QlFYgGO7baJ2CxIioSDpwqNggWCGDVVGphly3BkOpXDrKfNm/4AhACH5BAkKAAAALAAAAAAQABAAAAVgICCOZGmeqEAMRTEQwskYbV0Yx7kYSIzQhtgoBxCKBDQCIOcoLBimRiFhSABYU5gIgW01pLUBYkRItAYAqrlhYiwKjiWAcDMWY8QjsCf4DewiBzQ2N1AmKlgvgCiMjSQhACH5BAkKAAAALAAAAAAQABAAAAVfICCOZGmeqEgUxUAIpkA0AMKyxkEiSZEIsJqhYAg+boUFSTAkiBiNHks3sg1ILAfBiS10gyqCg0UaFBCkwy3RYKiIYMAC+RAxiQgYsJdAjw5DN2gILzEEZgVcKYuMJiEAOwAAAAAAAAAAAA==) no-repeat center center; }'+
- '.thumb-loading img {opacity:0.5}'+
+ '.thumb-loading img {opacity:0.5}'+
+ '.thumb-current img { outline: 3px solid green }'+
'.thumb-wrap{ padding:3px; float:left; }'+
- '.thumb{ padding:0px;}');
+ '.thumb{ padding:0px;}');
extjs_wait();
function extjs_wait() {
if( typeof window.Ext == 'undefined' || typeof window.Ext.Window == 'undefined') {
window.setTimeout( extjs_wait,100 );
} else {
var dummy = new Array();
dummy.push('foo');
window.Ext.each(dummy,main,window.Ext);
}
}
var main = function() {
var Ext=this;
var showDetailTimer;
Ext.apply(Function.prototype,{createInterceptor:function(fcn,scope){var method=this;return!Ext.isFunction(fcn)?this:function(){var me=this,args=arguments;fcn.target=me;fcn.method=method;return(fcn.apply(scope||me||window,args)!==false)?method.apply(me||window,args):null;};},createCallback:function(){var args=arguments,method=this;return function(){return method.apply(window,args);};},createDelegate:function(obj,args,appendArgs){var method=this;return function(){var callArgs=args||arguments;if(appendArgs===true){callArgs=Array.prototype.slice.call(arguments,0);callArgs=callArgs.concat(args);}else if(Ext.isNumber(appendArgs)){callArgs=Array.prototype.slice.call(arguments,0);var applyArgs=[appendArgs,0].concat(args);Array.prototype.splice.apply(callArgs,applyArgs);} return method.apply(obj||window,callArgs);};},defer:function(millis,obj,args,appendArgs){var fn=this.createDelegate(obj,args,appendArgs);if(millis>0){return setTimeout(fn,millis);} fn();return 0;}});Ext.applyIf(String,{format:function(format){var args=Ext.toArray(arguments,1);return format.replace(/\{(\d+)\}/g,function(m,i){return args[i];});}});
Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
expires: new Date(new Date().getTime()+(1000*60*60*24*7)) //7 days from now
}));
var picStore=new Ext.data.ArrayStore({
storeId: 'picStore',
fields:['imgUrl','thumbUrl','thumbImg','img','current','loaded']
});
var Templates = {};
+ var Bus = new Ext.util.Observable();
+
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
function resize_thumbs() {
Ext.each(Ext.query('img'),function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
var newImage = new Image();
newImage.src=this.src.replace(/images\/mini\//, "images/thumb/");
Ext.get(this).replaceWith(newImage);
}
});
}
function collect_Images() {
Ext.each(Ext.query('a[href*=image.php?id=] img'),function(){
var Img=new Image();
var ExtImg= Ext.get(Img);
ExtImg.on('load', function(e,t) {
var index = picStore.findExact('imgUrl',t.src);
if( index != -1 ) {
record=picStore.getAt(index);
record.set('loaded',true);
}
})
Img.src=this.src.replace(/thumb/,"full" );
var element={thumbUrl:this.src,imgUrl:this.src.replace(/thumb/,"full" ),thumbImg:this,img:Img};
picStore.addSorted( new picStore.recordType(element) );
});
}
function initTemplates() {
Templates.thumbTemplate = new Ext.XTemplate(
'<tpl for=".">',
'<div class="thumb-wrap">',
- '<div class="thumb {[values.loaded? "thumb-done": "thumb-loading"]}"><img src="{thumbUrl}"></div>',
+ '<div class="thumb {[values.loaded? "thumb-done": "thumb-loading"]} {[values.current ? "thumb-current" : ""]}"><img src="{thumbUrl}"></div>',
'</div>',
'</tpl>'
);
Templates.thumbTemplate.compile();
Templates.detailsTemplate = new Ext.XTemplate(
'<tpl for=".">',
- '<img style="max-width:{maxW}px; max-height:{maxH}px;" src="{imgUrl}">',
+ '<a href="{imgUrl}" target="_blank"><img style="max-width:{maxW}px; max-height:{maxH}px;" src="{imgUrl}"></a>',
'</tpl>'
);
Templates.detailsTemplate.compile();
}
function create_alternate_gallery() {
collect_Images();
initTemplates();
var storeView = new Ext.grid.GridPanel({
region: 'center',
store: picStore,
title: 'debug',
colModel:new Ext.grid.ColumnModel({
defaults: {
width: 120,
sortable: true
},
columns: [
{header:'URL',width:100,dataIndex:'imgUrl'},
{header:'thumbURL',width:100,dataIndex:'thumbUrl',hidden:true},
{header:'thumb',width:100,dataIndex:'thumbImg',hidden:true},
{header:'img',width:100,dataIndex:'img',hidden:true},
{header:'current',width:100,dataIndex:'current'},
{header:'loaded',width:100,dataIndex:'loaded'}
]
})
});
var thumbView=new Ext.DataView({
region:'center',
tpl: Templates.thumbTemplate,
singleSelect: true,
overClass:'x-view-over',
itemSelector: 'div.thumb-wrap',
emptyText : '<div style="padding:10px;">No images match the specified filter</div>',
store: picStore,
listeners: {
'mouseenter':{fn:function(dv,index){
if(showDetailTimer) {
clearTimeout(showDetailTimer);
}
showDetailTimer=showDetail.defer(200,this,[index]);}},
'beforeselect' : {fn:function(view){
return thumbView.store.getRange().length > 0;
}}
}
});
function showDetail(index){
var bigPic=Ext.getCmp('big-pic');
var record;
- currentIndex=picStore.findExact('current',true);
+ var currentIndex=picStore.findExact('current',true);
if(currentIndex != -1) {
record=picStore.getAt(currentIndex);
record.set('current',false);
}
record=picStore.getAt(index);
+ if( record == undefined )
+ return showDetail( 0 );
+
record.set('current',true);
picStore.commitChanges();
data=record.data;
data.maxW=Ext.getCmp('main-panel').getWidth();
data.maxH=Ext.getCmp('main-panel').getHeight();
bigPic.update(Templates.detailsTemplate.apply( data ));
}
+ function showNext( ) {
+ var currentIndex=picStore.findExact('current',true);
+ var nextIndex = currentIndex +1;
+ if( nextIndex > picStore.getCount() || currentIndex == -1 )
+ nextIndex = 0;
+
+ showDetail( nextIndex );
+
+ }
+ function showPrev( ) {
+ var currentIndex=picStore.findExact('current',true);
+ var nextIndex = currentIndex -1;
+ if( nextIndex < 0 || currentIndex == -1 )
+ nextIndex = picStore.getCount();
+ showDetail( nextIndex );
+
+ }
+
+ Bus.on('showNext', showNext );
+ Bus.on('showPrev', showPrev );
var win = new Ext.Window({
width:800,
height:600,
border:false,
id:'lightroom-window',
stateful:true,
layout:'border',
title:'Lightroom',
maximizable:true,
defaults: {
collapsible: true,
split: true,
collapseMode: 'mini',
collapsed:true
},
items: [
{
title: 'North',
region: 'north',
html: 'North',
id:'north-panel',
margins: '5 5 0 5',
height: 70
},{
- title: 'South',
+ header: false,
+ split: false,
region: 'south',
- html: 'South',
collapseMode: 'mini',
- margins: '0 5 5 5',
- height: 70,
- id:'south-panel'
+ titleCollapse: false,
+ margins: '0 0 0 0',
+ height: 30,
+ id:'south-panel',
+ layout: {type: 'hbox', align: 'stretch'},
+ items:[ {
+ xtype: 'button',
+ text: '<',
+ flex: 1,
+ clickEvent: 'click',
+ handler: function(){ Bus.fireEvent('showPrev'); }
+ },{
+ xtype: 'button',
+ text: '>',
+ flex: 1,
+ clickEvent: 'click',
+ handler: function(){ Bus.fireEvent('showNext'); }
+ }
+ ]
+
},{
region: 'west',
html: 'West',
margins: '0 0 0 5',
width: 300,
id:'west-panel',
layout:'border',
collapsed:false,
items:[ {xtype:'tabpanel',region:'center',activeTab:0,items:[storeView ]} ]
},{
title:'thumbs',
region: 'east',
html: 'East',
margins: '0 5 0 0',
width: 250,
id:'east-panel',
collapsed:false,
layout:'border',
items:[ {
region: 'center',
autoScroll: true,
items: thumbView },
{region:'south', height:25,id:'pager-panel',collapsible:false}]
},{
region: 'center',
collapsible: false,
collapsed:false,
id:'main-panel',
layout:'fit',
items: [{id:'big-pic'}]
}
]
});
win.show();
win.maximize();
showDetail.defer(250,this,[0]);
Ext.getCmp('pager-panel').body.appendChild(Ext.DomQuery.selectNode('div[id=gallery]').firstElementChild); // server paging
};
}})(unsafeWindow);
|
monkeyoperator/greasemonkey-scripts
|
20955f7b0e744caa33c892c0a7a7a7c973f10089
|
reversed changes for extJs
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index ecf32aa..cddf59e 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,385 +1,378 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js
+// @require http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js
+// @require http://layout.jquery-dev.net/download/jquery.layout.min.js
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
var jqLayout; // jQuery Layout-Object
- var Ext;
- var debugging = true;
+ var pageTracker;
var threadTimeout = 3000;
var numThreads = 6;
var chunksize=100;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var debugging=false;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
insertCSS();
-// insertExtJs();
- main()
+ main();
- function add_script_link(url) {
- var script = document.createElement("script");
- script.type = "text/javascript";
- script.src = url;
- document.getElementsByTagName('head')[0].appendChild(script);
- }
-
- function insertExtJs( ) {
-
- // Add javascripts and stylesheets
- add_script_link('http://extjs.cachefly.net/ext-3.2.0/adapter/ext/ext-base-debug.js');
- add_script_link('http://extjs.cachefly.net/ext-3.2.0/ext-all-debug.js');
- wait();
- }
- function wait() {
- if (typeof(unsafeWindow.Ext) == 'undefined' || typeof(unsafeWindow.Ext.Template) == 'undefined') {
- window.setTimeout(wait, 100);
- } else {
- Ext = unsafeWindow.Ext;
- main();
- }
- }
function main() {
-
- resize_thumbs();
+ log('payload started');
+ resize_thumbs();
relative_dates();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.unbind('click')
.click(function(){
window.open(this.src);
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function relative_dates() {
dateTimeReg=/([0-9]{2}:[0-9]{2}:[0-9]{2})|([0-9]{4}-[0-9]{2}-[0-9]{2})/;
dateELs = $('center,span,td').filter(function(){
return $(this).children().length==0 && dateTimeReg.test(this.textContent || this.innerText || $(this).text() || "");
});
dateELs.each(function(){
var $this=$(this);
var $thisText = $.trim($this.text());
var values;
var postdate = new Date();
var has_time = $thisText.indexOf(':') !== -1;
var has_date = $thisText.indexOf('-') !== -1;
var date_values = $thisText.split('-');
var time_values = $thisText.split(':');
if( has_date && has_time ) {
values = $thisText.split(" ");
date_values = values[0].split('-');
time_values = values[1].split(':');
}
if( has_date ) {
postdate.setFullYear( date_values[0] );
postdate.setMonth( date_values[1] - 1 );
postdate.setDate( date_values[2] );
}
if ( has_time ){
postdate.setHours( time_values[0] );
postdate.setMinutes( time_values[1]);
postdate.setSeconds( time_values[2] );
}
var relative_to = new Date();
var delta = parseInt((relative_to.getTime() - postdate.getTime() ) / 1000 );
// delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = delta + 'seconds ago';
} else if(delta < (60 * 60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else if(delta < (31 * 86400)) {
r = (parseInt(delta / 86400)).toString() + ' days ago';
} else {
r = '' + (parseInt(delta / (86400 * 30))).toString() + ' months ago';
}
$this.html( r );
$this.attr('title',$thisText);
});
}
function save_clubvisit( clubid ) {
log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
$('<div id="south-pane" class="ui-layout-south"></div>').appendTo('body');
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
$(':contains(next)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-e')
.replaceWith('').appendTo(serverPaging);
$(':contains(prev)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-w')
.replaceWith('').prependTo(serverPaging);
$('.fg-button').hover(function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); });
$('span',serverPaging).addClass('fg-left');
profileLinks = $('#menubar').appendTo('body').append(favlink);
profileLinks.addClass('ui-layout-north');
serverPaging.appendTo('#south-pane');
$('<div id="pagingtype">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').appendTo('#south-pane');
}
thumbholder = $('<div class="ui-layout-east" id="east-pane"></div>')
.appendTo($('body'));
piccontainer = $('<div class="ui-layout-center" id="center-pane"></div>').appendTo($('body'));
jqLayout=initLayout();
setInterval(function() {
saveOpts={
east:{size: jqLayout.state.east.size}
};
GM_setObject('layout',saveOpts);
}, 1000);
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
$(this).addClass('thumb thumb_initial');
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div id="infodiv"></div>')
.appendTo('#south-pane')
.progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
loadfunction = function( event, timeout ) {
log( timeout );
try{
if( $(this).data('prev') && !timeout ) {
$(this).data('prev').pic.parent().addClass('thumb_done').removeClass('thumb_loading');
}
$(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
var next=preload.shift();
next.pic.parent().addClass('thumb_loading').removeClass('thumb_initial');
var newthread = $(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
setTimeout( function() {
newthread.trigger('load',[true]);
},threadTimeout);
} else {
// infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},500);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < numThreads; i++ ) {
setTimeout(function(){
var thread=img.clone(true).trigger('load');
setTimeout(function(){
thread.trigger('load',[true]);
},threadTimeout);
},i*100);
}
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ log(e); }
}
}
function enhance_myclubs() {
log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
console.log( clubid+' lastvisit: '+lastvisit);
console.log( clubid+' lastmod: '+lastmod);
$(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function initLayout() {
layoutSettings = {
north: {
initClosed: true
},
south:{
size: "30"
},
center:{ },
east:{
size: "150"
}
};
savedLayout=GM_getObject('layout',{});
$.extend( layoutSettings, savedLayout);
return $('body').layout( layoutSettings );
}
function log( something ) {
if( debugging )
console.log( something );
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
function insertCSS() {
- $('head').append('<link href="http://extjs.cachefly.net/ext-3.2.0/resources/css/ext-all.css" rel="stylesheet" type="text/css">');
+ $('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
$('head').append('<style id="GM_fapCSS" type="text/css">'+
+ '.fg-button,.fg-left {float:left;} '+
+ '.fg-left .link3, .fg-left b { margin:0 -1px};'+
+ '.clear { clear: both; height:0; line-height:0}'+
+ '.ui-layout-pane {'+
+ ' background: #FFF;'+
+ ' border: 0px solid #BBB; }'+
+ '.ui-layout-pane-east{ overflow-y: scroll }'+
+ '.ui-layout-resizer { background: #DDD; }'+
+ '.ui-layout-toggler { background: #AAA; }'+
+ '#south-pane { padding: 5px; font-family: "Arial narrow"}'+
+ '#infodiv { float: right;color:#aaa;background:#fff;width:300px;height:10px;}'+
+ '#pagingtype { float: right;margin-left: 20px;}'+
+ '.thumb { display: block; float: left; border: 1px solid #eee;}'+
+ '.thumb img { border: 3px solid #fff; display:inline; opacity:0; '+
+ ' maxWidth:120px; maxHeight:120px }'+
'.thumb_initial { background: transparent url(data:image/gif;base64,'+
'R0lGODlhEAAQAPEAAP///wAAADY2NgAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdp'+
'dGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvkA7U64qGb2C6gtyXmeJ'+
'HIl+WYeuY7SSLozV6WvK9pfqWv8IKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvhY7DYhY'+
'5bV62xl9XvZJFCiGaReS1Xa5ICyP2jnS+M7drPgIKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLISP'+
'acLtvk6TE4jF6L3WZsyFlcd1pEZhKBixYOie8FiJ39nS97f39gNUCBEFACH5BAkKAAAALAAAAAAQ'+
'ABAAAAIshI9pwu2+xGmTrSqjBZlqfnnc1onmh44RxoIp5JpWN2b1Vdvn/ZbPb1MIAQUAIfkECQoA'+
'AAAsAAAAABAAEAAAAi2Ej2nC7b7YaVPEamPOgOqtYd3SSeFYmul0rlcpnpyXgu4K0t6mq/wD5CiG'+
'gAIAIfkECQoAAAAsAAAAABAAEAAAAiyEj2nC7b7akSuKyXDE11ZvdWLmiQB1kiOZdifYailHvzBk'+
'o5Kpq+HzUAgRBQA7AAAAAAAAAAAA) no-repeat center center; }'+
'.thumb_loading { background: transparent url(data:image/gif;base64,'+
'R0lGODlhEAAQAPQAAP///wAAAPj4+Dg4OISEhAYGBiYmJtbW1qioqBYWFnZ2dmZmZuTk5JiYmMbGxkhISFZWVgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05F'+
'VFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFUCAgjmRpnqUwFGwhKoRgqq2YFMaRGjWA8AbZiIBbjQQ8AmmFUJEQhQGJhaKOrCksgEla'+
'+KIkYvC6SJKQOISoNSYdeIk1ayA8ExTyeR3F749CACH5BAkKAAAALAAAAAAQABAAAAVoICCKR9KMaCoaxeCoqEAkRX3AwMHWxQIIjJSAZWgUEgzBwCBAEQpMwIDwY1FHgwJCtOW2UDWYIDyqNVVkUbYr'+
'6CK+o2eUMKgWrqKhj0FrEM8jQQALPFA3MAc8CQSAMA5ZBjgqDQmHIyEAIfkECQoAAAAsAAAAABAAEAAABWAgII4j85Ao2hRIKgrEUBQJLaSHMe8zgQo6Q8sxS7RIhILhBkgumCTZsXkACBC+0cwF2GoL'+
'LoFXREDcDlkAojBICRaFLDCOQtQKjmsQSubtDFU/NXcDBHwkaw1cKQ8MiyEAIfkECQoAAAAsAAAAABAAEAAABVIgII5kaZ6AIJQCMRTFQKiDQx4GrBfGa4uCnAEhQuRgPwCBtwK+kCNFgjh6QlFYgGO7'+
'baJ2CxIioSDpwqNggWCGDVVGphly3BkOpXDrKfNm/4AhACH5BAkKAAAALAAAAAAQABAAAAVgICCOZGmeqEAMRTEQwskYbV0Yx7kYSIzQhtgoBxCKBDQCIOcoLBimRiFhSABYU5gIgW01pLUBYkRItAYA'+
'qrlhYiwKjiWAcDMWY8QjsCf4DewiBzQ2N1AmKlgvgCiMjSQhACH5BAkKAAAALAAAAAAQABAAAAVfICCOZGmeqEgUxUAIpkA0AMKyxkEiSZEIsJqhYAg+boUFSTAkiBiNHks3sg1ILAfBiS10gyqCg0Ua'+
'FBCkwy3RYKiIYMAC+RAxiQgYsJdAjw5DN2gILzEEZgVcKYuMJiEAOwAAAAAAAAAAAA==) no-repeat center center; }'+
'.thumb_loading img { opacity:0.5; }'+
'.thumb_done { background: transparent}'+
'.thumb_done img { opacity:1; }'+
'</style>');
}
|
monkeyoperator/greasemonkey-scripts
|
7039aabb3d54a28a91eb5f02b63687ec6c1e5986
|
* added Loading indicator * Layout is preserved by Ext.state.CookieProvider
|
diff --git a/imagefap_lightroom.user.js b/imagefap_lightroom.user.js
index 0917f11..6c0d69b 100644
--- a/imagefap_lightroom.user.js
+++ b/imagefap_lightroom.user.js
@@ -1,239 +1,263 @@
// ==UserScript==
// @name ImageFap Lightroom
// @description Show content from Imagefap.com
// @include *imagefap.com/*
// @unwrap
// ==/UserScript==
document.cookie='popundr=1; path=/; expires='+new Date(Date.now()+24*60*60*1000*356).toGMTString();
(function(window) {
function loadScript(url) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'utf-8';
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
}
- function loadCss( url ) {
- var link = document.createElement('link');
- link.type = 'text/css';
- link.rel = 'stylesheet';
- link.href = url;
- document.getElementsByTagName('head')[0].appendChild(link);
-
- }
+ function loadCss( url ) {
+ var link = document.createElement('link');
+ link.type = 'text/css';
+ link.rel = 'stylesheet';
+ link.href = url;
+ document.getElementsByTagName('head')[0].appendChild(link);
+
+ }
+ function addStyle( style ) {
+ var tag = document.createElement('style');
+ tag.innerHTML=style;
+ document.getElementsByTagName('head')[0].appendChild(tag);
+ }
loadScript('http://extjs.cachefly.net/ext-3.2.0/adapter/ext/ext-base-debug.js');
loadScript('http://extjs.cachefly.net/ext-3.2.0/ext-all-debug.js');
loadCss('http://extjs.cachefly.net/ext-3.2.0/resources/css/ext-all.css');
+ addStyle('.thumb-loading { background: transparent url(data:image/gif;base64,R0lGODlhEAAQAPQAAP///wAAAPj4+Dg4OISEhAYGBiYmJtbW1qioqBYWFnZ2dmZmZuTk5JiYmMbGxkhISFZWVgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFUCAgjmRpnqUwFGwhKoRgqq2YFMaRGjWA8AbZiIBbjQQ8AmmFUJEQhQGJhaKOrCksgEla+KIkYvC6SJKQOISoNSYdeIk1ayA8ExTyeR3F749CACH5BAkKAAAALAAAAAAQABAAAAVoICCKR9KMaCoaxeCoqEAkRX3AwMHWxQIIjJSAZWgUEgzBwCBAEQpMwIDwY1FHgwJCtOW2UDWYIDyqNVVkUbYr6CK+o2eUMKgWrqKhj0FrEM8jQQALPFA3MAc8CQSAMA5ZBjgqDQmHIyEAIfkECQoAAAAsAAAAABAAEAAABWAgII4j85Ao2hRIKgrEUBQJLaSHMe8zgQo6Q8sxS7RIhILhBkgumCTZsXkACBC+0cwF2GoLLoFXREDcDlkAojBICRaFLDCOQtQKjmsQSubtDFU/NXcDBHwkaw1cKQ8MiyEAIfkECQoAAAAsAAAAABAAEAAABVIgII5kaZ6AIJQCMRTFQKiDQx4GrBfGa4uCnAEhQuRgPwCBtwK+kCNFgjh6QlFYgGO7baJ2CxIioSDpwqNggWCGDVVGphly3BkOpXDrKfNm/4AhACH5BAkKAAAALAAAAAAQABAAAAVgICCOZGmeqEAMRTEQwskYbV0Yx7kYSIzQhtgoBxCKBDQCIOcoLBimRiFhSABYU5gIgW01pLUBYkRItAYAqrlhYiwKjiWAcDMWY8QjsCf4DewiBzQ2N1AmKlgvgCiMjSQhACH5BAkKAAAALAAAAAAQABAAAAVfICCOZGmeqEgUxUAIpkA0AMKyxkEiSZEIsJqhYAg+boUFSTAkiBiNHks3sg1ILAfBiS10gyqCg0UaFBCkwy3RYKiIYMAC+RAxiQgYsJdAjw5DN2gILzEEZgVcKYuMJiEAOwAAAAAAAAAAAA==) no-repeat center center; }'+
+ '.thumb-loading img {opacity:0.5}'+
+ '.thumb-wrap{ padding:3px; float:left; }'+
+ '.thumb{ padding:0px;}');
extjs_wait();
function extjs_wait() {
if( typeof window.Ext == 'undefined' || typeof window.Ext.Window == 'undefined') {
window.setTimeout( extjs_wait,100 );
} else {
var dummy = new Array();
dummy.push('foo');
window.Ext.each(dummy,main,window.Ext);
}
}
var main = function() {
var Ext=this;
var showDetailTimer;
Ext.apply(Function.prototype,{createInterceptor:function(fcn,scope){var method=this;return!Ext.isFunction(fcn)?this:function(){var me=this,args=arguments;fcn.target=me;fcn.method=method;return(fcn.apply(scope||me||window,args)!==false)?method.apply(me||window,args):null;};},createCallback:function(){var args=arguments,method=this;return function(){return method.apply(window,args);};},createDelegate:function(obj,args,appendArgs){var method=this;return function(){var callArgs=args||arguments;if(appendArgs===true){callArgs=Array.prototype.slice.call(arguments,0);callArgs=callArgs.concat(args);}else if(Ext.isNumber(appendArgs)){callArgs=Array.prototype.slice.call(arguments,0);var applyArgs=[appendArgs,0].concat(args);Array.prototype.splice.apply(callArgs,applyArgs);} return method.apply(obj||window,callArgs);};},defer:function(millis,obj,args,appendArgs){var fn=this.createDelegate(obj,args,appendArgs);if(millis>0){return setTimeout(fn,millis);} fn();return 0;}});Ext.applyIf(String,{format:function(format){var args=Ext.toArray(arguments,1);return format.replace(/\{(\d+)\}/g,function(m,i){return args[i];});}});
+ Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
+ expires: new Date(new Date().getTime()+(1000*60*60*24*7)) //7 days from now
+ }));
var picStore=new Ext.data.ArrayStore({
storeId: 'picStore',
- fields:['imgUrl','thumbUrl','thumbImg','img','current']
+ fields:['imgUrl','thumbUrl','thumbImg','img','current','loaded']
});
var Templates = {};
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
function resize_thumbs() {
Ext.each(Ext.query('img'),function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
var newImage = new Image();
newImage.src=this.src.replace(/images\/mini\//, "images/thumb/");
Ext.get(this).replaceWith(newImage);
}
});
}
function collect_Images() {
Ext.each(Ext.query('a[href*=image.php?id=] img'),function(){
var Img=new Image();
+ var ExtImg= Ext.get(Img);
+
+ ExtImg.on('load', function(e,t) {
+ var index = picStore.findExact('imgUrl',t.src);
+ if( index != -1 ) {
+ record=picStore.getAt(index);
+ record.set('loaded',true);
+ }
+ })
Img.src=this.src.replace(/thumb/,"full" );
var element={thumbUrl:this.src,imgUrl:this.src.replace(/thumb/,"full" ),thumbImg:this,img:Img};
picStore.addSorted( new picStore.recordType(element) );
});
}
function initTemplates() {
Templates.thumbTemplate = new Ext.XTemplate(
'<tpl for=".">',
- '<div class="thumb-wrap" style="padding:3px;border:1px solid #888;border-width:1px 0 0 0" >',
- '<div class="thumb" style="padding-bottom:3px"><img src="{thumbUrl}"></div>',
+ '<div class="thumb-wrap">',
+ '<div class="thumb {[values.loaded? "thumb-done": "thumb-loading"]}"><img src="{thumbUrl}"></div>',
'</div>',
'</tpl>'
);
Templates.thumbTemplate.compile();
Templates.detailsTemplate = new Ext.XTemplate(
'<tpl for=".">',
'<img style="max-width:{maxW}px; max-height:{maxH}px;" src="{imgUrl}">',
'</tpl>'
);
Templates.detailsTemplate.compile();
}
function create_alternate_gallery() {
collect_Images();
initTemplates();
var storeView = new Ext.grid.GridPanel({
region: 'center',
store: picStore,
title: 'debug',
colModel:new Ext.grid.ColumnModel({
defaults: {
width: 120,
sortable: true
},
columns: [
{header:'URL',width:100,dataIndex:'imgUrl'},
{header:'thumbURL',width:100,dataIndex:'thumbUrl',hidden:true},
{header:'thumb',width:100,dataIndex:'thumbImg',hidden:true},
{header:'img',width:100,dataIndex:'img',hidden:true},
- {header:'current',width:100,dataIndex:'current'}
+ {header:'current',width:100,dataIndex:'current'},
+ {header:'loaded',width:100,dataIndex:'loaded'}
]
})
});
var thumbView=new Ext.DataView({
region:'center',
tpl: Templates.thumbTemplate,
singleSelect: true,
overClass:'x-view-over',
itemSelector: 'div.thumb-wrap',
emptyText : '<div style="padding:10px;">No images match the specified filter</div>',
store: picStore,
listeners: {
'mouseenter':{fn:function(dv,index){
if(showDetailTimer) {
clearTimeout(showDetailTimer);
}
showDetailTimer=showDetail.defer(200,this,[index]);}},
'beforeselect' : {fn:function(view){
return thumbView.store.getRange().length > 0;
}}
}
});
function showDetail(index){
var bigPic=Ext.getCmp('big-pic');
var record;
currentIndex=picStore.findExact('current',true);
if(currentIndex != -1) {
record=picStore.getAt(currentIndex);
record.set('current',false);
}
record=picStore.getAt(index);
record.set('current',true);
picStore.commitChanges();
data=record.data;
data.maxW=Ext.getCmp('main-panel').getWidth();
data.maxH=Ext.getCmp('main-panel').getHeight();
bigPic.update(Templates.detailsTemplate.apply( data ));
}
var win = new Ext.Window({
width:800,
height:600,
border:false,
+ id:'lightroom-window',
+ stateful:true,
layout:'border',
title:'Lightroom',
maximizable:true,
defaults: {
collapsible: true,
split: true,
collapseMode: 'mini',
collapsed:true
},
items: [
{
title: 'North',
region: 'north',
html: 'North',
id:'north-panel',
margins: '5 5 0 5',
height: 70
},{
title: 'South',
region: 'south',
html: 'South',
collapseMode: 'mini',
margins: '0 5 5 5',
height: 70,
id:'south-panel'
},{
region: 'west',
html: 'West',
margins: '0 0 0 5',
- width: 500,
+ width: 300,
id:'west-panel',
layout:'border',
- items:[ {xtype:'tabpanel',region:'center',items:[{title:'favs'}, storeView ]} ]
+ collapsed:false,
+ items:[ {xtype:'tabpanel',region:'center',activeTab:0,items:[storeView ]} ]
},{
- title: 'East',
+ title:'thumbs',
region: 'east',
html: 'East',
margins: '0 5 0 0',
width: 250,
id:'east-panel',
collapsed:false,
layout:'border',
-
items:[ {
region: 'center',
autoScroll: true,
items: thumbView },
- {region:'south', height:20,id:'pager-panel',collapsible:false}]
+ {region:'south', height:25,id:'pager-panel',collapsible:false}]
},{
region: 'center',
collapsible: false,
collapsed:false,
id:'main-panel',
layout:'fit',
items: [{id:'big-pic'}]
}
]
});
win.show();
win.maximize();
showDetail.defer(250,this,[0]);
Ext.getCmp('pager-panel').body.appendChild(Ext.DomQuery.selectNode('div[id=gallery]').firstElementChild); // server paging
};
}})(unsafeWindow);
|
monkeyoperator/greasemonkey-scripts
|
157f21ad3721e67dddf437ff9c4f344efe879605
|
Lightroom V0.1
|
diff --git a/imagefap_lightroom.user.js b/imagefap_lightroom.user.js
index d6d5587..0917f11 100644
--- a/imagefap_lightroom.user.js
+++ b/imagefap_lightroom.user.js
@@ -1,98 +1,239 @@
// ==UserScript==
// @name ImageFap Lightroom
// @description Show content from Imagefap.com
// @include *imagefap.com/*
// @unwrap
// ==/UserScript==
+document.cookie='popundr=1; path=/; expires='+new Date(Date.now()+24*60*60*1000*356).toGMTString();
(function(window) {
function loadScript(url) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'utf-8';
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
}
function loadCss( url ) {
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
document.getElementsByTagName('head')[0].appendChild(link);
}
loadScript('http://extjs.cachefly.net/ext-3.2.0/adapter/ext/ext-base-debug.js');
loadScript('http://extjs.cachefly.net/ext-3.2.0/ext-all-debug.js');
loadCss('http://extjs.cachefly.net/ext-3.2.0/resources/css/ext-all.css');
extjs_wait();
function extjs_wait() {
if( typeof window.Ext == 'undefined' || typeof window.Ext.Window == 'undefined') {
window.setTimeout( extjs_wait,100 );
} else {
- var dummy = new Array();
- dummy.push('foo');
- window.Ext.each(dummy,main,window.Ext);
+ var dummy = new Array();
+ dummy.push('foo');
+ window.Ext.each(dummy,main,window.Ext);
}
}
var main = function() {
var Ext=this;
+ var showDetailTimer;
+ Ext.apply(Function.prototype,{createInterceptor:function(fcn,scope){var method=this;return!Ext.isFunction(fcn)?this:function(){var me=this,args=arguments;fcn.target=me;fcn.method=method;return(fcn.apply(scope||me||window,args)!==false)?method.apply(me||window,args):null;};},createCallback:function(){var args=arguments,method=this;return function(){return method.apply(window,args);};},createDelegate:function(obj,args,appendArgs){var method=this;return function(){var callArgs=args||arguments;if(appendArgs===true){callArgs=Array.prototype.slice.call(arguments,0);callArgs=callArgs.concat(args);}else if(Ext.isNumber(appendArgs)){callArgs=Array.prototype.slice.call(arguments,0);var applyArgs=[appendArgs,0].concat(args);Array.prototype.splice.apply(callArgs,applyArgs);} return method.apply(obj||window,callArgs);};},defer:function(millis,obj,args,appendArgs){var fn=this.createDelegate(obj,args,appendArgs);if(millis>0){return setTimeout(fn,millis);} fn();return 0;}});Ext.applyIf(String,{format:function(format){var args=Ext.toArray(arguments,1);return format.replace(/\{(\d+)\}/g,function(m,i){return args[i];});}});
+
+ var picStore=new Ext.data.ArrayStore({
+ storeId: 'picStore',
+ fields:['imgUrl','thumbUrl','thumbImg','img','current']
+ });
+ var Templates = {};
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
+ resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
-function create_alternate_gallery() {
- var picStore=new Ext.data.ArrayStore({
- storeId: 'picStore',
- fields:['imgUrl','thumbUrl','thumbImg','img']
- });
+ function resize_thumbs() {
+ Ext.each(Ext.query('img'),function () {
+ var s = this.src.search(/\/images\/mini\//);
+ if( s != -1 ) {
+ var newImage = new Image();
+ newImage.src=this.src.replace(/images\/mini\//, "images/thumb/");
+ Ext.get(this).replaceWith(newImage);
+ }
+ });
+ }
+
+ function collect_Images() {
+ Ext.each(Ext.query('a[href*=image.php?id=] img'),function(){
+ var Img=new Image();
+ Img.src=this.src.replace(/thumb/,"full" );
+ var element={thumbUrl:this.src,imgUrl:this.src.replace(/thumb/,"full" ),thumbImg:this,img:Img};
+ picStore.addSorted( new picStore.recordType(element) );
+ });
+ }
+
+ function initTemplates() {
+ Templates.thumbTemplate = new Ext.XTemplate(
+ '<tpl for=".">',
+ '<div class="thumb-wrap" style="padding:3px;border:1px solid #888;border-width:1px 0 0 0" >',
+ '<div class="thumb" style="padding-bottom:3px"><img src="{thumbUrl}"></div>',
+ '</div>',
+ '</tpl>'
+ );
+ Templates.thumbTemplate.compile();
+
+ Templates.detailsTemplate = new Ext.XTemplate(
+ '<tpl for=".">',
+ '<img style="max-width:{maxW}px; max-height:{maxH}px;" src="{imgUrl}">',
+ '</tpl>'
+ );
+ Templates.detailsTemplate.compile();
+ }
+
+ function create_alternate_gallery() {
+ collect_Images();
+ initTemplates();
+ var storeView = new Ext.grid.GridPanel({
+ region: 'center',
+ store: picStore,
+ title: 'debug',
+ colModel:new Ext.grid.ColumnModel({
+ defaults: {
+ width: 120,
+ sortable: true
+ },
+ columns: [
+ {header:'URL',width:100,dataIndex:'imgUrl'},
+ {header:'thumbURL',width:100,dataIndex:'thumbUrl',hidden:true},
+ {header:'thumb',width:100,dataIndex:'thumbImg',hidden:true},
+ {header:'img',width:100,dataIndex:'img',hidden:true},
+ {header:'current',width:100,dataIndex:'current'}
+ ]
+ })
+ });
+ var thumbView=new Ext.DataView({
+ region:'center',
+ tpl: Templates.thumbTemplate,
+ singleSelect: true,
+ overClass:'x-view-over',
+ itemSelector: 'div.thumb-wrap',
+ emptyText : '<div style="padding:10px;">No images match the specified filter</div>',
+ store: picStore,
+ listeners: {
+ 'mouseenter':{fn:function(dv,index){
+ if(showDetailTimer) {
+ clearTimeout(showDetailTimer);
+ }
+
+ showDetailTimer=showDetail.defer(200,this,[index]);}},
+ 'beforeselect' : {fn:function(view){
+ return thumbView.store.getRange().length > 0;
+ }}
+ }
+ });
+
+ function showDetail(index){
+ var bigPic=Ext.getCmp('big-pic');
+ var record;
+ currentIndex=picStore.findExact('current',true);
+ if(currentIndex != -1) {
+ record=picStore.getAt(currentIndex);
+ record.set('current',false);
+ }
+ record=picStore.getAt(index);
+ record.set('current',true);
+ picStore.commitChanges();
+ data=record.data;
+ data.maxW=Ext.getCmp('main-panel').getWidth();
+ data.maxH=Ext.getCmp('main-panel').getHeight();
+ bigPic.update(Templates.detailsTemplate.apply( data ));
+
+ }
+
var win = new Ext.Window({
width:800,
height:600,
+ border:false,
layout:'border',
- title:"picStore"
- });
- win.add(new Ext.grid.GridPanel({
- region: 'center',
- store: picStore,
- colModel:new Ext.grid.ColumnModel({
+ title:'Lightroom',
+ maximizable:true,
defaults: {
- width: 120,
- sortable: true
+ collapsible: true,
+ split: true,
+ collapseMode: 'mini',
+ collapsed:true
+
},
- columns: [
- {header:'URL',width:100,dataIndex:'imgUrl'},
- {header:'thumbURL',width:100,dataIndex:'thumbUrl'},
- {header:'thumb',width:100,dataIndex:'thumbImg'}
+ items: [
+ {
+ title: 'North',
+ region: 'north',
+ html: 'North',
+ id:'north-panel',
+ margins: '5 5 0 5',
+ height: 70
+ },{
+ title: 'South',
+ region: 'south',
+ html: 'South',
+ collapseMode: 'mini',
+ margins: '0 5 5 5',
+ height: 70,
+ id:'south-panel'
+ },{
+ region: 'west',
+ html: 'West',
+ margins: '0 0 0 5',
+ width: 500,
+ id:'west-panel',
+ layout:'border',
+ items:[ {xtype:'tabpanel',region:'center',items:[{title:'favs'}, storeView ]} ]
+ },{
+ title: 'East',
+ region: 'east',
+ html: 'East',
+ margins: '0 5 0 0',
+ width: 250,
+ id:'east-panel',
+ collapsed:false,
+ layout:'border',
+
+ items:[ {
+ region: 'center',
+ autoScroll: true,
+ items: thumbView },
+ {region:'south', height:20,id:'pager-panel',collapsible:false}]
+ },{
+ region: 'center',
+ collapsible: false,
+ collapsed:false,
+ id:'main-panel',
+ layout:'fit',
+ items: [{id:'big-pic'}]
+ }
+
]
- })
-
-
- }));
+ });
win.show();
-
-Ext.each(Ext.query('a[href*=image.php?id=] img'),function(){
- var element={imgUrl:this.src,thumbUrl:this.src.replace(/thumb/,"full" ),thumbImg:this}
- picStore.addSorted( new picStore.recordType(element) );
-});
-};
-
+ win.maximize();
+ showDetail.defer(250,this,[0]);
+ Ext.getCmp('pager-panel').body.appendChild(Ext.DomQuery.selectNode('div[id=gallery]').firstElementChild); // server paging
+};
}})(unsafeWindow);
|
monkeyoperator/greasemonkey-scripts
|
0dad7223b7aac96175bc1154f41686848d04cda3
|
inital extjs version
|
diff --git a/imagefap_lightroom.user.js b/imagefap_lightroom.user.js
new file mode 100644
index 0000000..d6d5587
--- /dev/null
+++ b/imagefap_lightroom.user.js
@@ -0,0 +1,98 @@
+// ==UserScript==
+// @name ImageFap Lightroom
+// @description Show content from Imagefap.com
+// @include *imagefap.com/*
+// @unwrap
+// ==/UserScript==
+
+(function(window) {
+ function loadScript(url) {
+ var script = document.createElement('script');
+ script.type = 'text/javascript';
+ script.charset = 'utf-8';
+ script.src = url;
+
+ document.getElementsByTagName('head')[0].appendChild(script);
+ }
+ function loadCss( url ) {
+ var link = document.createElement('link');
+ link.type = 'text/css';
+ link.rel = 'stylesheet';
+ link.href = url;
+ document.getElementsByTagName('head')[0].appendChild(link);
+
+ }
+
+ loadScript('http://extjs.cachefly.net/ext-3.2.0/adapter/ext/ext-base-debug.js');
+ loadScript('http://extjs.cachefly.net/ext-3.2.0/ext-all-debug.js');
+ loadCss('http://extjs.cachefly.net/ext-3.2.0/resources/css/ext-all.css');
+ extjs_wait();
+ function extjs_wait() {
+ if( typeof window.Ext == 'undefined' || typeof window.Ext.Window == 'undefined') {
+ window.setTimeout( extjs_wait,100 );
+ } else {
+ var dummy = new Array();
+ dummy.push('foo');
+ window.Ext.each(dummy,main,window.Ext);
+ }
+ }
+
+var main = function() {
+ var Ext=this;
+
+ var randompage=window.location.href.match(/\/random\.php/);
+ var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
+ if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
+ if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
+ else gallerypage = false;
+ var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
+ var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
+ if( clubspage )
+ clubspage=clubspage[1];
+
+ if( gallerypage || randompage )
+ create_alternate_gallery();
+
+function create_alternate_gallery() {
+
+ var picStore=new Ext.data.ArrayStore({
+ storeId: 'picStore',
+ fields:['imgUrl','thumbUrl','thumbImg','img']
+ });
+
+ var win = new Ext.Window({
+ width:800,
+ height:600,
+ layout:'border',
+ title:"picStore"
+ });
+ win.add(new Ext.grid.GridPanel({
+ region: 'center',
+ store: picStore,
+ colModel:new Ext.grid.ColumnModel({
+ defaults: {
+ width: 120,
+ sortable: true
+ },
+ columns: [
+ {header:'URL',width:100,dataIndex:'imgUrl'},
+ {header:'thumbURL',width:100,dataIndex:'thumbUrl'},
+ {header:'thumb',width:100,dataIndex:'thumbImg'}
+ ]
+ })
+
+
+ }));
+ win.show();
+
+Ext.each(Ext.query('a[href*=image.php?id=] img'),function(){
+ var element={imgUrl:this.src,thumbUrl:this.src.replace(/thumb/,"full" ),thumbImg:this}
+ picStore.addSorted( new picStore.recordType(element) );
+});
+};
+
+
+
+
+}})(unsafeWindow);
+
|
monkeyoperator/greasemonkey-scripts
|
1c37495e5d2399f20cffcdd77b5c9cc86fab47ed
|
Switched to EXTjs
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index cddf59e..ecf32aa 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,378 +1,385 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js
-// @require http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js
-// @require http://layout.jquery-dev.net/download/jquery.layout.min.js
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
var jqLayout; // jQuery Layout-Object
- var pageTracker;
+ var Ext;
+ var debugging = true;
var threadTimeout = 3000;
var numThreads = 6;
var chunksize=100;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var debugging=false;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
insertCSS();
- main();
+// insertExtJs();
+ main()
+ function add_script_link(url) {
+ var script = document.createElement("script");
+ script.type = "text/javascript";
+ script.src = url;
+ document.getElementsByTagName('head')[0].appendChild(script);
+ }
+
+ function insertExtJs( ) {
+
+ // Add javascripts and stylesheets
+ add_script_link('http://extjs.cachefly.net/ext-3.2.0/adapter/ext/ext-base-debug.js');
+ add_script_link('http://extjs.cachefly.net/ext-3.2.0/ext-all-debug.js');
+ wait();
+ }
+ function wait() {
+ if (typeof(unsafeWindow.Ext) == 'undefined' || typeof(unsafeWindow.Ext.Template) == 'undefined') {
+ window.setTimeout(wait, 100);
+ } else {
+ Ext = unsafeWindow.Ext;
+ main();
+ }
+ }
function main() {
- log('payload started');
- resize_thumbs();
+
+ resize_thumbs();
relative_dates();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.unbind('click')
.click(function(){
window.open(this.src);
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function relative_dates() {
dateTimeReg=/([0-9]{2}:[0-9]{2}:[0-9]{2})|([0-9]{4}-[0-9]{2}-[0-9]{2})/;
dateELs = $('center,span,td').filter(function(){
return $(this).children().length==0 && dateTimeReg.test(this.textContent || this.innerText || $(this).text() || "");
});
dateELs.each(function(){
var $this=$(this);
var $thisText = $.trim($this.text());
var values;
var postdate = new Date();
var has_time = $thisText.indexOf(':') !== -1;
var has_date = $thisText.indexOf('-') !== -1;
var date_values = $thisText.split('-');
var time_values = $thisText.split(':');
if( has_date && has_time ) {
values = $thisText.split(" ");
date_values = values[0].split('-');
time_values = values[1].split(':');
}
if( has_date ) {
postdate.setFullYear( date_values[0] );
postdate.setMonth( date_values[1] - 1 );
postdate.setDate( date_values[2] );
}
if ( has_time ){
postdate.setHours( time_values[0] );
postdate.setMinutes( time_values[1]);
postdate.setSeconds( time_values[2] );
}
var relative_to = new Date();
var delta = parseInt((relative_to.getTime() - postdate.getTime() ) / 1000 );
// delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = delta + 'seconds ago';
} else if(delta < (60 * 60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else if(delta < (31 * 86400)) {
r = (parseInt(delta / 86400)).toString() + ' days ago';
} else {
r = '' + (parseInt(delta / (86400 * 30))).toString() + ' months ago';
}
$this.html( r );
$this.attr('title',$thisText);
});
}
function save_clubvisit( clubid ) {
log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
$('<div id="south-pane" class="ui-layout-south"></div>').appendTo('body');
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
$(':contains(next)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-e')
.replaceWith('').appendTo(serverPaging);
$(':contains(prev)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-w')
.replaceWith('').prependTo(serverPaging);
$('.fg-button').hover(function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); });
$('span',serverPaging).addClass('fg-left');
profileLinks = $('#menubar').appendTo('body').append(favlink);
profileLinks.addClass('ui-layout-north');
serverPaging.appendTo('#south-pane');
$('<div id="pagingtype">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').appendTo('#south-pane');
}
thumbholder = $('<div class="ui-layout-east" id="east-pane"></div>')
.appendTo($('body'));
piccontainer = $('<div class="ui-layout-center" id="center-pane"></div>').appendTo($('body'));
jqLayout=initLayout();
setInterval(function() {
saveOpts={
east:{size: jqLayout.state.east.size}
};
GM_setObject('layout',saveOpts);
}, 1000);
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
$(this).addClass('thumb thumb_initial');
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div id="infodiv"></div>')
.appendTo('#south-pane')
.progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
loadfunction = function( event, timeout ) {
log( timeout );
try{
if( $(this).data('prev') && !timeout ) {
$(this).data('prev').pic.parent().addClass('thumb_done').removeClass('thumb_loading');
}
$(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
var next=preload.shift();
next.pic.parent().addClass('thumb_loading').removeClass('thumb_initial');
var newthread = $(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
setTimeout( function() {
newthread.trigger('load',[true]);
},threadTimeout);
} else {
// infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},500);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < numThreads; i++ ) {
setTimeout(function(){
var thread=img.clone(true).trigger('load');
setTimeout(function(){
thread.trigger('load',[true]);
},threadTimeout);
},i*100);
}
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ log(e); }
}
}
function enhance_myclubs() {
log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
console.log( clubid+' lastvisit: '+lastvisit);
console.log( clubid+' lastmod: '+lastmod);
$(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function initLayout() {
layoutSettings = {
north: {
initClosed: true
},
south:{
size: "30"
},
center:{ },
east:{
size: "150"
}
};
savedLayout=GM_getObject('layout',{});
$.extend( layoutSettings, savedLayout);
return $('body').layout( layoutSettings );
}
function log( something ) {
if( debugging )
console.log( something );
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
function insertCSS() {
- $('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
+ $('head').append('<link href="http://extjs.cachefly.net/ext-3.2.0/resources/css/ext-all.css" rel="stylesheet" type="text/css">');
$('head').append('<style id="GM_fapCSS" type="text/css">'+
- '.fg-button,.fg-left {float:left;} '+
- '.fg-left .link3, .fg-left b { margin:0 -1px};'+
- '.clear { clear: both; height:0; line-height:0}'+
- '.ui-layout-pane {'+
- ' background: #FFF;'+
- ' border: 0px solid #BBB; }'+
- '.ui-layout-pane-east{ overflow-y: scroll }'+
- '.ui-layout-resizer { background: #DDD; }'+
- '.ui-layout-toggler { background: #AAA; }'+
- '#south-pane { padding: 5px; font-family: "Arial narrow"}'+
- '#infodiv { float: right;color:#aaa;background:#fff;width:300px;height:10px;}'+
- '#pagingtype { float: right;margin-left: 20px;}'+
- '.thumb { display: block; float: left; border: 1px solid #eee;}'+
- '.thumb img { border: 3px solid #fff; display:inline; opacity:0; '+
- ' maxWidth:120px; maxHeight:120px }'+
'.thumb_initial { background: transparent url(data:image/gif;base64,'+
'R0lGODlhEAAQAPEAAP///wAAADY2NgAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdp'+
'dGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvkA7U64qGb2C6gtyXmeJ'+
'HIl+WYeuY7SSLozV6WvK9pfqWv8IKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvhY7DYhY'+
'5bV62xl9XvZJFCiGaReS1Xa5ICyP2jnS+M7drPgIKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLISP'+
'acLtvk6TE4jF6L3WZsyFlcd1pEZhKBixYOie8FiJ39nS97f39gNUCBEFACH5BAkKAAAALAAAAAAQ'+
'ABAAAAIshI9pwu2+xGmTrSqjBZlqfnnc1onmh44RxoIp5JpWN2b1Vdvn/ZbPb1MIAQUAIfkECQoA'+
'AAAsAAAAABAAEAAAAi2Ej2nC7b7YaVPEamPOgOqtYd3SSeFYmul0rlcpnpyXgu4K0t6mq/wD5CiG'+
'gAIAIfkECQoAAAAsAAAAABAAEAAAAiyEj2nC7b7akSuKyXDE11ZvdWLmiQB1kiOZdifYailHvzBk'+
'o5Kpq+HzUAgRBQA7AAAAAAAAAAAA) no-repeat center center; }'+
'.thumb_loading { background: transparent url(data:image/gif;base64,'+
'R0lGODlhEAAQAPQAAP///wAAAPj4+Dg4OISEhAYGBiYmJtbW1qioqBYWFnZ2dmZmZuTk5JiYmMbGxkhISFZWVgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05F'+
'VFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFUCAgjmRpnqUwFGwhKoRgqq2YFMaRGjWA8AbZiIBbjQQ8AmmFUJEQhQGJhaKOrCksgEla'+
'+KIkYvC6SJKQOISoNSYdeIk1ayA8ExTyeR3F749CACH5BAkKAAAALAAAAAAQABAAAAVoICCKR9KMaCoaxeCoqEAkRX3AwMHWxQIIjJSAZWgUEgzBwCBAEQpMwIDwY1FHgwJCtOW2UDWYIDyqNVVkUbYr'+
'6CK+o2eUMKgWrqKhj0FrEM8jQQALPFA3MAc8CQSAMA5ZBjgqDQmHIyEAIfkECQoAAAAsAAAAABAAEAAABWAgII4j85Ao2hRIKgrEUBQJLaSHMe8zgQo6Q8sxS7RIhILhBkgumCTZsXkACBC+0cwF2GoL'+
'LoFXREDcDlkAojBICRaFLDCOQtQKjmsQSubtDFU/NXcDBHwkaw1cKQ8MiyEAIfkECQoAAAAsAAAAABAAEAAABVIgII5kaZ6AIJQCMRTFQKiDQx4GrBfGa4uCnAEhQuRgPwCBtwK+kCNFgjh6QlFYgGO7'+
'baJ2CxIioSDpwqNggWCGDVVGphly3BkOpXDrKfNm/4AhACH5BAkKAAAALAAAAAAQABAAAAVgICCOZGmeqEAMRTEQwskYbV0Yx7kYSIzQhtgoBxCKBDQCIOcoLBimRiFhSABYU5gIgW01pLUBYkRItAYA'+
'qrlhYiwKjiWAcDMWY8QjsCf4DewiBzQ2N1AmKlgvgCiMjSQhACH5BAkKAAAALAAAAAAQABAAAAVfICCOZGmeqEgUxUAIpkA0AMKyxkEiSZEIsJqhYAg+boUFSTAkiBiNHks3sg1ILAfBiS10gyqCg0Ua'+
'FBCkwy3RYKiIYMAC+RAxiQgYsJdAjw5DN2gILzEEZgVcKYuMJiEAOwAAAAAAAAAAAA==) no-repeat center center; }'+
'.thumb_loading img { opacity:0.5; }'+
'.thumb_done { background: transparent}'+
'.thumb_done img { opacity:1; }'+
'</style>');
}
|
monkeyoperator/greasemonkey-scripts
|
2e3dbb6ed0e93a56d6dc4dc7e9606902704acc59
|
Eclipse files added to gitignore
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..541e887
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+/.project
+/.settings
|
monkeyoperator/greasemonkey-scripts
|
64379d1e48974a047bb44940a8bceb33a4a82d79
|
Timeout for picture preloading to avoid hangs
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index 0055e6f..cddf59e 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,369 +1,378 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js
// @require http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js
// @require http://layout.jquery-dev.net/download/jquery.layout.min.js
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
var jqLayout; // jQuery Layout-Object
- var $;
var pageTracker;
- var threads=6;
+ var threadTimeout = 3000;
+ var numThreads = 6;
var chunksize=100;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var debugging=false;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
insertCSS();
main();
function main() {
log('payload started');
resize_thumbs();
relative_dates();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
+ .unbind('click')
.click(function(){
- $(this).css({position:'absolute'}).attr('showing',0);
- piccontainer.hide();
+ window.open(this.src);
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function relative_dates() {
- dateTimeReg=/(([0-9]{2}):([0-9]{2}):([0-9]{2}))|(([0-9]{4})-([0-9]{2})-([0-9]{2}))/;
- dateELs = $('center,span').filter(function(){
- return $(this).children().length==0 && dateTimeReg.test(this.textContent || this.innerText || jQuery(this).text() || "");
+ dateTimeReg=/([0-9]{2}:[0-9]{2}:[0-9]{2})|([0-9]{4}-[0-9]{2}-[0-9]{2})/;
+ dateELs = $('center,span,td').filter(function(){
+ return $(this).children().length==0 && dateTimeReg.test(this.textContent || this.innerText || $(this).text() || "");
});
dateELs.each(function(){
var $this=$(this);
var $thisText = $.trim($this.text());
var values;
var postdate = new Date();
var has_time = $thisText.indexOf(':') !== -1;
var has_date = $thisText.indexOf('-') !== -1;
var date_values = $thisText.split('-');
var time_values = $thisText.split(':');
if( has_date && has_time ) {
values = $thisText.split(" ");
date_values = values[0].split('-');
time_values = values[1].split(':');
}
if( has_date ) {
postdate.setFullYear( date_values[0] );
postdate.setMonth( date_values[1] - 1 );
postdate.setDate( date_values[2] );
}
if ( has_time ){
postdate.setHours( time_values[0] );
postdate.setMinutes( time_values[1]);
postdate.setSeconds( time_values[2] );
}
var relative_to = new Date();
var delta = parseInt((relative_to.getTime() - postdate.getTime() ) / 1000 );
// delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = delta + 'seconds ago';
} else if(delta < (60 * 60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else if(delta < (31 * 86400)) {
r = (parseInt(delta / 86400)).toString() + ' days ago';
} else {
r = '' + (parseInt(delta / (86400 * 30))).toString() + ' months ago';
}
$this.html( r );
$this.attr('title',$thisText);
});
}
function save_clubvisit( clubid ) {
log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
$('<div id="south-pane" class="ui-layout-south"></div>').appendTo('body');
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
$(':contains(next)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-e')
.replaceWith('').appendTo(serverPaging);
$(':contains(prev)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-w')
.replaceWith('').prependTo(serverPaging);
$('.fg-button').hover(function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); });
$('span',serverPaging).addClass('fg-left');
profileLinks = $('#menubar').appendTo('body').append(favlink);
profileLinks.addClass('ui-layout-north');
serverPaging.appendTo('#south-pane');
$('<div id="pagingtype">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').appendTo('#south-pane');
}
thumbholder = $('<div class="ui-layout-east" id="east-pane"></div>')
.appendTo($('body'));
piccontainer = $('<div class="ui-layout-center" id="center-pane"></div>').appendTo($('body'));
jqLayout=initLayout();
setInterval(function() {
saveOpts={
east:{size: jqLayout.state.east.size}
};
GM_setObject('layout',saveOpts);
}, 1000);
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
$(this).addClass('thumb thumb_initial');
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div id="infodiv"></div>')
.appendTo('#south-pane')
.progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
- loadfunction = function() {
+ loadfunction = function( event, timeout ) {
+ log( timeout );
try{
- if( $(this).data('prev') ) {
+ if( $(this).data('prev') && !timeout ) {
$(this).data('prev').pic.parent().addClass('thumb_done').removeClass('thumb_loading');
}
$(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
var next=preload.shift();
next.pic.parent().addClass('thumb_loading').removeClass('thumb_initial');
- $(this).clone(true).appendTo(piccontainer)
+ var newthread = $(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
+ setTimeout( function() {
+ newthread.trigger('load',[true]);
+ },threadTimeout);
} else {
// infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},500);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
- for( var i=0; i < threads; i++ )
- setTimeout(function(){img.clone(true).trigger('load');},i*200);
-
+ for( var i=0; i < numThreads; i++ ) {
+ setTimeout(function(){
+ var thread=img.clone(true).trigger('load');
+ setTimeout(function(){
+ thread.trigger('load',[true]);
+ },threadTimeout);
+ },i*100);
+ }
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ log(e); }
}
}
function enhance_myclubs() {
log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
console.log( clubid+' lastvisit: '+lastvisit);
console.log( clubid+' lastmod: '+lastmod);
$(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function initLayout() {
layoutSettings = {
north: {
initClosed: true
},
south:{
size: "30"
},
center:{ },
east:{
size: "150"
}
};
savedLayout=GM_getObject('layout',{});
$.extend( layoutSettings, savedLayout);
return $('body').layout( layoutSettings );
}
function log( something ) {
if( debugging )
console.log( something );
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
function insertCSS() {
$('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
$('head').append('<style id="GM_fapCSS" type="text/css">'+
'.fg-button,.fg-left {float:left;} '+
'.fg-left .link3, .fg-left b { margin:0 -1px};'+
'.clear { clear: both; height:0; line-height:0}'+
'.ui-layout-pane {'+
' background: #FFF;'+
' border: 0px solid #BBB; }'+
'.ui-layout-pane-east{ overflow-y: scroll }'+
'.ui-layout-resizer { background: #DDD; }'+
'.ui-layout-toggler { background: #AAA; }'+
'#south-pane { padding: 5px; font-family: "Arial narrow"}'+
'#infodiv { float: right;color:#aaa;background:#fff;width:300px;height:10px;}'+
'#pagingtype { float: right;margin-left: 20px;}'+
'.thumb { display: block; float: left; border: 1px solid #eee;}'+
'.thumb img { border: 3px solid #fff; display:inline; opacity:0; '+
' maxWidth:120px; maxHeight:120px }'+
'.thumb_initial { background: transparent url(data:image/gif;base64,'+
'R0lGODlhEAAQAPEAAP///wAAADY2NgAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdp'+
'dGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvkA7U64qGb2C6gtyXmeJ'+
'HIl+WYeuY7SSLozV6WvK9pfqWv8IKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvhY7DYhY'+
'5bV62xl9XvZJFCiGaReS1Xa5ICyP2jnS+M7drPgIKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLISP'+
'acLtvk6TE4jF6L3WZsyFlcd1pEZhKBixYOie8FiJ39nS97f39gNUCBEFACH5BAkKAAAALAAAAAAQ'+
'ABAAAAIshI9pwu2+xGmTrSqjBZlqfnnc1onmh44RxoIp5JpWN2b1Vdvn/ZbPb1MIAQUAIfkECQoA'+
'AAAsAAAAABAAEAAAAi2Ej2nC7b7YaVPEamPOgOqtYd3SSeFYmul0rlcpnpyXgu4K0t6mq/wD5CiG'+
'gAIAIfkECQoAAAAsAAAAABAAEAAAAiyEj2nC7b7akSuKyXDE11ZvdWLmiQB1kiOZdifYailHvzBk'+
'o5Kpq+HzUAgRBQA7AAAAAAAAAAAA) no-repeat center center; }'+
'.thumb_loading { background: transparent url(data:image/gif;base64,'+
'R0lGODlhEAAQAPQAAP///wAAAPj4+Dg4OISEhAYGBiYmJtbW1qioqBYWFnZ2dmZmZuTk5JiYmMbGxkhISFZWVgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05F'+
'VFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFUCAgjmRpnqUwFGwhKoRgqq2YFMaRGjWA8AbZiIBbjQQ8AmmFUJEQhQGJhaKOrCksgEla'+
'+KIkYvC6SJKQOISoNSYdeIk1ayA8ExTyeR3F749CACH5BAkKAAAALAAAAAAQABAAAAVoICCKR9KMaCoaxeCoqEAkRX3AwMHWxQIIjJSAZWgUEgzBwCBAEQpMwIDwY1FHgwJCtOW2UDWYIDyqNVVkUbYr'+
'6CK+o2eUMKgWrqKhj0FrEM8jQQALPFA3MAc8CQSAMA5ZBjgqDQmHIyEAIfkECQoAAAAsAAAAABAAEAAABWAgII4j85Ao2hRIKgrEUBQJLaSHMe8zgQo6Q8sxS7RIhILhBkgumCTZsXkACBC+0cwF2GoL'+
'LoFXREDcDlkAojBICRaFLDCOQtQKjmsQSubtDFU/NXcDBHwkaw1cKQ8MiyEAIfkECQoAAAAsAAAAABAAEAAABVIgII5kaZ6AIJQCMRTFQKiDQx4GrBfGa4uCnAEhQuRgPwCBtwK+kCNFgjh6QlFYgGO7'+
'baJ2CxIioSDpwqNggWCGDVVGphly3BkOpXDrKfNm/4AhACH5BAkKAAAALAAAAAAQABAAAAVgICCOZGmeqEAMRTEQwskYbV0Yx7kYSIzQhtgoBxCKBDQCIOcoLBimRiFhSABYU5gIgW01pLUBYkRItAYA'+
'qrlhYiwKjiWAcDMWY8QjsCf4DewiBzQ2N1AmKlgvgCiMjSQhACH5BAkKAAAALAAAAAAQABAAAAVfICCOZGmeqEgUxUAIpkA0AMKyxkEiSZEIsJqhYAg+boUFSTAkiBiNHks3sg1ILAfBiS10gyqCg0Ua'+
'FBCkwy3RYKiIYMAC+RAxiQgYsJdAjw5DN2gILzEEZgVcKYuMJiEAOwAAAAAAAAAAAA==) no-repeat center center; }'+
'.thumb_loading img { opacity:0.5; }'+
'.thumb_done { background: transparent}'+
'.thumb_done img { opacity:1; }'+
'</style>');
}
|
monkeyoperator/greasemonkey-scripts
|
b8eb12e1a347df1756d986386f1c684ffd263511
|
@require für externe js-dateien removed Google-analytics
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index 5c303f7..0055e6f 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,399 +1,369 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
+// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js
+// @require http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js
+// @require http://layout.jquery-dev.net/download/jquery.layout.min.js
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
var jqLayout; // jQuery Layout-Object
var $;
var pageTracker;
var threads=6;
var chunksize=100;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var debugging=false;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
- insertJS();
-// Check if jQuery and evil Tracking code loaded
- function GM_wait() {
- if(typeof unsafeWindow.jQuery == 'undefined') log("waiting for jQuery");
- else {
- $ = $ || unsafeWindow.jQuery.noConflict();
- if(typeof unsafeWindow.jQuery.ui == 'undefined') log("waiting for jQuery-UI");
- if(typeof $.fn.layout == 'undefined') log("waiting for jQuery-Layout");
- }
+ insertCSS();
+ main();
- if(typeof unsafeWindow._gat == 'undefined') log("waiting for google-analytics");
- else { pageTracker = unsafeWindow._gat._getTracker("UA-7978064-1"); }
- if( $ && unsafeWindow.jQuery.ui && $.fn.layout && pageTracker ) {
- insertCSS();
- pageTracker._trackPageview();
- window.setTimeout(payload,10);
- }
- else window.setTimeout(GM_wait,100);
+ function main() {
+ log('payload started');
+ resize_thumbs();
+ relative_dates();
+ if( gallerypage || randompage )
+ create_alternate_gallery();
+ if( myclubspage )
+ enhance_myclubs();
+ if( clubspage )
+ save_clubvisit( clubspage );
}
- GM_wait();
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.click(function(){
$(this).css({position:'absolute'}).attr('showing',0);
piccontainer.hide();
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
-
-
- function payload() {
- log('payload started');
- resize_thumbs();
- relative_dates();
- if( gallerypage || randompage )
- create_alternate_gallery();
- if( myclubspage )
- enhance_myclubs();
- if( clubspage )
- save_clubvisit( clubspage );
- }
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function relative_dates() {
dateTimeReg=/(([0-9]{2}):([0-9]{2}):([0-9]{2}))|(([0-9]{4})-([0-9]{2})-([0-9]{2}))/;
dateELs = $('center,span').filter(function(){
return $(this).children().length==0 && dateTimeReg.test(this.textContent || this.innerText || jQuery(this).text() || "");
});
dateELs.each(function(){
var $this=$(this);
var $thisText = $.trim($this.text());
var values;
var postdate = new Date();
var has_time = $thisText.indexOf(':') !== -1;
var has_date = $thisText.indexOf('-') !== -1;
var date_values = $thisText.split('-');
var time_values = $thisText.split(':');
if( has_date && has_time ) {
values = $thisText.split(" ");
date_values = values[0].split('-');
time_values = values[1].split(':');
}
if( has_date ) {
postdate.setFullYear( date_values[0] );
postdate.setMonth( date_values[1] - 1 );
postdate.setDate( date_values[2] );
}
if ( has_time ){
postdate.setHours( time_values[0] );
postdate.setMinutes( time_values[1]);
postdate.setSeconds( time_values[2] );
}
var relative_to = new Date();
var delta = parseInt((relative_to.getTime() - postdate.getTime() ) / 1000 );
// delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = delta + 'seconds ago';
} else if(delta < (60 * 60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else if(delta < (31 * 86400)) {
r = (parseInt(delta / 86400)).toString() + ' days ago';
} else {
r = '' + (parseInt(delta / (86400 * 30))).toString() + ' months ago';
}
$this.html( r );
$this.attr('title',$thisText);
});
}
function save_clubvisit( clubid ) {
log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
$('<div id="south-pane" class="ui-layout-south"></div>').appendTo('body');
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
$(':contains(next)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-e')
.replaceWith('').appendTo(serverPaging);
$(':contains(prev)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-w')
.replaceWith('').prependTo(serverPaging);
$('.fg-button').hover(function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); });
$('span',serverPaging).addClass('fg-left');
profileLinks = $('#menubar').appendTo('body').append(favlink);
profileLinks.addClass('ui-layout-north');
serverPaging.appendTo('#south-pane');
$('<div id="pagingtype">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').appendTo('#south-pane');
}
thumbholder = $('<div class="ui-layout-east" id="east-pane"></div>')
.appendTo($('body'));
piccontainer = $('<div class="ui-layout-center" id="center-pane"></div>').appendTo($('body'));
jqLayout=initLayout();
setInterval(function() {
saveOpts={
east:{size: jqLayout.state.east.size}
};
GM_setObject('layout',saveOpts);
}, 1000);
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
$(this).addClass('thumb thumb_initial');
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div id="infodiv"></div>')
.appendTo('#south-pane')
.progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
$(this).data('prev').pic.parent().addClass('thumb_done').removeClass('thumb_loading');
}
$(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
var next=preload.shift();
next.pic.parent().addClass('thumb_loading').removeClass('thumb_initial');
$(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
} else {
// infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},500);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ log(e); }
}
}
function enhance_myclubs() {
log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
console.log( clubid+' lastvisit: '+lastvisit);
console.log( clubid+' lastmod: '+lastmod);
$(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function initLayout() {
layoutSettings = {
north: {
initClosed: true
},
south:{
size: "30"
},
center:{ },
east:{
size: "150"
}
};
savedLayout=GM_getObject('layout',{});
$.extend( layoutSettings, savedLayout);
return $('body').layout( layoutSettings );
}
function log( something ) {
if( debugging )
console.log( something );
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
-function insertJS() {
- _insertJS('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js');
- _insertJS('http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js');
- _insertJS('http://www.google-analytics.com/ga.js');
- _insertJS('http://layout.jquery-dev.net/download/jquery.layout.min.js');
-}
-
-function _insertJS( url ) {
- EL = document.createElement('script');
- EL.src = url;
- EL.type = 'text/javascript';
- document.getElementsByTagName('head')[0].appendChild(EL);
-}
-
function insertCSS() {
$('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
$('head').append('<style id="GM_fapCSS" type="text/css">'+
'.fg-button,.fg-left {float:left;} '+
'.fg-left .link3, .fg-left b { margin:0 -1px};'+
'.clear { clear: both; height:0; line-height:0}'+
'.ui-layout-pane {'+
' background: #FFF;'+
' border: 0px solid #BBB; }'+
'.ui-layout-pane-east{ overflow-y: scroll }'+
'.ui-layout-resizer { background: #DDD; }'+
'.ui-layout-toggler { background: #AAA; }'+
'#south-pane { padding: 5px; font-family: "Arial narrow"}'+
'#infodiv { float: right;color:#aaa;background:#fff;width:300px;height:10px;}'+
'#pagingtype { float: right;margin-left: 20px;}'+
'.thumb { display: block; float: left; border: 1px solid #eee;}'+
'.thumb img { border: 3px solid #fff; display:inline; opacity:0; '+
' maxWidth:120px; maxHeight:120px }'+
'.thumb_initial { background: transparent url(data:image/gif;base64,'+
'R0lGODlhEAAQAPEAAP///wAAADY2NgAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdp'+
'dGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvkA7U64qGb2C6gtyXmeJ'+
'HIl+WYeuY7SSLozV6WvK9pfqWv8IKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvhY7DYhY'+
'5bV62xl9XvZJFCiGaReS1Xa5ICyP2jnS+M7drPgIKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLISP'+
'acLtvk6TE4jF6L3WZsyFlcd1pEZhKBixYOie8FiJ39nS97f39gNUCBEFACH5BAkKAAAALAAAAAAQ'+
'ABAAAAIshI9pwu2+xGmTrSqjBZlqfnnc1onmh44RxoIp5JpWN2b1Vdvn/ZbPb1MIAQUAIfkECQoA'+
'AAAsAAAAABAAEAAAAi2Ej2nC7b7YaVPEamPOgOqtYd3SSeFYmul0rlcpnpyXgu4K0t6mq/wD5CiG'+
'gAIAIfkECQoAAAAsAAAAABAAEAAAAiyEj2nC7b7akSuKyXDE11ZvdWLmiQB1kiOZdifYailHvzBk'+
'o5Kpq+HzUAgRBQA7AAAAAAAAAAAA) no-repeat center center; }'+
'.thumb_loading { background: transparent url(data:image/gif;base64,'+
'R0lGODlhEAAQAPQAAP///wAAAPj4+Dg4OISEhAYGBiYmJtbW1qioqBYWFnZ2dmZmZuTk5JiYmMbGxkhISFZWVgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05F'+
'VFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFUCAgjmRpnqUwFGwhKoRgqq2YFMaRGjWA8AbZiIBbjQQ8AmmFUJEQhQGJhaKOrCksgEla'+
'+KIkYvC6SJKQOISoNSYdeIk1ayA8ExTyeR3F749CACH5BAkKAAAALAAAAAAQABAAAAVoICCKR9KMaCoaxeCoqEAkRX3AwMHWxQIIjJSAZWgUEgzBwCBAEQpMwIDwY1FHgwJCtOW2UDWYIDyqNVVkUbYr'+
'6CK+o2eUMKgWrqKhj0FrEM8jQQALPFA3MAc8CQSAMA5ZBjgqDQmHIyEAIfkECQoAAAAsAAAAABAAEAAABWAgII4j85Ao2hRIKgrEUBQJLaSHMe8zgQo6Q8sxS7RIhILhBkgumCTZsXkACBC+0cwF2GoL'+
'LoFXREDcDlkAojBICRaFLDCOQtQKjmsQSubtDFU/NXcDBHwkaw1cKQ8MiyEAIfkECQoAAAAsAAAAABAAEAAABVIgII5kaZ6AIJQCMRTFQKiDQx4GrBfGa4uCnAEhQuRgPwCBtwK+kCNFgjh6QlFYgGO7'+
'baJ2CxIioSDpwqNggWCGDVVGphly3BkOpXDrKfNm/4AhACH5BAkKAAAALAAAAAAQABAAAAVgICCOZGmeqEAMRTEQwskYbV0Yx7kYSIzQhtgoBxCKBDQCIOcoLBimRiFhSABYU5gIgW01pLUBYkRItAYA'+
'qrlhYiwKjiWAcDMWY8QjsCf4DewiBzQ2N1AmKlgvgCiMjSQhACH5BAkKAAAALAAAAAAQABAAAAVfICCOZGmeqEgUxUAIpkA0AMKyxkEiSZEIsJqhYAg+boUFSTAkiBiNHks3sg1ILAfBiS10gyqCg0Ua'+
'FBCkwy3RYKiIYMAC+RAxiQgYsJdAjw5DN2gILzEEZgVcKYuMJiEAOwAAAAAAAAAAAA==) no-repeat center center; }'+
'.thumb_loading img { opacity:0.5; }'+
'.thumb_done { background: transparent}'+
'.thumb_done img { opacity:1; }'+
'</style>');
}
|
monkeyoperator/greasemonkey-scripts
|
5703e701ea535788938aae36a20195f458e1448b
|
grafiken hinzugefügt
|
diff --git a/data/16-7.gif b/data/16-7.gif
new file mode 100644
index 0000000..40e3890
Binary files /dev/null and b/data/16-7.gif differ
diff --git a/data/4-1.gif b/data/4-1.gif
new file mode 100644
index 0000000..e192ca8
Binary files /dev/null and b/data/4-1.gif differ
|
monkeyoperator/greasemonkey-scripts
|
b49c50905fa3737b5f63e21313781a96618ff0ba
|
relative Zeitangaben auch auf clubseiten
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index a8b13cb..5c303f7 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,390 +1,399 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
var jqLayout; // jQuery Layout-Object
var $;
var pageTracker;
var threads=6;
var chunksize=100;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var debugging=false;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
insertJS();
// Check if jQuery and evil Tracking code loaded
function GM_wait() {
if(typeof unsafeWindow.jQuery == 'undefined') log("waiting for jQuery");
else {
$ = $ || unsafeWindow.jQuery.noConflict();
if(typeof unsafeWindow.jQuery.ui == 'undefined') log("waiting for jQuery-UI");
if(typeof $.fn.layout == 'undefined') log("waiting for jQuery-Layout");
}
if(typeof unsafeWindow._gat == 'undefined') log("waiting for google-analytics");
else { pageTracker = unsafeWindow._gat._getTracker("UA-7978064-1"); }
if( $ && unsafeWindow.jQuery.ui && $.fn.layout && pageTracker ) {
insertCSS();
pageTracker._trackPageview();
window.setTimeout(payload,10);
}
else window.setTimeout(GM_wait,100);
}
GM_wait();
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.click(function(){
$(this).css({position:'absolute'}).attr('showing',0);
piccontainer.hide();
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function payload() {
log('payload started');
resize_thumbs();
relative_dates();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function relative_dates() {
dateTimeReg=/(([0-9]{2}):([0-9]{2}):([0-9]{2}))|(([0-9]{4})-([0-9]{2})-([0-9]{2}))/;
- dateELs = $('center').filter(function(){
+ dateELs = $('center,span').filter(function(){
return $(this).children().length==0 && dateTimeReg.test(this.textContent || this.innerText || jQuery(this).text() || "");
});
dateELs.each(function(){
var $this=$(this);
var $thisText = $.trim($this.text());
var values;
var postdate = new Date();
- if( $thisText.indexOf(':') !== -1 ) {
- values = $thisText.split(":");
- postdate.setHours( values[0] );
- postdate.setMinutes( values[1]);
- postdate.setSeconds( values[2] );
- } else {
- values = $thisText.split('-');
- postdate.setFullYear( values[0] );
- postdate.setMonth( values[1] - 1 );
- postdate.setDate( values[2] );
+ var has_time = $thisText.indexOf(':') !== -1;
+ var has_date = $thisText.indexOf('-') !== -1;
+ var date_values = $thisText.split('-');
+ var time_values = $thisText.split(':');
+ if( has_date && has_time ) {
+ values = $thisText.split(" ");
+ date_values = values[0].split('-');
+ time_values = values[1].split(':');
}
+ if( has_date ) {
+ postdate.setFullYear( date_values[0] );
+ postdate.setMonth( date_values[1] - 1 );
+ postdate.setDate( date_values[2] );
+ }
+ if ( has_time ){
+ postdate.setHours( time_values[0] );
+ postdate.setMinutes( time_values[1]);
+ postdate.setSeconds( time_values[2] );
+ }
+
var relative_to = new Date();
var delta = parseInt((relative_to.getTime() - postdate.getTime() ) / 1000 );
// delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = delta + 'seconds ago';
} else if(delta < (60 * 60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
- } else if(delta < (14 * 86400)) {
+ } else if(delta < (31 * 86400)) {
r = (parseInt(delta / 86400)).toString() + ' days ago';
} else {
r = '' + (parseInt(delta / (86400 * 30))).toString() + ' months ago';
}
$this.html( r );
$this.attr('title',$thisText);
});
}
function save_clubvisit( clubid ) {
log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
$('<div id="south-pane" class="ui-layout-south"></div>').appendTo('body');
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
$(':contains(next)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-e')
.replaceWith('').appendTo(serverPaging);
$(':contains(prev)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-w')
.replaceWith('').prependTo(serverPaging);
$('.fg-button').hover(function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); });
$('span',serverPaging).addClass('fg-left');
profileLinks = $('#menubar').appendTo('body').append(favlink);
profileLinks.addClass('ui-layout-north');
serverPaging.appendTo('#south-pane');
$('<div id="pagingtype">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').appendTo('#south-pane');
}
thumbholder = $('<div class="ui-layout-east" id="east-pane"></div>')
.appendTo($('body'));
piccontainer = $('<div class="ui-layout-center" id="center-pane"></div>').appendTo($('body'));
jqLayout=initLayout();
setInterval(function() {
saveOpts={
east:{size: jqLayout.state.east.size}
};
GM_setObject('layout',saveOpts);
}, 1000);
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
$(this).addClass('thumb thumb_initial');
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div id="infodiv"></div>')
.appendTo('#south-pane')
.progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
$(this).data('prev').pic.parent().addClass('thumb_done').removeClass('thumb_loading');
}
$(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
var next=preload.shift();
next.pic.parent().addClass('thumb_loading').removeClass('thumb_initial');
$(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
} else {
// infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},500);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ log(e); }
}
}
function enhance_myclubs() {
log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
console.log( clubid+' lastvisit: '+lastvisit);
console.log( clubid+' lastmod: '+lastmod);
$(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function initLayout() {
layoutSettings = {
north: {
initClosed: true
},
south:{
size: "30"
},
center:{ },
east:{
size: "150"
}
};
savedLayout=GM_getObject('layout',{});
$.extend( layoutSettings, savedLayout);
return $('body').layout( layoutSettings );
}
function log( something ) {
if( debugging )
console.log( something );
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
function insertJS() {
_insertJS('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js');
_insertJS('http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js');
_insertJS('http://www.google-analytics.com/ga.js');
_insertJS('http://layout.jquery-dev.net/download/jquery.layout.min.js');
}
function _insertJS( url ) {
EL = document.createElement('script');
EL.src = url;
EL.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(EL);
}
function insertCSS() {
$('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
$('head').append('<style id="GM_fapCSS" type="text/css">'+
'.fg-button,.fg-left {float:left;} '+
'.fg-left .link3, .fg-left b { margin:0 -1px};'+
'.clear { clear: both; height:0; line-height:0}'+
'.ui-layout-pane {'+
' background: #FFF;'+
' border: 0px solid #BBB; }'+
'.ui-layout-pane-east{ overflow-y: scroll }'+
'.ui-layout-resizer { background: #DDD; }'+
'.ui-layout-toggler { background: #AAA; }'+
'#south-pane { padding: 5px; font-family: "Arial narrow"}'+
'#infodiv { float: right;color:#aaa;background:#fff;width:300px;height:10px;}'+
'#pagingtype { float: right;margin-left: 20px;}'+
'.thumb { display: block; float: left; border: 1px solid #eee;}'+
'.thumb img { border: 3px solid #fff; display:inline; opacity:0; '+
' maxWidth:120px; maxHeight:120px }'+
'.thumb_initial { background: transparent url(data:image/gif;base64,'+
'R0lGODlhEAAQAPEAAP///wAAADY2NgAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdp'+
'dGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvkA7U64qGb2C6gtyXmeJ'+
'HIl+WYeuY7SSLozV6WvK9pfqWv8IKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvhY7DYhY'+
'5bV62xl9XvZJFCiGaReS1Xa5ICyP2jnS+M7drPgIKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLISP'+
'acLtvk6TE4jF6L3WZsyFlcd1pEZhKBixYOie8FiJ39nS97f39gNUCBEFACH5BAkKAAAALAAAAAAQ'+
'ABAAAAIshI9pwu2+xGmTrSqjBZlqfnnc1onmh44RxoIp5JpWN2b1Vdvn/ZbPb1MIAQUAIfkECQoA'+
'AAAsAAAAABAAEAAAAi2Ej2nC7b7YaVPEamPOgOqtYd3SSeFYmul0rlcpnpyXgu4K0t6mq/wD5CiG'+
'gAIAIfkECQoAAAAsAAAAABAAEAAAAiyEj2nC7b7akSuKyXDE11ZvdWLmiQB1kiOZdifYailHvzBk'+
'o5Kpq+HzUAgRBQA7AAAAAAAAAAAA) no-repeat center center; }'+
'.thumb_loading { background: transparent url(data:image/gif;base64,'+
'R0lGODlhEAAQAPQAAP///wAAAPj4+Dg4OISEhAYGBiYmJtbW1qioqBYWFnZ2dmZmZuTk5JiYmMbGxkhISFZWVgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05F'+
'VFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFUCAgjmRpnqUwFGwhKoRgqq2YFMaRGjWA8AbZiIBbjQQ8AmmFUJEQhQGJhaKOrCksgEla'+
'+KIkYvC6SJKQOISoNSYdeIk1ayA8ExTyeR3F749CACH5BAkKAAAALAAAAAAQABAAAAVoICCKR9KMaCoaxeCoqEAkRX3AwMHWxQIIjJSAZWgUEgzBwCBAEQpMwIDwY1FHgwJCtOW2UDWYIDyqNVVkUbYr'+
'6CK+o2eUMKgWrqKhj0FrEM8jQQALPFA3MAc8CQSAMA5ZBjgqDQmHIyEAIfkECQoAAAAsAAAAABAAEAAABWAgII4j85Ao2hRIKgrEUBQJLaSHMe8zgQo6Q8sxS7RIhILhBkgumCTZsXkACBC+0cwF2GoL'+
'LoFXREDcDlkAojBICRaFLDCOQtQKjmsQSubtDFU/NXcDBHwkaw1cKQ8MiyEAIfkECQoAAAAsAAAAABAAEAAABVIgII5kaZ6AIJQCMRTFQKiDQx4GrBfGa4uCnAEhQuRgPwCBtwK+kCNFgjh6QlFYgGO7'+
'baJ2CxIioSDpwqNggWCGDVVGphly3BkOpXDrKfNm/4AhACH5BAkKAAAALAAAAAAQABAAAAVgICCOZGmeqEAMRTEQwskYbV0Yx7kYSIzQhtgoBxCKBDQCIOcoLBimRiFhSABYU5gIgW01pLUBYkRItAYA'+
'qrlhYiwKjiWAcDMWY8QjsCf4DewiBzQ2N1AmKlgvgCiMjSQhACH5BAkKAAAALAAAAAAQABAAAAVfICCOZGmeqEgUxUAIpkA0AMKyxkEiSZEIsJqhYAg+boUFSTAkiBiNHks3sg1ILAfBiS10gyqCg0Ua'+
'FBCkwy3RYKiIYMAC+RAxiQgYsJdAjw5DN2gILzEEZgVcKYuMJiEAOwAAAAAAAAAAAA==) no-repeat center center; }'+
'.thumb_loading img { opacity:0.5; }'+
'.thumb_done { background: transparent}'+
'.thumb_done img { opacity:1; }'+
'</style>');
}
|
monkeyoperator/greasemonkey-scripts
|
3026c539a40be75a5bac64a53380c75b7178464c
|
relative gallery-times (entweder date oder time)
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index a5cebba..a8b13cb 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,345 +1,390 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
var jqLayout; // jQuery Layout-Object
var $;
var pageTracker;
var threads=6;
var chunksize=100;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var debugging=false;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
insertJS();
// Check if jQuery and evil Tracking code loaded
function GM_wait() {
if(typeof unsafeWindow.jQuery == 'undefined') log("waiting for jQuery");
else {
$ = $ || unsafeWindow.jQuery.noConflict();
if(typeof unsafeWindow.jQuery.ui == 'undefined') log("waiting for jQuery-UI");
if(typeof $.fn.layout == 'undefined') log("waiting for jQuery-Layout");
}
if(typeof unsafeWindow._gat == 'undefined') log("waiting for google-analytics");
else { pageTracker = unsafeWindow._gat._getTracker("UA-7978064-1"); }
if( $ && unsafeWindow.jQuery.ui && $.fn.layout && pageTracker ) {
insertCSS();
pageTracker._trackPageview();
window.setTimeout(payload,10);
}
else window.setTimeout(GM_wait,100);
}
GM_wait();
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.click(function(){
$(this).css({position:'absolute'}).attr('showing',0);
piccontainer.hide();
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function payload() {
log('payload started');
resize_thumbs();
+ relative_dates();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
+ function relative_dates() {
+ dateTimeReg=/(([0-9]{2}):([0-9]{2}):([0-9]{2}))|(([0-9]{4})-([0-9]{2})-([0-9]{2}))/;
+ dateELs = $('center').filter(function(){
+ return $(this).children().length==0 && dateTimeReg.test(this.textContent || this.innerText || jQuery(this).text() || "");
+ });
+
+ dateELs.each(function(){
+ var $this=$(this);
+ var $thisText = $.trim($this.text());
+ var values;
+ var postdate = new Date();
+ if( $thisText.indexOf(':') !== -1 ) {
+ values = $thisText.split(":");
+ postdate.setHours( values[0] );
+ postdate.setMinutes( values[1]);
+ postdate.setSeconds( values[2] );
+ } else {
+ values = $thisText.split('-');
+ postdate.setFullYear( values[0] );
+ postdate.setMonth( values[1] - 1 );
+ postdate.setDate( values[2] );
+ }
+ var relative_to = new Date();
+ var delta = parseInt((relative_to.getTime() - postdate.getTime() ) / 1000 );
+// delta = delta + (relative_to.getTimezoneOffset() * 60);
+
+ var r = '';
+ if (delta < 60) {
+ r = delta + 'seconds ago';
+ } else if(delta < (60 * 60)) {
+ r = (parseInt(delta / 60)).toString() + ' minutes ago';
+ } else if(delta < (24*60*60)) {
+ r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
+ } else if(delta < (48*60*60)) {
+ r = '1 day ago';
+ } else if(delta < (14 * 86400)) {
+ r = (parseInt(delta / 86400)).toString() + ' days ago';
+ } else {
+ r = '' + (parseInt(delta / (86400 * 30))).toString() + ' months ago';
+ }
+ $this.html( r );
+ $this.attr('title',$thisText);
+ });
+ }
function save_clubvisit( clubid ) {
log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
$('<div id="south-pane" class="ui-layout-south"></div>').appendTo('body');
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
$(':contains(next)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-e')
.replaceWith('').appendTo(serverPaging);
$(':contains(prev)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-w')
.replaceWith('').prependTo(serverPaging);
$('.fg-button').hover(function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); });
$('span',serverPaging).addClass('fg-left');
profileLinks = $('#menubar').appendTo('body').append(favlink);
profileLinks.addClass('ui-layout-north');
serverPaging.appendTo('#south-pane');
$('<div id="pagingtype">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').appendTo('#south-pane');
}
thumbholder = $('<div class="ui-layout-east" id="east-pane"></div>')
.appendTo($('body'));
piccontainer = $('<div class="ui-layout-center" id="center-pane"></div>').appendTo($('body'));
jqLayout=initLayout();
setInterval(function() {
saveOpts={
east:{size: jqLayout.state.east.size}
};
GM_setObject('layout',saveOpts);
}, 1000);
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
$(this).addClass('thumb thumb_initial');
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div id="infodiv"></div>')
.appendTo('#south-pane')
.progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
$(this).data('prev').pic.parent().addClass('thumb_done').removeClass('thumb_loading');
}
$(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
var next=preload.shift();
next.pic.parent().addClass('thumb_loading').removeClass('thumb_initial');
$(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
} else {
// infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},500);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ log(e); }
}
}
function enhance_myclubs() {
log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
console.log( clubid+' lastvisit: '+lastvisit);
console.log( clubid+' lastmod: '+lastmod);
$(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function initLayout() {
layoutSettings = {
north: {
initClosed: true
},
south:{
size: "30"
},
center:{ },
east:{
size: "150"
}
};
savedLayout=GM_getObject('layout',{});
$.extend( layoutSettings, savedLayout);
return $('body').layout( layoutSettings );
}
function log( something ) {
if( debugging )
console.log( something );
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
function insertJS() {
_insertJS('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js');
_insertJS('http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js');
_insertJS('http://www.google-analytics.com/ga.js');
_insertJS('http://layout.jquery-dev.net/download/jquery.layout.min.js');
}
function _insertJS( url ) {
EL = document.createElement('script');
EL.src = url;
EL.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(EL);
}
function insertCSS() {
$('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
$('head').append('<style id="GM_fapCSS" type="text/css">'+
'.fg-button,.fg-left {float:left;} '+
- '.fg-left .link3, .fg-left b { margin:0 -6px};'+
+ '.fg-left .link3, .fg-left b { margin:0 -1px};'+
'.clear { clear: both; height:0; line-height:0}'+
'.ui-layout-pane {'+
' background: #FFF;'+
' border: 0px solid #BBB; }'+
'.ui-layout-pane-east{ overflow-y: scroll }'+
'.ui-layout-resizer { background: #DDD; }'+
'.ui-layout-toggler { background: #AAA; }'+
'#south-pane { padding: 5px; font-family: "Arial narrow"}'+
'#infodiv { float: right;color:#aaa;background:#fff;width:300px;height:10px;}'+
'#pagingtype { float: right;margin-left: 20px;}'+
'.thumb { display: block; float: left; border: 1px solid #eee;}'+
'.thumb img { border: 3px solid #fff; display:inline; opacity:0; '+
' maxWidth:120px; maxHeight:120px }'+
'.thumb_initial { background: transparent url(data:image/gif;base64,'+
'R0lGODlhEAAQAPEAAP///wAAADY2NgAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdp'+
'dGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvkA7U64qGb2C6gtyXmeJ'+
'HIl+WYeuY7SSLozV6WvK9pfqWv8IKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvhY7DYhY'+
'5bV62xl9XvZJFCiGaReS1Xa5ICyP2jnS+M7drPgIKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLISP'+
'acLtvk6TE4jF6L3WZsyFlcd1pEZhKBixYOie8FiJ39nS97f39gNUCBEFACH5BAkKAAAALAAAAAAQ'+
'ABAAAAIshI9pwu2+xGmTrSqjBZlqfnnc1onmh44RxoIp5JpWN2b1Vdvn/ZbPb1MIAQUAIfkECQoA'+
'AAAsAAAAABAAEAAAAi2Ej2nC7b7YaVPEamPOgOqtYd3SSeFYmul0rlcpnpyXgu4K0t6mq/wD5CiG'+
'gAIAIfkECQoAAAAsAAAAABAAEAAAAiyEj2nC7b7akSuKyXDE11ZvdWLmiQB1kiOZdifYailHvzBk'+
'o5Kpq+HzUAgRBQA7AAAAAAAAAAAA) no-repeat center center; }'+
'.thumb_loading { background: transparent url(data:image/gif;base64,'+
'R0lGODlhEAAQAPQAAP///wAAAPj4+Dg4OISEhAYGBiYmJtbW1qioqBYWFnZ2dmZmZuTk5JiYmMbGxkhISFZWVgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05F'+
'VFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFUCAgjmRpnqUwFGwhKoRgqq2YFMaRGjWA8AbZiIBbjQQ8AmmFUJEQhQGJhaKOrCksgEla'+
'+KIkYvC6SJKQOISoNSYdeIk1ayA8ExTyeR3F749CACH5BAkKAAAALAAAAAAQABAAAAVoICCKR9KMaCoaxeCoqEAkRX3AwMHWxQIIjJSAZWgUEgzBwCBAEQpMwIDwY1FHgwJCtOW2UDWYIDyqNVVkUbYr'+
'6CK+o2eUMKgWrqKhj0FrEM8jQQALPFA3MAc8CQSAMA5ZBjgqDQmHIyEAIfkECQoAAAAsAAAAABAAEAAABWAgII4j85Ao2hRIKgrEUBQJLaSHMe8zgQo6Q8sxS7RIhILhBkgumCTZsXkACBC+0cwF2GoL'+
'LoFXREDcDlkAojBICRaFLDCOQtQKjmsQSubtDFU/NXcDBHwkaw1cKQ8MiyEAIfkECQoAAAAsAAAAABAAEAAABVIgII5kaZ6AIJQCMRTFQKiDQx4GrBfGa4uCnAEhQuRgPwCBtwK+kCNFgjh6QlFYgGO7'+
'baJ2CxIioSDpwqNggWCGDVVGphly3BkOpXDrKfNm/4AhACH5BAkKAAAALAAAAAAQABAAAAVgICCOZGmeqEAMRTEQwskYbV0Yx7kYSIzQhtgoBxCKBDQCIOcoLBimRiFhSABYU5gIgW01pLUBYkRItAYA'+
'qrlhYiwKjiWAcDMWY8QjsCf4DewiBzQ2N1AmKlgvgCiMjSQhACH5BAkKAAAALAAAAAAQABAAAAVfICCOZGmeqEgUxUAIpkA0AMKyxkEiSZEIsJqhYAg+boUFSTAkiBiNHks3sg1ILAfBiS10gyqCg0Ua'+
'FBCkwy3RYKiIYMAC+RAxiQgYsJdAjw5DN2gILzEEZgVcKYuMJiEAOwAAAAAAAAAAAA==) no-repeat center center; }'+
'.thumb_loading img { opacity:0.5; }'+
'.thumb_done { background: transparent}'+
'.thumb_done img { opacity:1; }'+
'</style>');
}
|
monkeyoperator/greasemonkey-scripts
|
141093f9acb25cae5e307a620f9d5739d5ae924c
|
Styling enhancements
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index 0725e8a..a5cebba 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,320 +1,345 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
var jqLayout; // jQuery Layout-Object
var $;
var pageTracker;
- var threads=8;
+ var threads=6;
var chunksize=100;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var debugging=false;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
insertJS();
// Check if jQuery and evil Tracking code loaded
function GM_wait() {
if(typeof unsafeWindow.jQuery == 'undefined') log("waiting for jQuery");
else {
$ = $ || unsafeWindow.jQuery.noConflict();
if(typeof unsafeWindow.jQuery.ui == 'undefined') log("waiting for jQuery-UI");
if(typeof $.fn.layout == 'undefined') log("waiting for jQuery-Layout");
}
if(typeof unsafeWindow._gat == 'undefined') log("waiting for google-analytics");
else { pageTracker = unsafeWindow._gat._getTracker("UA-7978064-1"); }
if( $ && unsafeWindow.jQuery.ui && $.fn.layout && pageTracker ) {
insertCSS();
pageTracker._trackPageview();
window.setTimeout(payload,10);
}
else window.setTimeout(GM_wait,100);
}
GM_wait();
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.click(function(){
$(this).css({position:'absolute'}).attr('showing',0);
piccontainer.hide();
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function payload() {
log('payload started');
resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function save_clubvisit( clubid ) {
log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
$('<div id="south-pane" class="ui-layout-south"></div>').appendTo('body');
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
$(':contains(next)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-e')
.replaceWith('').appendTo(serverPaging);
$(':contains(prev)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-w')
.replaceWith('').prependTo(serverPaging);
$('.fg-button').hover(function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); });
$('span',serverPaging).addClass('fg-left');
profileLinks = $('#menubar').appendTo('body').append(favlink);
profileLinks.addClass('ui-layout-north');
serverPaging.appendTo('#south-pane');
$('<div id="pagingtype">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').appendTo('#south-pane');
}
thumbholder = $('<div class="ui-layout-east" id="east-pane"></div>')
.appendTo($('body'));
piccontainer = $('<div class="ui-layout-center" id="center-pane"></div>').appendTo($('body'));
jqLayout=initLayout();
setInterval(function() {
saveOpts={
east:{size: jqLayout.state.east.size}
};
GM_setObject('layout',saveOpts);
}, 1000);
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
+ $(this).addClass('thumb thumb_initial');
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
- pic.css({maxWidth:'120px',maxHeight:'120px',display:'none'});
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div id="infodiv"></div>')
.appendTo('#south-pane')
.progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
- $(this).data('prev').pic.css({opacity:'1'});
+ $(this).data('prev').pic.parent().addClass('thumb_done').removeClass('thumb_loading');
}
$(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
var next=preload.shift();
- next.pic.css({opacity:'0.5',border:'3px solid #fff',display:'inline'});
+ next.pic.parent().addClass('thumb_loading').removeClass('thumb_initial');
$(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
} else {
// infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},500);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ log(e); }
}
}
function enhance_myclubs() {
log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
console.log( clubid+' lastvisit: '+lastvisit);
console.log( clubid+' lastmod: '+lastmod);
$(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function initLayout() {
layoutSettings = {
north: {
initClosed: true
},
south:{
size: "30"
},
center:{ },
east:{
size: "150"
}
};
savedLayout=GM_getObject('layout',{});
$.extend( layoutSettings, savedLayout);
return $('body').layout( layoutSettings );
}
function log( something ) {
if( debugging )
console.log( something );
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
function insertJS() {
_insertJS('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js');
_insertJS('http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js');
_insertJS('http://www.google-analytics.com/ga.js');
_insertJS('http://layout.jquery-dev.net/download/jquery.layout.min.js');
}
function _insertJS( url ) {
EL = document.createElement('script');
EL.src = url;
EL.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(EL);
}
function insertCSS() {
$('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
$('head').append('<style id="GM_fapCSS" type="text/css">'+
'.fg-button,.fg-left {float:left;} '+
'.fg-left .link3, .fg-left b { margin:0 -6px};'+
'.clear { clear: both; height:0; line-height:0}'+
'.ui-layout-pane {'+
' background: #FFF;'+
' border: 0px solid #BBB; }'+
'.ui-layout-pane-east{ overflow-y: scroll }'+
'.ui-layout-resizer { background: #DDD; }'+
'.ui-layout-toggler { background: #AAA; }'+
'#south-pane { padding: 5px; font-family: "Arial narrow"}'+
'#infodiv { float: right;color:#aaa;background:#fff;width:300px;height:10px;}'+
'#pagingtype { float: right;margin-left: 20px;}'+
+ '.thumb { display: block; float: left; border: 1px solid #eee;}'+
+ '.thumb img { border: 3px solid #fff; display:inline; opacity:0; '+
+ ' maxWidth:120px; maxHeight:120px }'+
+ '.thumb_initial { background: transparent url(data:image/gif;base64,'+
+ 'R0lGODlhEAAQAPEAAP///wAAADY2NgAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdp'+
+ 'dGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvkA7U64qGb2C6gtyXmeJ'+
+ 'HIl+WYeuY7SSLozV6WvK9pfqWv8IKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLYSPacLtvhY7DYhY'+
+ '5bV62xl9XvZJFCiGaReS1Xa5ICyP2jnS+M7drPgIKoaIAgAh+QQJCgAAACwAAAAAEAAQAAACLISP'+
+ 'acLtvk6TE4jF6L3WZsyFlcd1pEZhKBixYOie8FiJ39nS97f39gNUCBEFACH5BAkKAAAALAAAAAAQ'+
+ 'ABAAAAIshI9pwu2+xGmTrSqjBZlqfnnc1onmh44RxoIp5JpWN2b1Vdvn/ZbPb1MIAQUAIfkECQoA'+
+ 'AAAsAAAAABAAEAAAAi2Ej2nC7b7YaVPEamPOgOqtYd3SSeFYmul0rlcpnpyXgu4K0t6mq/wD5CiG'+
+ 'gAIAIfkECQoAAAAsAAAAABAAEAAAAiyEj2nC7b7akSuKyXDE11ZvdWLmiQB1kiOZdifYailHvzBk'+
+ 'o5Kpq+HzUAgRBQA7AAAAAAAAAAAA) no-repeat center center; }'+
+ '.thumb_loading { background: transparent url(data:image/gif;base64,'+
+'R0lGODlhEAAQAPQAAP///wAAAPj4+Dg4OISEhAYGBiYmJtbW1qioqBYWFnZ2dmZmZuTk5JiYmMbGxkhISFZWVgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05F'+
+'VFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFUCAgjmRpnqUwFGwhKoRgqq2YFMaRGjWA8AbZiIBbjQQ8AmmFUJEQhQGJhaKOrCksgEla'+
+'+KIkYvC6SJKQOISoNSYdeIk1ayA8ExTyeR3F749CACH5BAkKAAAALAAAAAAQABAAAAVoICCKR9KMaCoaxeCoqEAkRX3AwMHWxQIIjJSAZWgUEgzBwCBAEQpMwIDwY1FHgwJCtOW2UDWYIDyqNVVkUbYr'+
+'6CK+o2eUMKgWrqKhj0FrEM8jQQALPFA3MAc8CQSAMA5ZBjgqDQmHIyEAIfkECQoAAAAsAAAAABAAEAAABWAgII4j85Ao2hRIKgrEUBQJLaSHMe8zgQo6Q8sxS7RIhILhBkgumCTZsXkACBC+0cwF2GoL'+
+'LoFXREDcDlkAojBICRaFLDCOQtQKjmsQSubtDFU/NXcDBHwkaw1cKQ8MiyEAIfkECQoAAAAsAAAAABAAEAAABVIgII5kaZ6AIJQCMRTFQKiDQx4GrBfGa4uCnAEhQuRgPwCBtwK+kCNFgjh6QlFYgGO7'+
+'baJ2CxIioSDpwqNggWCGDVVGphly3BkOpXDrKfNm/4AhACH5BAkKAAAALAAAAAAQABAAAAVgICCOZGmeqEAMRTEQwskYbV0Yx7kYSIzQhtgoBxCKBDQCIOcoLBimRiFhSABYU5gIgW01pLUBYkRItAYA'+
+'qrlhYiwKjiWAcDMWY8QjsCf4DewiBzQ2N1AmKlgvgCiMjSQhACH5BAkKAAAALAAAAAAQABAAAAVfICCOZGmeqEgUxUAIpkA0AMKyxkEiSZEIsJqhYAg+boUFSTAkiBiNHks3sg1ILAfBiS10gyqCg0Ua'+
+'FBCkwy3RYKiIYMAC+RAxiQgYsJdAjw5DN2gILzEEZgVcKYuMJiEAOwAAAAAAAAAAAA==) no-repeat center center; }'+
+ '.thumb_loading img { opacity:0.5; }'+
+ '.thumb_done { background: transparent}'+
+ '.thumb_done img { opacity:1; }'+
'</style>');
}
|
monkeyoperator/greasemonkey-scripts
|
c86d540ba589815cc117563ffd1bc305fda00438
|
infodiv und paging type in south pane verlegt
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index 8f6ab92..0725e8a 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,319 +1,320 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
var jqLayout; // jQuery Layout-Object
var $;
var pageTracker;
var threads=8;
var chunksize=100;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var debugging=false;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
insertJS();
// Check if jQuery and evil Tracking code loaded
function GM_wait() {
if(typeof unsafeWindow.jQuery == 'undefined') log("waiting for jQuery");
else {
$ = $ || unsafeWindow.jQuery.noConflict();
if(typeof unsafeWindow.jQuery.ui == 'undefined') log("waiting for jQuery-UI");
if(typeof $.fn.layout == 'undefined') log("waiting for jQuery-Layout");
}
if(typeof unsafeWindow._gat == 'undefined') log("waiting for google-analytics");
else { pageTracker = unsafeWindow._gat._getTracker("UA-7978064-1"); }
if( $ && unsafeWindow.jQuery.ui && $.fn.layout && pageTracker ) {
insertCSS();
pageTracker._trackPageview();
window.setTimeout(payload,10);
}
else window.setTimeout(GM_wait,100);
}
GM_wait();
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.click(function(){
$(this).css({position:'absolute'}).attr('showing',0);
piccontainer.hide();
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function payload() {
log('payload started');
resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function save_clubvisit( clubid ) {
log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
+ $('<div id="south-pane" class="ui-layout-south"></div>').appendTo('body');
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
$(':contains(next)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-e')
.replaceWith('').appendTo(serverPaging);
$(':contains(prev)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-w')
.replaceWith('').prependTo(serverPaging);
$('.fg-button').hover(function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); });
$('span',serverPaging).addClass('fg-left');
profileLinks = $('#menubar').appendTo('body').append(favlink);
profileLinks.addClass('ui-layout-north');
- serverPaging.addClass('ui-layout-south').appendTo('body');
- $('<div style="float:left;">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').prependTo('#menubar');
+ serverPaging.appendTo('#south-pane');
+ $('<div id="pagingtype">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').appendTo('#south-pane');
}
- thumbholder = $('<div class="ui-layout-east"></div>')
+ thumbholder = $('<div class="ui-layout-east" id="east-pane"></div>')
.appendTo($('body'));
- piccontainer = $('<div class="ui-layout-center"></div>').appendTo($('body'));
+ piccontainer = $('<div class="ui-layout-center" id="center-pane"></div>').appendTo($('body'));
jqLayout=initLayout();
setInterval(function() {
saveOpts={
east:{size: jqLayout.state.east.size}
};
GM_setObject('layout',saveOpts);
}, 1000);
- piccontainer.hide();
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
pic.css({maxWidth:'120px',maxHeight:'120px',display:'none'});
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
- infodiv=$('<div></div>')
- .appendTo('body')
- .css({position:'fixed',bottom:'30px',right:'200px',color:'#aaa',background:'#fff',margin:'5px',
- width:'300px',height:'10px',fontFamily:'arial narrow'})
+ infodiv=$('<div id="infodiv"></div>')
+ .appendTo('#south-pane')
.progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
$(this).data('prev').pic.css({opacity:'1'});
}
$(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
var next=preload.shift();
next.pic.css({opacity:'0.5',border:'3px solid #fff',display:'inline'});
$(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
} else {
// infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},500);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ log(e); }
}
}
function enhance_myclubs() {
log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
console.log( clubid+' lastvisit: '+lastvisit);
console.log( clubid+' lastmod: '+lastmod);
$(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function initLayout() {
layoutSettings = {
north: {
initClosed: true
},
south:{
- size: "auto"
+ size: "30"
},
center:{ },
east:{
size: "150"
}
};
savedLayout=GM_getObject('layout',{});
$.extend( layoutSettings, savedLayout);
return $('body').layout( layoutSettings );
}
function log( something ) {
if( debugging )
console.log( something );
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
function insertJS() {
_insertJS('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js');
_insertJS('http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js');
_insertJS('http://www.google-analytics.com/ga.js');
_insertJS('http://layout.jquery-dev.net/download/jquery.layout.min.js');
}
function _insertJS( url ) {
EL = document.createElement('script');
EL.src = url;
EL.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(EL);
}
function insertCSS() {
$('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
$('head').append('<style id="GM_fapCSS" type="text/css">'+
'.fg-button,.fg-left {float:left;} '+
'.fg-left .link3, .fg-left b { margin:0 -6px};'+
'.clear { clear: both; height:0; line-height:0}'+
'.ui-layout-pane {'+
' background: #FFF;'+
' border: 0px solid #BBB; }'+
'.ui-layout-pane-east{ overflow-y: scroll }'+
'.ui-layout-resizer { background: #DDD; }'+
'.ui-layout-toggler { background: #AAA; }'+
+ '#south-pane { padding: 5px; font-family: "Arial narrow"}'+
+ '#infodiv { float: right;color:#aaa;background:#fff;width:300px;height:10px;}'+
+ '#pagingtype { float: right;margin-left: 20px;}'+
'</style>');
}
|
monkeyoperator/greasemonkey-scripts
|
e2edd937a1595a0ea2adc35d4afbe545d174b4c1
|
Layout is now saved
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index c279d79..8f6ab92 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,304 +1,319 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
+ var jqLayout; // jQuery Layout-Object
var $;
var pageTracker;
var threads=8;
var chunksize=100;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
+ var debugging=false;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
- console.log(gallerypage);
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
insertJS();
// Check if jQuery and evil Tracking code loaded
function GM_wait() {
- if(typeof unsafeWindow.jQuery == 'undefined') console.log("waiting for jQuery");
+ if(typeof unsafeWindow.jQuery == 'undefined') log("waiting for jQuery");
else {
$ = $ || unsafeWindow.jQuery.noConflict();
- if(typeof unsafeWindow.jQuery.ui == 'undefined') console.log("waiting for jQuery-UI");
- if(typeof $.fn.layout == 'undefined') console.log("waiting for jQuery-Layout");
+ if(typeof unsafeWindow.jQuery.ui == 'undefined') log("waiting for jQuery-UI");
+ if(typeof $.fn.layout == 'undefined') log("waiting for jQuery-Layout");
}
- if(typeof unsafeWindow._gat == 'undefined') console.log("waiting for ga");
+ if(typeof unsafeWindow._gat == 'undefined') log("waiting for google-analytics");
else { pageTracker = unsafeWindow._gat._getTracker("UA-7978064-1"); }
if( $ && unsafeWindow.jQuery.ui && $.fn.layout && pageTracker ) {
insertCSS();
pageTracker._trackPageview();
window.setTimeout(payload,10);
}
else window.setTimeout(GM_wait,100);
}
GM_wait();
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.click(function(){
$(this).css({position:'absolute'}).attr('showing',0);
piccontainer.hide();
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function payload() {
- console.log('payload started');
+ log('payload started');
resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function save_clubvisit( clubid ) {
- GM_log('club '+clubid+' visited');
+ log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
$(':contains(next)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-e')
.replaceWith('').appendTo(serverPaging);
$(':contains(prev)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-w')
.replaceWith('').prependTo(serverPaging);
$('.fg-button').hover(function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); });
$('span',serverPaging).addClass('fg-left');
profileLinks = $('#menubar').appendTo('body').append(favlink);
profileLinks.addClass('ui-layout-north');
serverPaging.addClass('ui-layout-south').appendTo('body');
$('<div style="float:left;">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').prependTo('#menubar');
}
thumbholder = $('<div class="ui-layout-east"></div>')
.appendTo($('body'));
piccontainer = $('<div class="ui-layout-center"></div>').appendTo($('body'));
- $('body').layout({ north: {
- initClosed: true
-
- }
- ,south:{
- size: "auto"
- }
- ,center:{
-
- }
- ,east:{
- size: "150"
- }
-
- });
-
+ jqLayout=initLayout();
+ setInterval(function() {
+ saveOpts={
+ east:{size: jqLayout.state.east.size}
+ };
+ GM_setObject('layout',saveOpts);
+ }, 1000);
piccontainer.hide();
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
pic.css({maxWidth:'120px',maxHeight:'120px',display:'none'});
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div></div>')
.appendTo('body')
.css({position:'fixed',bottom:'30px',right:'200px',color:'#aaa',background:'#fff',margin:'5px',
width:'300px',height:'10px',fontFamily:'arial narrow'})
.progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
$(this).data('prev').pic.css({opacity:'1'});
}
$(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
var next=preload.shift();
next.pic.css({opacity:'0.5',border:'3px solid #fff',display:'inline'});
$(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
} else {
// infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},500);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
- } catch(e){ console.log(e); }
+ } catch(e){ log(e); }
}
}
function enhance_myclubs() {
- GM_log( 'i has myclubs' );
+ log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
- GM_log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
+ log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
-// console.log( clubid+' lastvisit: '+lastvisit);
-// console.log( clubid+' lastmod: '+lastmod);
-// $(this).parent().parent().next().append(lastmod.toLocaleString());
+ console.log( clubid+' lastvisit: '+lastvisit);
+ console.log( clubid+' lastmod: '+lastmod);
+ $(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
+function initLayout() {
+ layoutSettings = {
+ north: {
+ initClosed: true
+ },
+ south:{
+ size: "auto"
+ },
+ center:{ },
+ east:{
+ size: "150"
+ }
+ };
+ savedLayout=GM_getObject('layout',{});
+ $.extend( layoutSettings, savedLayout);
+
+ return $('body').layout( layoutSettings );
+}
+
+function log( something ) {
+ if( debugging )
+ console.log( something );
+}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
function insertJS() {
_insertJS('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js');
_insertJS('http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js');
_insertJS('http://www.google-analytics.com/ga.js');
_insertJS('http://layout.jquery-dev.net/download/jquery.layout.min.js');
}
function _insertJS( url ) {
EL = document.createElement('script');
EL.src = url;
EL.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(EL);
}
function insertCSS() {
$('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
$('head').append('<style id="GM_fapCSS" type="text/css">'+
'.fg-button,.fg-left {float:left;} '+
'.fg-left .link3, .fg-left b { margin:0 -6px};'+
'.clear { clear: both; height:0; line-height:0}'+
'.ui-layout-pane {'+
' background: #FFF;'+
' border: 0px solid #BBB; }'+
'.ui-layout-pane-east{ overflow-y: scroll }'+
'.ui-layout-resizer { background: #DDD; }'+
'.ui-layout-toggler { background: #AAA; }'+
'</style>');
}
|
monkeyoperator/greasemonkey-scripts
|
1d23f28461bbc0e98c67277f17451b4d62d229dd
|
auf jQuery.layout wird nun korrekt gewartet
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index 0917085..c279d79 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,303 +1,304 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
var $;
var pageTracker;
var threads=8;
var chunksize=100;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
console.log(gallerypage);
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
insertJS();
// Check if jQuery and evil Tracking code loaded
function GM_wait() {
if(typeof unsafeWindow.jQuery == 'undefined') console.log("waiting for jQuery");
else {
$ = $ || unsafeWindow.jQuery.noConflict();
if(typeof unsafeWindow.jQuery.ui == 'undefined') console.log("waiting for jQuery-UI");
+ if(typeof $.fn.layout == 'undefined') console.log("waiting for jQuery-Layout");
}
if(typeof unsafeWindow._gat == 'undefined') console.log("waiting for ga");
else { pageTracker = unsafeWindow._gat._getTracker("UA-7978064-1"); }
- if( $ && unsafeWindow.jQuery.ui && pageTracker ) {
+ if( $ && unsafeWindow.jQuery.ui && $.fn.layout && pageTracker ) {
insertCSS();
pageTracker._trackPageview();
window.setTimeout(payload,10);
}
else window.setTimeout(GM_wait,100);
}
GM_wait();
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.click(function(){
$(this).css({position:'absolute'}).attr('showing',0);
piccontainer.hide();
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function payload() {
console.log('payload started');
resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function save_clubvisit( clubid ) {
GM_log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
$(':contains(next)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-e')
.replaceWith('').appendTo(serverPaging);
$(':contains(prev)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-w')
.replaceWith('').prependTo(serverPaging);
$('.fg-button').hover(function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); });
$('span',serverPaging).addClass('fg-left');
profileLinks = $('#menubar').appendTo('body').append(favlink);
profileLinks.addClass('ui-layout-north');
serverPaging.addClass('ui-layout-south').appendTo('body');
$('<div style="float:left;">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').prependTo('#menubar');
}
thumbholder = $('<div class="ui-layout-east"></div>')
.appendTo($('body'));
piccontainer = $('<div class="ui-layout-center"></div>').appendTo($('body'));
$('body').layout({ north: {
initClosed: true
}
,south:{
size: "auto"
}
,center:{
}
,east:{
size: "150"
}
});
piccontainer.hide();
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
pic.css({maxWidth:'120px',maxHeight:'120px',display:'none'});
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div></div>')
.appendTo('body')
- .css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',margin:'5px',
+ .css({position:'fixed',bottom:'30px',right:'200px',color:'#aaa',background:'#fff',margin:'5px',
width:'300px',height:'10px',fontFamily:'arial narrow'})
.progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
$(this).data('prev').pic.css({opacity:'1'});
}
$(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
var next=preload.shift();
next.pic.css({opacity:'0.5',border:'3px solid #fff',display:'inline'});
$(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
} else {
// infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},500);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ console.log(e); }
}
}
function enhance_myclubs() {
GM_log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
GM_log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
// console.log( clubid+' lastvisit: '+lastvisit);
// console.log( clubid+' lastmod: '+lastmod);
// $(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
function insertJS() {
_insertJS('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js');
_insertJS('http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js');
_insertJS('http://www.google-analytics.com/ga.js');
_insertJS('http://layout.jquery-dev.net/download/jquery.layout.min.js');
}
function _insertJS( url ) {
EL = document.createElement('script');
EL.src = url;
EL.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(EL);
}
function insertCSS() {
$('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
$('head').append('<style id="GM_fapCSS" type="text/css">'+
'.fg-button,.fg-left {float:left;} '+
'.fg-left .link3, .fg-left b { margin:0 -6px};'+
'.clear { clear: both; height:0; line-height:0}'+
'.ui-layout-pane {'+
' background: #FFF;'+
' border: 0px solid #BBB; }'+
'.ui-layout-pane-east{ overflow-y: scroll }'+
'.ui-layout-resizer { background: #DDD; }'+
'.ui-layout-toggler { background: #AAA; }'+
'</style>');
}
|
monkeyoperator/greasemonkey-scripts
|
1b34d07ab7a4f97b6fee0d72032de85c0b09b5d1
|
using jQuery-Layout plugin now
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index 2538efd..0917085 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,285 +1,303 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
var $;
var pageTracker;
var threads=8;
var chunksize=100;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
console.log(gallerypage);
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
- // Add jQuery and jQuery-UI
- var GM_JQ = document.createElement('script');
- var GM_JQ_UI = document.createElement('script');
- GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js';
- GM_JQ.type = 'text/javascript';
- GM_JQ_UI.src = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js';
- GM_JQ_UI.type = 'text/javascript';
- // Add Google Analytics Tracking code
- var GM_GA = document.createElement('script');
- GM_GA.src = 'http://www.google-analytics.com/ga.js';
- GM_GA.type = 'text/javascript';
- document.getElementsByTagName('body')[0].appendChild(GM_JQ);
- document.getElementsByTagName('body')[0].appendChild(GM_JQ_UI);
- document.getElementsByTagName('body')[0].appendChild(GM_GA);
+ insertJS();
// Check if jQuery and evil Tracking code loaded
function GM_wait() {
if(typeof unsafeWindow.jQuery == 'undefined') console.log("waiting for jQuery");
else {
$ = $ || unsafeWindow.jQuery.noConflict();
if(typeof unsafeWindow.jQuery.ui == 'undefined') console.log("waiting for jQuery-UI");
}
if(typeof unsafeWindow._gat == 'undefined') console.log("waiting for ga");
else { pageTracker = unsafeWindow._gat._getTracker("UA-7978064-1"); }
if( $ && unsafeWindow.jQuery.ui && pageTracker ) {
insertCSS();
pageTracker._trackPageview();
window.setTimeout(payload,10);
}
else window.setTimeout(GM_wait,100);
}
GM_wait();
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.click(function(){
$(this).css({position:'absolute'}).attr('showing',0);
piccontainer.hide();
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function payload() {
console.log('payload started');
resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function save_clubvisit( clubid ) {
GM_log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
$(':contains(next)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-e')
.replaceWith('').appendTo(serverPaging);
$(':contains(prev)',serverPaging).eq(1)
.addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-w')
.replaceWith('').prependTo(serverPaging);
$('.fg-button').hover(function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); });
$('span',serverPaging).addClass('fg-left');
profileLinks = $('#menubar').appendTo('body').append(favlink);
- serverPaging.appendTo('#menubar').wrap('<div style="position: absolute;top:0;left:0;background:#fff"></div>');
+ profileLinks.addClass('ui-layout-north');
+ serverPaging.addClass('ui-layout-south').appendTo('body');
$('<div style="float:left;">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').prependTo('#menubar');
}
- thumbholder = $('<div style="position:static; float:right; width: 255px; height: 100%; overflow-x: hidden; overflow-y:scroll"></div>')
+ thumbholder = $('<div class="ui-layout-east"></div>')
.appendTo($('body'));
- thumbholder.css({marginTop:-($('#menubar').height()+2)});
- piccontainer = $('<div style="position:relative;;float:left;255px;height:100%;"></div>').appendTo($('body'));
+ piccontainer = $('<div class="ui-layout-center"></div>').appendTo($('body'));
+ $('body').layout({ north: {
+ initClosed: true
+
+ }
+ ,south:{
+ size: "auto"
+ }
+ ,center:{
+
+ }
+ ,east:{
+ size: "150"
+ }
+
+ });
+
piccontainer.hide();
- var w=$('#menubar').width();
- if( !w )
- w=$('body').width();
- piccontainer.css({width:w-255});
- piccontainer.css({marginTop:-($('#menubar').height()+2)});
- piccontainer.bind('DOMMouseScroll',function(e){
+ piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
- });
+ });
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
pic.css({maxWidth:'120px',maxHeight:'120px',display:'none'});
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div></div>')
.appendTo('body')
.css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',margin:'5px',
width:'300px',height:'10px',fontFamily:'arial narrow'})
.progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
$(this).data('prev').pic.css({opacity:'1'});
}
$(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
var next=preload.shift();
next.pic.css({opacity:'0.5',border:'3px solid #fff',display:'inline'});
$(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
} else {
// infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},500);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ console.log(e); }
}
}
function enhance_myclubs() {
GM_log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
GM_log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
// console.log( clubid+' lastvisit: '+lastvisit);
// console.log( clubid+' lastmod: '+lastmod);
// $(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
+function insertJS() {
+ _insertJS('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js');
+ _insertJS('http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js');
+ _insertJS('http://www.google-analytics.com/ga.js');
+ _insertJS('http://layout.jquery-dev.net/download/jquery.layout.min.js');
+}
+
+function _insertJS( url ) {
+ EL = document.createElement('script');
+ EL.src = url;
+ EL.type = 'text/javascript';
+ document.getElementsByTagName('head')[0].appendChild(EL);
+}
+
function insertCSS() {
$('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
$('head').append('<style id="GM_fapCSS" type="text/css">'+
'.fg-button,.fg-left {float:left;} '+
'.fg-left .link3, .fg-left b { margin:0 -6px};'+
'.clear { clear: both; height:0; line-height:0}'+
+ '.ui-layout-pane {'+
+ ' background: #FFF;'+
+ ' border: 0px solid #BBB; }'+
+ '.ui-layout-pane-east{ overflow-y: scroll }'+
+ '.ui-layout-resizer { background: #DDD; }'+
+ '.ui-layout-toggler { background: #AAA; }'+
'</style>');
}
|
monkeyoperator/greasemonkey-scripts
|
4ff022b6874dc5c884788c2481d051f10aad1ad3
|
Styled the pager display
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index 6f4d211..2538efd 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,267 +1,285 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
var $;
var pageTracker;
var threads=8;
- var chunksize=50;
+ var chunksize=100;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
console.log(gallerypage);
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
// Add jQuery and jQuery-UI
var GM_JQ = document.createElement('script');
var GM_JQ_UI = document.createElement('script');
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js';
GM_JQ.type = 'text/javascript';
GM_JQ_UI.src = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js';
GM_JQ_UI.type = 'text/javascript';
// Add Google Analytics Tracking code
var GM_GA = document.createElement('script');
GM_GA.src = 'http://www.google-analytics.com/ga.js';
GM_GA.type = 'text/javascript';
document.getElementsByTagName('body')[0].appendChild(GM_JQ);
document.getElementsByTagName('body')[0].appendChild(GM_JQ_UI);
document.getElementsByTagName('body')[0].appendChild(GM_GA);
// Check if jQuery and evil Tracking code loaded
function GM_wait() {
if(typeof unsafeWindow.jQuery == 'undefined') console.log("waiting for jQuery");
else {
$ = $ || unsafeWindow.jQuery.noConflict();
if(typeof unsafeWindow.jQuery.ui == 'undefined') console.log("waiting for jQuery-UI");
}
if(typeof unsafeWindow._gat == 'undefined') console.log("waiting for ga");
else { pageTracker = unsafeWindow._gat._getTracker("UA-7978064-1"); }
if( $ && unsafeWindow.jQuery.ui && pageTracker ) {
- $('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
+ insertCSS();
pageTracker._trackPageview();
- window.setTimeout(payload,100);
+ window.setTimeout(payload,10);
}
else window.setTimeout(GM_wait,100);
}
GM_wait();
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.click(function(){
$(this).css({position:'absolute'}).attr('showing',0);
piccontainer.hide();
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function payload() {
console.log('payload started');
resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function save_clubvisit( clubid ) {
GM_log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
+ $(':contains(next)',serverPaging).eq(1)
+ .addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-e')
+ .replaceWith('').appendTo(serverPaging);
+ $(':contains(prev)',serverPaging).eq(1)
+ .addClass('fg-button ui-state-default ui-priority-primary ui-corner-all ui-icon ui-icon-triangle-1-w')
+ .replaceWith('').prependTo(serverPaging);
+
+ $('.fg-button').hover(function(){ $(this).addClass("ui-state-hover"); }, function(){ $(this).removeClass("ui-state-hover"); });
+ $('span',serverPaging).addClass('fg-left');
+
profileLinks = $('#menubar').appendTo('body').append(favlink);
serverPaging.appendTo('#menubar').wrap('<div style="position: absolute;top:0;left:0;background:#fff"></div>');
$('<div style="float:left;">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').prependTo('#menubar');
}
thumbholder = $('<div style="position:static; float:right; width: 255px; height: 100%; overflow-x: hidden; overflow-y:scroll"></div>')
.appendTo($('body'));
thumbholder.css({marginTop:-($('#menubar').height()+2)});
piccontainer = $('<div style="position:relative;;float:left;255px;height:100%;"></div>').appendTo($('body'));
piccontainer.hide();
var w=$('#menubar').width();
if( !w )
w=$('body').width();
piccontainer.css({width:w-255});
piccontainer.css({marginTop:-($('#menubar').height()+2)});
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
pic.css({maxWidth:'120px',maxHeight:'120px',display:'none'});
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div></div>')
.appendTo('body')
.css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',margin:'5px',
width:'300px',height:'10px',fontFamily:'arial narrow'})
.progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
$(this).data('prev').pic.css({opacity:'1'});
}
$(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
var next=preload.shift();
next.pic.css({opacity:'0.5',border:'3px solid #fff',display:'inline'});
$(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
} else {
// infodiv.empty().append('done.');
- setTimeout(function(){infodiv.hide();},2000);
+ setTimeout(function(){infodiv.hide();},500);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ console.log(e); }
}
}
function enhance_myclubs() {
GM_log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
GM_log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
// console.log( clubid+' lastvisit: '+lastvisit);
// console.log( clubid+' lastmod: '+lastmod);
// $(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
+function insertCSS() {
+ $('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
+ $('head').append('<style id="GM_fapCSS" type="text/css">'+
+ '.fg-button,.fg-left {float:left;} '+
+ '.fg-left .link3, .fg-left b { margin:0 -6px};'+
+ '.clear { clear: both; height:0; line-height:0}'+
+ '</style>');
+}
|
monkeyoperator/greasemonkey-scripts
|
9451807025175a20af8b16b1232e6c01729db746
|
Added jQuery-UI only Progressbar is used for now.
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index d4d6e42..6f4d211 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,256 +1,267 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
var $;
var pageTracker;
var threads=8;
var chunksize=50;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
console.log(gallerypage);
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
- // Add jQuery
+ // Add jQuery and jQuery-UI
var GM_JQ = document.createElement('script');
- GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js';
+ var GM_JQ_UI = document.createElement('script');
+ GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js';
GM_JQ.type = 'text/javascript';
- document.getElementsByTagName('body')[0].appendChild(GM_JQ);
- // Add evil Tracking code
+ GM_JQ_UI.src = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js';
+ GM_JQ_UI.type = 'text/javascript';
+ // Add Google Analytics Tracking code
var GM_GA = document.createElement('script');
GM_GA.src = 'http://www.google-analytics.com/ga.js';
GM_GA.type = 'text/javascript';
+ document.getElementsByTagName('body')[0].appendChild(GM_JQ);
+ document.getElementsByTagName('body')[0].appendChild(GM_JQ_UI);
document.getElementsByTagName('body')[0].appendChild(GM_GA);
// Check if jQuery and evil Tracking code loaded
function GM_wait() {
- if(typeof unsafeWindow.jQuery == 'undefined') console.log("waiting for jquery");
- else { $ = unsafeWindow.jQuery.noConflict(); }
+ if(typeof unsafeWindow.jQuery == 'undefined') console.log("waiting for jQuery");
+ else {
+ $ = $ || unsafeWindow.jQuery.noConflict();
+ if(typeof unsafeWindow.jQuery.ui == 'undefined') console.log("waiting for jQuery-UI");
+ }
+
if(typeof unsafeWindow._gat == 'undefined') console.log("waiting for ga");
else { pageTracker = unsafeWindow._gat._getTracker("UA-7978064-1"); }
- if( $ && pageTracker ) {
+ if( $ && unsafeWindow.jQuery.ui && pageTracker ) {
+ $('head').append('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" rel="stylesheet" type="text/css">');
+
pageTracker._trackPageview();
window.setTimeout(payload,100);
}
else window.setTimeout(GM_wait,100);
}
GM_wait();
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.click(function(){
$(this).css({position:'absolute'}).attr('showing',0);
piccontainer.hide();
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function payload() {
console.log('payload started');
resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function save_clubvisit( clubid ) {
GM_log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
- serverPaging=$('#gallery font').eq(0);
- profileLinks = $('#menubar').appendTo('body').append(favlink);
- serverPaging.appendTo('#menubar').wrap('<div style="position: absolute;top:0;left:0;background:#fff"></div>');
- $('<div style="float:left;">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').prependTo('#menubar');
+ serverPaging=$('#gallery font').eq(0);
+ profileLinks = $('#menubar').appendTo('body').append(favlink);
+ serverPaging.appendTo('#menubar').wrap('<div style="position: absolute;top:0;left:0;background:#fff"></div>');
+ $('<div style="float:left;">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').prependTo('#menubar');
}
thumbholder = $('<div style="position:static; float:right; width: 255px; height: 100%; overflow-x: hidden; overflow-y:scroll"></div>')
.appendTo($('body'));
thumbholder.css({marginTop:-($('#menubar').height()+2)});
piccontainer = $('<div style="position:relative;;float:left;255px;height:100%;"></div>').appendTo($('body'));
piccontainer.hide();
var w=$('#menubar').width();
if( !w )
w=$('body').width();
- piccontainer.css({width:w-255});
- piccontainer.css({marginTop:-($('#menubar').height()+2)});
- piccontainer.bind('DOMMouseScroll',function(e){
+ piccontainer.css({width:w-255});
+ piccontainer.css({marginTop:-($('#menubar').height()+2)});
+ piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
pic.css({maxWidth:'120px',maxHeight:'120px',display:'none'});
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
- infodiv=$('<div>converted '+numfound+' links</div>')
+ infodiv=$('<div></div>')
.appendTo('body')
- .css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',padding:'5px',margin:'5px',
- border:'1px solid #88f',fontFamily:'arial narrow'});
+ .css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',margin:'5px',
+ width:'300px',height:'10px',fontFamily:'arial narrow'})
+ .progressbar({ value:0});
var prev = false;
var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
$(this).data('prev').pic.css({opacity:'1'});
}
+ $(infodiv).progressbar('option','value',(numfound-preload.length)/numfound * 100);
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
- infodiv.empty().append(preload.length+' left');
var next=preload.shift();
next.pic.css({opacity:'0.5',border:'3px solid #fff',display:'inline'});
$(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
} else {
- infodiv.empty().append('done.');
+// infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},2000);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ console.log(e); }
}
}
function enhance_myclubs() {
GM_log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
GM_log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
// console.log( clubid+' lastvisit: '+lastvisit);
// console.log( clubid+' lastmod: '+lastmod);
// $(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
|
monkeyoperator/greasemonkey-scripts
|
edb2bc6b60df509749a74a538c91fc173ccbed8a
|
Implemented evil User-tracking using Google Analytics
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
index 38e420b..d4d6e42 100644
--- a/imagefap_enhancer.user.js
+++ b/imagefap_enhancer.user.js
@@ -1,243 +1,256 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
-// just doing some documenting here
-//
+
var visits = GM_getObject('visits',{});
-// Add jQuery
- var GM_JQ = document.createElement('script');
+
var $;
+ var pageTracker;
var threads=8;
var chunksize=50;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
console.log(gallerypage);
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
+ // Add jQuery
+ var GM_JQ = document.createElement('script');
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js';
GM_JQ.type = 'text/javascript';
document.getElementsByTagName('body')[0].appendChild(GM_JQ);
+ // Add evil Tracking code
+ var GM_GA = document.createElement('script');
+ GM_GA.src = 'http://www.google-analytics.com/ga.js';
+ GM_GA.type = 'text/javascript';
+ document.getElementsByTagName('body')[0].appendChild(GM_GA);
-// Check if jQuery's loaded
+// Check if jQuery and evil Tracking code loaded
function GM_wait() {
- if(typeof unsafeWindow.jQuery == 'undefined') { console.log("waiting for jquery"); window.setTimeout(GM_wait,100); }
- else { $ = unsafeWindow.jQuery.noConflict(); window.setTimeout(payload,100); }
+ if(typeof unsafeWindow.jQuery == 'undefined') console.log("waiting for jquery");
+ else { $ = unsafeWindow.jQuery.noConflict(); }
+ if(typeof unsafeWindow._gat == 'undefined') console.log("waiting for ga");
+ else { pageTracker = unsafeWindow._gat._getTracker("UA-7978064-1"); }
+ if( $ && pageTracker ) {
+ pageTracker._trackPageview();
+ window.setTimeout(payload,100);
+ }
+ else window.setTimeout(GM_wait,100);
}
GM_wait();
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.click(function(){
$(this).css({position:'absolute'}).attr('showing',0);
piccontainer.hide();
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function payload() {
console.log('payload started');
resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function save_clubvisit( clubid ) {
GM_log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
profileLinks = $('#menubar').appendTo('body').append(favlink);
serverPaging.appendTo('#menubar').wrap('<div style="position: absolute;top:0;left:0;background:#fff"></div>');
$('<div style="float:left;">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').prependTo('#menubar');
}
thumbholder = $('<div style="position:static; float:right; width: 255px; height: 100%; overflow-x: hidden; overflow-y:scroll"></div>')
.appendTo($('body'));
thumbholder.css({marginTop:-($('#menubar').height()+2)});
piccontainer = $('<div style="position:relative;;float:left;255px;height:100%;"></div>').appendTo($('body'));
piccontainer.hide();
var w=$('#menubar').width();
if( !w )
w=$('body').width();
piccontainer.css({width:w-255});
piccontainer.css({marginTop:-($('#menubar').height()+2)});
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
pic.css({maxWidth:'120px',maxHeight:'120px',display:'none'});
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div>converted '+numfound+' links</div>')
.appendTo('body')
.css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',padding:'5px',margin:'5px',
border:'1px solid #88f',fontFamily:'arial narrow'});
var prev = false;
var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
$(this).data('prev').pic.css({opacity:'1'});
}
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
infodiv.empty().append(preload.length+' left');
var next=preload.shift();
next.pic.css({opacity:'0.5',border:'3px solid #fff',display:'inline'});
$(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
} else {
infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},2000);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ console.log(e); }
}
}
function enhance_myclubs() {
GM_log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
GM_log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
// console.log( clubid+' lastvisit: '+lastvisit);
// console.log( clubid+' lastmod: '+lastmod);
// $(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
|
monkeyoperator/greasemonkey-scripts
|
7c5ba89390d4a7348993c89cd4b54cae51b6f841
|
did some documentation
|
diff --git a/imagefap_enhancer.js b/imagefap_enhancer.js
index c206508..38e420b 100644
--- a/imagefap_enhancer.js
+++ b/imagefap_enhancer.js
@@ -1,242 +1,243 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
-
+// just doing some documenting here
+//
var visits = GM_getObject('visits',{});
// Add jQuery
var GM_JQ = document.createElement('script');
var $;
var threads=8;
var chunksize=50;
var piccontainer;
var preload = new Array();
var pics = new Array();
var showtimer;
var idxOffset = 0;
var randompage=window.location.href.match(/\/random\.php/);
var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
else gallerypage = false;
console.log(gallerypage);
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js';
GM_JQ.type = 'text/javascript';
document.getElementsByTagName('body')[0].appendChild(GM_JQ);
// Check if jQuery's loaded
function GM_wait() {
if(typeof unsafeWindow.jQuery == 'undefined') { console.log("waiting for jquery"); window.setTimeout(GM_wait,100); }
else { $ = unsafeWindow.jQuery.noConflict(); window.setTimeout(payload,100); }
}
GM_wait();
function showimg( pic, replace ) {
$('img',thumbholder).css({borderColor:'#fff'});
piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
showpic = $('[src='+pic.url+']');
showpic.css({position:'static'})
.attr('showing',1)
.click(function(){
$(this).css({position:'absolute'}).attr('showing',0);
piccontainer.hide();
});
$('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function payload() {
console.log('payload started');
resize_thumbs();
if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function save_clubvisit( clubid ) {
GM_log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
if( gallerypage ) {
favlink = $('#gallery').next('a').eq(0);
serverPaging=$('#gallery font').eq(0);
profileLinks = $('#menubar').appendTo('body').append(favlink);
serverPaging.appendTo('#menubar').wrap('<div style="position: absolute;top:0;left:0;background:#fff"></div>');
$('<div style="float:left;">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').prependTo('#menubar');
}
thumbholder = $('<div style="position:static; float:right; width: 255px; height: 100%; overflow-x: hidden; overflow-y:scroll"></div>')
.appendTo($('body'));
thumbholder.css({marginTop:-($('#menubar').height()+2)});
piccontainer = $('<div style="position:relative;;float:left;255px;height:100%;"></div>').appendTo($('body'));
piccontainer.hide();
var w=$('#menubar').width();
if( !w )
w=$('body').width();
piccontainer.css({width:w-255});
piccontainer.css({marginTop:-($('#menubar').height()+2)});
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
var dir = 0;
$.each(pics,function(i,item){
lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0)
dir=1;
else if( e.detail < 0 )
dir=-1;
if( showtimer ) {
clearTimeout( showtimer );
idxOffset+=dir;
}
idx = idx + dir + idxOffset;
if( idx > pics.length-1)
idx=pics.length-1;
else if( idx < 0 )
idx=0;
showtimer=setTimeout(function(){
idxOffset = 0;
showimg( pics[idx] );
showtimer = false;
},25);
$('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
pic.css({maxWidth:'120px',maxHeight:'120px',display:'none'});
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div>converted '+numfound+' links</div>')
.appendTo('body')
.css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',padding:'5px',margin:'5px',
border:'1px solid #88f',fontFamily:'arial narrow'});
var prev = false;
var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
$(this).data('prev').pic.css({opacity:'1'});
}
if( pos_in_chunk++ < chunksize ) {
if(preload[0]) {
infodiv.empty().append(preload.length+' left');
var next=preload.shift();
next.pic.css({opacity:'0.5',border:'3px solid #fff',display:'inline'});
$(this).clone(true).appendTo(piccontainer)
.data('prev',next).data('thumb',next.thumb)
.attr('src',next.url);
} else {
infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},2000);
}
} else {
if( !infodiv.data('waiting') ){
infodiv.append('<br/>continue').bind('click',startLoads);
infodiv.data('waiting',true);
}
}
} catch(e){};
}
startLoads = function() {
pos_in_chunk=0;
infodiv.data('waiting',false);
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
}
try {
var img = $('<img>')
.css({'position':'absolute','left':'-5000px'})
.css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.appendTo(piccontainer);
img.bind('load', loadfunction );
startLoads();
} catch(e){ console.log(e); }
}
}
function enhance_myclubs() {
GM_log( 'i has myclubs' );
$( "td[width='100%'][valign='top'] table" ).each( function() {
var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
if ( glink ) {
var gid = glink.match( /cid=(.*)/ )[ 1 ];
var td = $( "tr:nth-child(2) td:nth-child(2)", this );
var display = $( "tr:nth-child(2) td:nth-child(3)", this );
td.append( '<div id="club_'+gid+'">');
var gdiv = $( '#club_' + gid );
gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
gdiv.hide().load( glink + ' font span', {}, function()
{
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
var lastvisit = $(this).parent().data('lastvisit');
var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
display =$(this).parent().parent().parent().children();
GM_log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
if( lastmod.getTime() > lastvisit || lastvisit == undefined )
display.css({background:'#FFE2C5'});
else
display.css({background:'#e2FFC5'});
// console.log( clubid+' lastvisit: '+lastvisit);
// console.log( clubid+' lastmod: '+lastmod);
// $(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
|
monkeyoperator/greasemonkey-scripts
|
f81c582b7740222b9a05854db1bd2d05baddd6f8
|
geladene Bilder werden referenziert gehalten, umschaltbare Paging-funktion: Server: HTML der Imagefap-Blätterfunktion wird eingeblendet Client: Loading stops after chunksize pics
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
deleted file mode 100644
index c206508..0000000
--- a/imagefap_enhancer.user.js
+++ /dev/null
@@ -1,242 +0,0 @@
-// ==UserScript==
-// @name ImageFap enhancer
-// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
-// @include *imagefap.com/*
-// ==/UserScript==
-// imageFapThumbSize.user.js
-
- var visits = GM_getObject('visits',{});
-// Add jQuery
- var GM_JQ = document.createElement('script');
- var $;
- var threads=8;
- var chunksize=50;
- var piccontainer;
- var preload = new Array();
- var pics = new Array();
- var showtimer;
- var idxOffset = 0;
- var randompage=window.location.href.match(/\/random\.php/);
- var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
- if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
- if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
- else gallerypage = false;
- console.log(gallerypage);
- var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
- var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
- if( clubspage )
- clubspage=clubspage[1];
- GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js';
- GM_JQ.type = 'text/javascript';
- document.getElementsByTagName('body')[0].appendChild(GM_JQ);
-
-// Check if jQuery's loaded
- function GM_wait() {
- if(typeof unsafeWindow.jQuery == 'undefined') { console.log("waiting for jquery"); window.setTimeout(GM_wait,100); }
- else { $ = unsafeWindow.jQuery.noConflict(); window.setTimeout(payload,100); }
- }
- GM_wait();
- function showimg( pic, replace ) {
- $('img',thumbholder).css({borderColor:'#fff'});
- piccontainer.children().css({position:'absolute'}).attr('showing',0);
- piccontainer.show();
- showpic = $('[src='+pic.url+']');
- showpic.css({position:'static'})
- .attr('showing',1)
- .click(function(){
- $(this).css({position:'absolute'}).attr('showing',0);
- piccontainer.hide();
- });
- $('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
- }
-
-
- function payload() {
- console.log('payload started');
- resize_thumbs();
- if( gallerypage || randompage )
- create_alternate_gallery();
- if( myclubspage )
- enhance_myclubs();
- if( clubspage )
- save_clubvisit( clubspage );
- }
- function resize_thumbs() {
- $('img').each(function () {
- var s = this.src.search(/\/images\/mini\//);
- if( s != -1 ) {
- $(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
- }
- });
- }
- function save_clubvisit( clubid ) {
- GM_log('club '+clubid+' visited');
- dt=new Date();
- visits['club_'+clubid] = dt.getTime();
- GM_setObject('visits', visits);
- }
- function create_alternate_gallery() {
- var numfound=0;
- if( gallerypage ) {
- favlink = $('#gallery').next('a').eq(0);
- serverPaging=$('#gallery font').eq(0);
- profileLinks = $('#menubar').appendTo('body').append(favlink);
- serverPaging.appendTo('#menubar').wrap('<div style="position: absolute;top:0;left:0;background:#fff"></div>');
- $('<div style="float:left;">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').prependTo('#menubar');
- }
- thumbholder = $('<div style="position:static; float:right; width: 255px; height: 100%; overflow-x: hidden; overflow-y:scroll"></div>')
- .appendTo($('body'));
- thumbholder.css({marginTop:-($('#menubar').height()+2)});
-
- piccontainer = $('<div style="position:relative;;float:left;255px;height:100%;"></div>').appendTo($('body'));
- piccontainer.hide();
- var w=$('#menubar').width();
- if( !w )
- w=$('body').width();
- piccontainer.css({width:w-255});
- piccontainer.css({marginTop:-($('#menubar').height()+2)});
- piccontainer.bind('DOMMouseScroll',function(e){
- var idx = 0;
- var dir = 0;
- $.each(pics,function(i,item){
- lookfor = $('img[showing=1]',piccontainer).attr('src');
- if( item.url == lookfor ) idx=i;
- });
-
- if( e.detail > 0)
- dir=1;
-
- else if( e.detail < 0 )
- dir=-1;
-
- if( showtimer ) {
- clearTimeout( showtimer );
- idxOffset+=dir;
- }
- idx = idx + dir + idxOffset;
- if( idx > pics.length-1)
- idx=pics.length-1;
- else if( idx < 0 )
- idx=0;
-
- showtimer=setTimeout(function(){
- idxOffset = 0;
- showimg( pics[idx] );
- showtimer = false;
- },25);
-
- $('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
- });
-
- $('a[href*=image.php?id=]').each(function(){
- $(this).appendTo(thumbholder);
- var pic = $(this).find('img').eq(0);
- if( pic.attr && pic.attr('src') ) {
- var picurl = pic.attr('src').replace(/thumb/,"full" );
- var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
- preload.push(picobj);
- pics.push(picobj);
- pic.css({maxWidth:'120px',maxHeight:'120px',display:'none'});
- $(this).mouseover(function(){ showimg(picobj); return false; });
- numfound++;
- }
- });
- $('body > center:first-child').remove();
- if( numfound > 0 ) {
- infodiv=$('<div>converted '+numfound+' links</div>')
- .appendTo('body')
- .css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',padding:'5px',margin:'5px',
- border:'1px solid #88f',fontFamily:'arial narrow'});
-
- var prev = false;
- var pos_in_chunk=0;
- loadfunction = function() {
- try{
- if( $(this).data('prev') ) {
- $(this).data('prev').pic.css({opacity:'1'});
- }
- if( pos_in_chunk++ < chunksize ) {
- if(preload[0]) {
- infodiv.empty().append(preload.length+' left');
- var next=preload.shift();
- next.pic.css({opacity:'0.5',border:'3px solid #fff',display:'inline'});
- $(this).clone(true).appendTo(piccontainer)
- .data('prev',next).data('thumb',next.thumb)
- .attr('src',next.url);
- } else {
- infodiv.empty().append('done.');
- setTimeout(function(){infodiv.hide();},2000);
- }
- } else {
- if( !infodiv.data('waiting') ){
- infodiv.append('<br/>continue').bind('click',startLoads);
- infodiv.data('waiting',true);
- }
- }
- } catch(e){};
- }
- startLoads = function() {
- pos_in_chunk=0;
- infodiv.data('waiting',false);
- for( var i=0; i < threads; i++ )
- setTimeout(function(){img.clone(true).trigger('load');},i*200);
-
- }
- try {
- var img = $('<img>')
- .css({'position':'absolute','left':'-5000px'})
- .css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
- .appendTo(piccontainer);
-
-
- img.bind('load', loadfunction );
- startLoads();
- } catch(e){ console.log(e); }
- }
- }
-
- function enhance_myclubs() {
- GM_log( 'i has myclubs' );
- $( "td[width='100%'][valign='top'] table" ).each( function() {
- var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
- if ( glink ) {
- var gid = glink.match( /cid=(.*)/ )[ 1 ];
- var td = $( "tr:nth-child(2) td:nth-child(2)", this );
- var display = $( "tr:nth-child(2) td:nth-child(3)", this );
- td.append( '<div id="club_'+gid+'">');
- var gdiv = $( '#club_' + gid );
- gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
- gdiv.hide().load( glink + ' font span', {}, function()
- {
- $('span',this).each(function(){
- if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
- {
- var clubid = $(this).parent().attr('id');
- var lastvisit = $(this).parent().data('lastvisit');
- var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
- display =$(this).parent().parent().parent().children();
- GM_log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
- if( lastmod.getTime() > lastvisit || lastvisit == undefined )
- display.css({background:'#FFE2C5'});
- else
- display.css({background:'#e2FFC5'});
-
-// console.log( clubid+' lastvisit: '+lastvisit);
-// console.log( clubid+' lastmod: '+lastmod);
-// $(this).parent().parent().next().append(lastmod.toLocaleString());
- return false;
- }
- });
- });
- }
- });
- }
-function GM_getObject(key, defaultValue) {
- return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
-}
-
-function GM_setObject(key, value) {
- GM_setValue(key, value.toSource());
-}
-
-
diff --git a/imagefapthumbresizer.user.js b/imagefapthumbresizer.user.js
index 1213aab..c206508 100644
--- a/imagefapthumbresizer.user.js
+++ b/imagefapthumbresizer.user.js
@@ -1,176 +1,242 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
- GM_setValue('foo','bar');
-// Add jQuery from goole
+// Add jQuery
var GM_JQ = document.createElement('script');
var $;
var threads=8;
+ var chunksize=50;
var piccontainer;
var preload = new Array();
var pics = new Array();
- var gallerypage=window.location.href.match(/\/gallery\/|\/gallery\.php\?gid/)?true:false;
+ var showtimer;
+ var idxOffset = 0;
+ var randompage=window.location.href.match(/\/random\.php/);
+ var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
+ if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
+ if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
+ else gallerypage = false;
+ console.log(gallerypage);
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js';
GM_JQ.type = 'text/javascript';
document.getElementsByTagName('body')[0].appendChild(GM_JQ);
// Check if jQuery's loaded
function GM_wait() {
if(typeof unsafeWindow.jQuery == 'undefined') { console.log("waiting for jquery"); window.setTimeout(GM_wait,100); }
else { $ = unsafeWindow.jQuery.noConflict(); window.setTimeout(payload,100); }
}
GM_wait();
function showimg( pic, replace ) {
+ $('img',thumbholder).css({borderColor:'#fff'});
+ piccontainer.children().css({position:'absolute'}).attr('showing',0);
piccontainer.show();
- if( gallerypage || replace ){
- piccontainer.empty();
- }
-// $('<img src="'+pic.url+'">')
- $('[src='+pic.url+']').clone()
- .appendTo(piccontainer)
- .css({width:'',left:'',maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
- .click(function(){
- $(this).remove();
- piccontainer.hide();
- });
+ showpic = $('[src='+pic.url+']');
+ showpic.css({position:'static'})
+ .attr('showing',1)
+ .click(function(){
+ $(this).css({position:'absolute'}).attr('showing',0);
+ piccontainer.hide();
+ });
+ $('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
}
function payload() {
console.log('payload started');
resize_thumbs();
- if( gallerypage )
+ if( gallerypage || randompage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function save_clubvisit( clubid ) {
GM_log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
- favlink = $('#gallery').next('a').eq(0);
- profileLinks = $('#menubar').appendTo('body').append(favlink);
+ if( gallerypage ) {
+ favlink = $('#gallery').next('a').eq(0);
+ serverPaging=$('#gallery font').eq(0);
+ profileLinks = $('#menubar').appendTo('body').append(favlink);
+ serverPaging.appendTo('#menubar').wrap('<div style="position: absolute;top:0;left:0;background:#fff"></div>');
+ $('<div style="float:left;">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').prependTo('#menubar');
+ }
thumbholder = $('<div style="position:static; float:right; width: 255px; height: 100%; overflow-x: hidden; overflow-y:scroll"></div>')
.appendTo($('body'));
thumbholder.css({marginTop:-($('#menubar').height()+2)});
piccontainer = $('<div style="position:relative;;float:left;255px;height:100%;"></div>').appendTo($('body'));
piccontainer.hide();
- piccontainer.css({width:$('#menubar').width()-255});
+ var w=$('#menubar').width();
+ if( !w )
+ w=$('body').width();
+ piccontainer.css({width:w-255});
piccontainer.css({marginTop:-($('#menubar').height()+2)});
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
+ var dir = 0;
$.each(pics,function(i,item){
- lookfor = $('img',piccontainer).attr('src');
+ lookfor = $('img[showing=1]',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
- if( e.detail > 0 && idx+1 < pics.length)
- showimg( pics[idx+1]);
-
- if( e.detail < 0 && idx-1 >= 0 )
- showimg( pics[idx-1] );
+ if( e.detail > 0)
+ dir=1;
+
+ else if( e.detail < 0 )
+ dir=-1;
+
+ if( showtimer ) {
+ clearTimeout( showtimer );
+ idxOffset+=dir;
+ }
+ idx = idx + dir + idxOffset;
+ if( idx > pics.length-1)
+ idx=pics.length-1;
+ else if( idx < 0 )
+ idx=0;
+
+ showtimer=setTimeout(function(){
+ idxOffset = 0;
+ showimg( pics[idx] );
+ showtimer = false;
+ },25);
+
+ $('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
- var picobj = {pic:pic,url:picurl};
+ var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
preload.push(picobj);
pics.push(picobj);
- pic.css({maxWidth:'120px',maxHeight:'120px'});
+ pic.css({maxWidth:'120px',maxHeight:'120px',display:'none'});
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div>converted '+numfound+' links</div>')
.appendTo('body')
- .css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',padding:'5px',margin:'5px',border:'1px solid #88f'});
+ .css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',padding:'5px',margin:'5px',
+ border:'1px solid #88f',fontFamily:'arial narrow'});
var prev = false;
+ var pos_in_chunk=0;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
- $(this).data('prev').pic.css({outline:'3px solid #080'});
+ $(this).data('prev').pic.css({opacity:'1'});
}
- if(preload[0]) {
- infodiv.empty().append(preload.length+' left');
- var next=preload.shift();
- next.pic.css({outline:'3px dotted #f00'});
- $(this).clone(true).appendTo('body').data('prev',next).attr('src',next.url);
- } else {
- infodiv.empty().append('done.');
- setTimeout(function(){infodiv.hide();},2000);
+ if( pos_in_chunk++ < chunksize ) {
+ if(preload[0]) {
+ infodiv.empty().append(preload.length+' left');
+ var next=preload.shift();
+ next.pic.css({opacity:'0.5',border:'3px solid #fff',display:'inline'});
+ $(this).clone(true).appendTo(piccontainer)
+ .data('prev',next).data('thumb',next.thumb)
+ .attr('src',next.url);
+ } else {
+ infodiv.empty().append('done.');
+ setTimeout(function(){infodiv.hide();},2000);
+ }
+ } else {
+ if( !infodiv.data('waiting') ){
+ infodiv.append('<br/>continue').bind('click',startLoads);
+ infodiv.data('waiting',true);
+ }
}
} catch(e){};
}
+ startLoads = function() {
+ pos_in_chunk=0;
+ infodiv.data('waiting',false);
+ for( var i=0; i < threads; i++ )
+ setTimeout(function(){img.clone(true).trigger('load');},i*200);
+
+ }
try {
- var img = $('<img>').css({'position':'absolute','left':'-5000px','width':'10px'});
+ var img = $('<img>')
+ .css({'position':'absolute','left':'-5000px'})
+ .css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
+ .appendTo(piccontainer);
+
+
img.bind('load', loadfunction );
- for( var i=0; i < threads; i++ )
- setTimeout(function(){img.clone(true).trigger('load');},i*200);
+ startLoads();
} catch(e){ console.log(e); }
}
}
+
function enhance_myclubs() {
- GM_log('i has myclubs');
- $("td[width='100%'][valign='top'] table").each(function(){
- var glink=$("tr:nth-child(2) ;a[href*='clubs/index.php?cid=']",this).attr('href');
- if (glink) {
- var gid=glink.match(/cid=(.*)/)[1];
- var td=$("tr:nth-child(2) td:nth-child(2)",this);
- var display=$("tr:nth-child(2) td:nth-child(3)",this);
- td.append('<div id="club_'+gid+'">');
- var gdiv=$('#club_'+gid);
- gdiv.hide().load(glink+' font span',{},function(){
+ GM_log( 'i has myclubs' );
+ $( "td[width='100%'][valign='top'] table" ).each( function() {
+ var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
+ if ( glink ) {
+ var gid = glink.match( /cid=(.*)/ )[ 1 ];
+ var td = $( "tr:nth-child(2) td:nth-child(2)", this );
+ var display = $( "tr:nth-child(2) td:nth-child(3)", this );
+ td.append( '<div id="club_'+gid+'">');
+ var gdiv = $( '#club_' + gid );
+ gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
+ gdiv.hide().load( glink + ' font span', {}, function()
+ {
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
- lastmod= new Date(gdate[1], gdate[2], gdate[3],gdate[4],gdate[5],gdate[6]);
- console.log( clubid+' lastvisit: '+visits['club_'+clubid] );
- console.log( clubid+' lastmod: '+lastmod);
- $(this).parent().parent().next().append(lastmod.toLocaleString());
+ var lastvisit = $(this).parent().data('lastvisit');
+ var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
+ display =$(this).parent().parent().parent().children();
+ GM_log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
+ if( lastmod.getTime() > lastvisit || lastvisit == undefined )
+ display.css({background:'#FFE2C5'});
+ else
+ display.css({background:'#e2FFC5'});
+
+// console.log( clubid+' lastvisit: '+lastvisit);
+// console.log( clubid+' lastmod: '+lastmod);
+// $(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
|
monkeyoperator/greasemonkey-scripts
|
5c59f1d629f25b0dfeffaf16438402db9387f08a
|
neuer name, neuer content
|
diff --git a/imagefap_enhancer.user.js b/imagefap_enhancer.user.js
new file mode 100644
index 0000000..c206508
--- /dev/null
+++ b/imagefap_enhancer.user.js
@@ -0,0 +1,242 @@
+// ==UserScript==
+// @name ImageFap enhancer
+// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
+// @include *imagefap.com/*
+// ==/UserScript==
+// imageFapThumbSize.user.js
+
+ var visits = GM_getObject('visits',{});
+// Add jQuery
+ var GM_JQ = document.createElement('script');
+ var $;
+ var threads=8;
+ var chunksize=50;
+ var piccontainer;
+ var preload = new Array();
+ var pics = new Array();
+ var showtimer;
+ var idxOffset = 0;
+ var randompage=window.location.href.match(/\/random\.php/);
+ var gallerypage=window.location.href.match(/\/random\.php|\/gallery\/(.*)|\/gallery\.php\?p?gid=(.*)/);
+ if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0].match(/[0-9]+/);
+ if( gallerypage && gallerypage[0] ) gallerypage = gallerypage[0];
+ else gallerypage = false;
+ console.log(gallerypage);
+ var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
+ var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
+ if( clubspage )
+ clubspage=clubspage[1];
+ GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js';
+ GM_JQ.type = 'text/javascript';
+ document.getElementsByTagName('body')[0].appendChild(GM_JQ);
+
+// Check if jQuery's loaded
+ function GM_wait() {
+ if(typeof unsafeWindow.jQuery == 'undefined') { console.log("waiting for jquery"); window.setTimeout(GM_wait,100); }
+ else { $ = unsafeWindow.jQuery.noConflict(); window.setTimeout(payload,100); }
+ }
+ GM_wait();
+ function showimg( pic, replace ) {
+ $('img',thumbholder).css({borderColor:'#fff'});
+ piccontainer.children().css({position:'absolute'}).attr('showing',0);
+ piccontainer.show();
+ showpic = $('[src='+pic.url+']');
+ showpic.css({position:'static'})
+ .attr('showing',1)
+ .click(function(){
+ $(this).css({position:'absolute'}).attr('showing',0);
+ piccontainer.hide();
+ });
+ $('img[src="'+showpic.data('thumb')+'"]').css({borderColor:'#f00'});
+ }
+
+
+ function payload() {
+ console.log('payload started');
+ resize_thumbs();
+ if( gallerypage || randompage )
+ create_alternate_gallery();
+ if( myclubspage )
+ enhance_myclubs();
+ if( clubspage )
+ save_clubvisit( clubspage );
+ }
+ function resize_thumbs() {
+ $('img').each(function () {
+ var s = this.src.search(/\/images\/mini\//);
+ if( s != -1 ) {
+ $(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
+ }
+ });
+ }
+ function save_clubvisit( clubid ) {
+ GM_log('club '+clubid+' visited');
+ dt=new Date();
+ visits['club_'+clubid] = dt.getTime();
+ GM_setObject('visits', visits);
+ }
+ function create_alternate_gallery() {
+ var numfound=0;
+ if( gallerypage ) {
+ favlink = $('#gallery').next('a').eq(0);
+ serverPaging=$('#gallery font').eq(0);
+ profileLinks = $('#menubar').appendTo('body').append(favlink);
+ serverPaging.appendTo('#menubar').wrap('<div style="position: absolute;top:0;left:0;background:#fff"></div>');
+ $('<div style="float:left;">paging:<a href="/gallery.php?gid='+gallerypage+'&view=1">server</a> | <a href="/gallery.php?gid='+gallerypage+'&view=2">client</a></div>').prependTo('#menubar');
+ }
+ thumbholder = $('<div style="position:static; float:right; width: 255px; height: 100%; overflow-x: hidden; overflow-y:scroll"></div>')
+ .appendTo($('body'));
+ thumbholder.css({marginTop:-($('#menubar').height()+2)});
+
+ piccontainer = $('<div style="position:relative;;float:left;255px;height:100%;"></div>').appendTo($('body'));
+ piccontainer.hide();
+ var w=$('#menubar').width();
+ if( !w )
+ w=$('body').width();
+ piccontainer.css({width:w-255});
+ piccontainer.css({marginTop:-($('#menubar').height()+2)});
+ piccontainer.bind('DOMMouseScroll',function(e){
+ var idx = 0;
+ var dir = 0;
+ $.each(pics,function(i,item){
+ lookfor = $('img[showing=1]',piccontainer).attr('src');
+ if( item.url == lookfor ) idx=i;
+ });
+
+ if( e.detail > 0)
+ dir=1;
+
+ else if( e.detail < 0 )
+ dir=-1;
+
+ if( showtimer ) {
+ clearTimeout( showtimer );
+ idxOffset+=dir;
+ }
+ idx = idx + dir + idxOffset;
+ if( idx > pics.length-1)
+ idx=pics.length-1;
+ else if( idx < 0 )
+ idx=0;
+
+ showtimer=setTimeout(function(){
+ idxOffset = 0;
+ showimg( pics[idx] );
+ showtimer = false;
+ },25);
+
+ $('img[src="'+pics[idx].thumb+'"]').get(0).scrollIntoView(false);
+ });
+
+ $('a[href*=image.php?id=]').each(function(){
+ $(this).appendTo(thumbholder);
+ var pic = $(this).find('img').eq(0);
+ if( pic.attr && pic.attr('src') ) {
+ var picurl = pic.attr('src').replace(/thumb/,"full" );
+ var picobj = {pic:pic,url:picurl,thumb:pic.attr('src')};
+ preload.push(picobj);
+ pics.push(picobj);
+ pic.css({maxWidth:'120px',maxHeight:'120px',display:'none'});
+ $(this).mouseover(function(){ showimg(picobj); return false; });
+ numfound++;
+ }
+ });
+ $('body > center:first-child').remove();
+ if( numfound > 0 ) {
+ infodiv=$('<div>converted '+numfound+' links</div>')
+ .appendTo('body')
+ .css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',padding:'5px',margin:'5px',
+ border:'1px solid #88f',fontFamily:'arial narrow'});
+
+ var prev = false;
+ var pos_in_chunk=0;
+ loadfunction = function() {
+ try{
+ if( $(this).data('prev') ) {
+ $(this).data('prev').pic.css({opacity:'1'});
+ }
+ if( pos_in_chunk++ < chunksize ) {
+ if(preload[0]) {
+ infodiv.empty().append(preload.length+' left');
+ var next=preload.shift();
+ next.pic.css({opacity:'0.5',border:'3px solid #fff',display:'inline'});
+ $(this).clone(true).appendTo(piccontainer)
+ .data('prev',next).data('thumb',next.thumb)
+ .attr('src',next.url);
+ } else {
+ infodiv.empty().append('done.');
+ setTimeout(function(){infodiv.hide();},2000);
+ }
+ } else {
+ if( !infodiv.data('waiting') ){
+ infodiv.append('<br/>continue').bind('click',startLoads);
+ infodiv.data('waiting',true);
+ }
+ }
+ } catch(e){};
+ }
+ startLoads = function() {
+ pos_in_chunk=0;
+ infodiv.data('waiting',false);
+ for( var i=0; i < threads; i++ )
+ setTimeout(function(){img.clone(true).trigger('load');},i*200);
+
+ }
+ try {
+ var img = $('<img>')
+ .css({'position':'absolute','left':'-5000px'})
+ .css({maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
+ .appendTo(piccontainer);
+
+
+ img.bind('load', loadfunction );
+ startLoads();
+ } catch(e){ console.log(e); }
+ }
+ }
+
+ function enhance_myclubs() {
+ GM_log( 'i has myclubs' );
+ $( "td[width='100%'][valign='top'] table" ).each( function() {
+ var glink=$( "tr:nth-child(2) ;a[href*='clubs/index.php?cid=']", this ).attr( 'href' );
+ if ( glink ) {
+ var gid = glink.match( /cid=(.*)/ )[ 1 ];
+ var td = $( "tr:nth-child(2) td:nth-child(2)", this );
+ var display = $( "tr:nth-child(2) td:nth-child(3)", this );
+ td.append( '<div id="club_'+gid+'">');
+ var gdiv = $( '#club_' + gid );
+ gdiv.data( 'lastvisit', visits[ 'club_'+gid ] );
+ gdiv.hide().load( glink + ' font span', {}, function()
+ {
+ $('span',this).each(function(){
+ if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
+ {
+ var clubid = $(this).parent().attr('id');
+ var lastvisit = $(this).parent().data('lastvisit');
+ var lastmod= new Date(gdate[1], parseInt(gdate[2])-1, gdate[3],gdate[4],gdate[5],gdate[6]);
+ display =$(this).parent().parent().parent().children();
+ GM_log( clubid+' lastmod:'+ lastmod.getTime()+ ' lastvisit:'+ lastvisit );
+ if( lastmod.getTime() > lastvisit || lastvisit == undefined )
+ display.css({background:'#FFE2C5'});
+ else
+ display.css({background:'#e2FFC5'});
+
+// console.log( clubid+' lastvisit: '+lastvisit);
+// console.log( clubid+' lastmod: '+lastmod);
+// $(this).parent().parent().next().append(lastmod.toLocaleString());
+ return false;
+ }
+ });
+ });
+ }
+ });
+ }
+function GM_getObject(key, defaultValue) {
+ return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
+}
+
+function GM_setObject(key, value) {
+ GM_setValue(key, value.toSource());
+}
+
+
|
monkeyoperator/greasemonkey-scripts
|
81b52fbe01391a172fd4c9ec4790738172c7bdaf
|
Signed-off-by: makro <makro@mbox.(none)>
|
diff --git a/imagefapthumbresizer.user.js b/imagefapthumbresizer.user.js
index 84266da..1213aab 100644
--- a/imagefapthumbresizer.user.js
+++ b/imagefapthumbresizer.user.js
@@ -1,176 +1,176 @@
// ==UserScript==
// @name ImageFap enhancer
// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
// @include *imagefap.com/*
// ==/UserScript==
// imageFapThumbSize.user.js
var visits = GM_getObject('visits',{});
GM_setValue('foo','bar');
-// Add jQuery
+// Add jQuery from goole
var GM_JQ = document.createElement('script');
var $;
var threads=8;
var piccontainer;
var preload = new Array();
var pics = new Array();
var gallerypage=window.location.href.match(/\/gallery\/|\/gallery\.php\?gid/)?true:false;
var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
if( clubspage )
clubspage=clubspage[1];
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js';
GM_JQ.type = 'text/javascript';
document.getElementsByTagName('body')[0].appendChild(GM_JQ);
// Check if jQuery's loaded
function GM_wait() {
if(typeof unsafeWindow.jQuery == 'undefined') { console.log("waiting for jquery"); window.setTimeout(GM_wait,100); }
else { $ = unsafeWindow.jQuery.noConflict(); window.setTimeout(payload,100); }
}
GM_wait();
function showimg( pic, replace ) {
piccontainer.show();
if( gallerypage || replace ){
piccontainer.empty();
}
// $('<img src="'+pic.url+'">')
$('[src='+pic.url+']').clone()
.appendTo(piccontainer)
.css({width:'',left:'',maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
.click(function(){
$(this).remove();
piccontainer.hide();
});
}
function payload() {
console.log('payload started');
resize_thumbs();
if( gallerypage )
create_alternate_gallery();
if( myclubspage )
enhance_myclubs();
if( clubspage )
save_clubvisit( clubspage );
}
function resize_thumbs() {
$('img').each(function () {
var s = this.src.search(/\/images\/mini\//);
if( s != -1 ) {
$(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
}
});
}
function save_clubvisit( clubid ) {
GM_log('club '+clubid+' visited');
dt=new Date();
visits['club_'+clubid] = dt.getTime();
GM_setObject('visits', visits);
}
function create_alternate_gallery() {
var numfound=0;
favlink = $('#gallery').next('a').eq(0);
profileLinks = $('#menubar').appendTo('body').append(favlink);
thumbholder = $('<div style="position:static; float:right; width: 255px; height: 100%; overflow-x: hidden; overflow-y:scroll"></div>')
.appendTo($('body'));
thumbholder.css({marginTop:-($('#menubar').height()+2)});
piccontainer = $('<div style="position:relative;;float:left;255px;height:100%;"></div>').appendTo($('body'));
piccontainer.hide();
piccontainer.css({width:$('#menubar').width()-255});
piccontainer.css({marginTop:-($('#menubar').height()+2)});
piccontainer.bind('DOMMouseScroll',function(e){
var idx = 0;
$.each(pics,function(i,item){
lookfor = $('img',piccontainer).attr('src');
if( item.url == lookfor ) idx=i;
});
if( e.detail > 0 && idx+1 < pics.length)
showimg( pics[idx+1]);
if( e.detail < 0 && idx-1 >= 0 )
showimg( pics[idx-1] );
});
$('a[href*=image.php?id=]').each(function(){
$(this).appendTo(thumbholder);
var pic = $(this).find('img').eq(0);
if( pic.attr && pic.attr('src') ) {
var picurl = pic.attr('src').replace(/thumb/,"full" );
var picobj = {pic:pic,url:picurl};
preload.push(picobj);
pics.push(picobj);
pic.css({maxWidth:'120px',maxHeight:'120px'});
$(this).mouseover(function(){ showimg(picobj); return false; });
numfound++;
}
});
$('body > center:first-child').remove();
if( numfound > 0 ) {
infodiv=$('<div>converted '+numfound+' links</div>')
.appendTo('body')
.css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',padding:'5px',margin:'5px',border:'1px solid #88f'});
var prev = false;
loadfunction = function() {
try{
if( $(this).data('prev') ) {
$(this).data('prev').pic.css({outline:'3px solid #080'});
}
if(preload[0]) {
infodiv.empty().append(preload.length+' left');
var next=preload.shift();
next.pic.css({outline:'3px dotted #f00'});
$(this).clone(true).appendTo('body').data('prev',next).attr('src',next.url);
} else {
infodiv.empty().append('done.');
setTimeout(function(){infodiv.hide();},2000);
}
} catch(e){};
}
try {
var img = $('<img>').css({'position':'absolute','left':'-5000px','width':'10px'});
img.bind('load', loadfunction );
for( var i=0; i < threads; i++ )
setTimeout(function(){img.clone(true).trigger('load');},i*200);
} catch(e){ console.log(e); }
}
}
function enhance_myclubs() {
GM_log('i has myclubs');
$("td[width='100%'][valign='top'] table").each(function(){
var glink=$("tr:nth-child(2) ;a[href*='clubs/index.php?cid=']",this).attr('href');
if (glink) {
var gid=glink.match(/cid=(.*)/)[1];
var td=$("tr:nth-child(2) td:nth-child(2)",this);
var display=$("tr:nth-child(2) td:nth-child(3)",this);
td.append('<div id="club_'+gid+'">');
var gdiv=$('#club_'+gid);
gdiv.hide().load(glink+' font span',{},function(){
$('span',this).each(function(){
if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
{
var clubid = $(this).parent().attr('id');
lastmod= new Date(gdate[1], gdate[2], gdate[3],gdate[4],gdate[5],gdate[6]);
console.log( clubid+' lastvisit: '+visits['club_'+clubid] );
console.log( clubid+' lastmod: '+lastmod);
$(this).parent().parent().next().append(lastmod.toLocaleString());
return false;
}
});
});
}
});
}
function GM_getObject(key, defaultValue) {
return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
}
function GM_setObject(key, value) {
GM_setValue(key, value.toSource());
}
|
monkeyoperator/greasemonkey-scripts
|
59f90e8e09cbecaf6de6dc0efe1ff80c3567b2da
|
initial check-in
|
diff --git a/betterdir.user.js b/betterdir.user.js
new file mode 100644
index 0000000..84b48ce
--- /dev/null
+++ b/betterdir.user.js
@@ -0,0 +1,245 @@
+
+// BetterDir
+// version 1.0 BETA!
+// 2005-05-02
+// Copyright (c) 2005, Mark Pilgrim
+// Released under the GPL license
+// http://www.gnu.org/copyleft/gpl.html
+//
+// --------------------------------------------------------------------
+//
+// This is a Greasemonkey user script. To install it, you need
+// Greasemonkey 0.3 or later: http://greasemonkey.mozdev.org/
+// Then restart Firefox and revisit this script.
+// Under Tools, there will be a new menu item to "Install User Script".
+// Accept the default configuration and install.
+//
+// To uninstall, go to Tools/Manage User Scripts,
+// select "BetterDir", and click Uninstall.
+//
+// --------------------------------------------------------------------
+//
+// ==UserScript==
+// @name BetterDir
+// @namespace http://diveintomark.org/projects/greasemonkey/
+// @description make Apache 1.3-style directory listings prettier
+// @include *
+// ==/UserScript==
+
+function addGlobalStyle(css) {
+ var head, style;
+ head = document.getElementsByTagName('head')[0];
+ if (!head) { return; }
+ style = document.createElement('style');
+ style.type = 'text/css';
+ style.innerHTML = css;
+ head.appendChild(style);
+}
+
+var titles, pre, headers, table, caption;
+var tr0, header, a, nHeaders, th, pretext;
+var row, rows, nRows, odd, rest, restcols, tr, td;
+var nColumns, rightAlign, col, temp;
+var footer, footertext;
+
+titles = document.getElementsByTagName('title');
+// if page has no title, bail
+if (!titles.length) { return; }
+// if page title does not start with "Index of /", bail
+if (!(/^Index of \//.test(titles[0].textContent))) { return; }
+
+// If we can't find the PRE element, this is either
+// not a directory listing at all, or it's an
+// Apache 2.x listing with fancy table output enabled
+pre = document.getElementsByTagName('pre')[0];
+if (!pre) { return; }
+
+// find the column headers, or bail
+headers = document.evaluate(
+ "//a[contains(@href, '?')]",
+ document,
+ null,
+ XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
+ null);
+if (!headers) { return; }
+
+// Tables aren't evil, they're just supposed to be used for tabular data.
+// This is tabular data, so let's make a TABLE element
+table = document.createElement('table');
+// give the table a summary, for accessibility
+table.setAttribute('summary', 'Directory listing');
+caption = document.createElement('caption');
+// the "title" of the table should go in a CAPTION element
+// inside the TABLE element, for semantic purity
+caption.textContent = document.evaluate(
+ "//head/title",
+ document,
+ null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent;
+table.appendChild(caption);
+
+tr0 = document.createElement('tr');
+nHeaders = 0;
+for (var i = 0; i < headers.snapshotLength; i++) {
+ header = headers.snapshotItem(i);
+ // column headers go into TH elements, for accessibility
+ th = document.createElement('th');
+ a = document.createElement('a');
+ a.href = header.href;
+ a.textContent = header.textContent;
+ // give each of the column header links a title,
+ // to explain what the hell they do (it took me 5 years
+ // to stumble onto this sorting feature --
+ // titles might've helped, ya think?)
+ a.title = "Sort by " + header.textContent.toLowerCase();
+ th.appendChild(a);
+ tr0.appendChild(th);
+ nHeaders++;
+}
+table.appendChild(tr0);
+
+pretext = pre.innerHTML;
+if (/<hr/.test(pretext)) {
+ pretext = pretext.split(/<hr.*?>/)[1];
+}
+rows = pretext.split(/\n/);
+nRows = rows.length;
+odd = true;
+for (var i = 0; i < nRows; i++) {
+ row = rows[i];
+ row = row.replace(/^\s*|\s*$/g, '');
+ if (!row) { continue; }
+ if (/\<hr/.test(row)) { continue; }
+ temp = row.split(/<\/a>/);
+ a = temp[0] + '</a>';
+ if (/<img/.test(a)) {
+ a = a.split(/<img.*?>/)[1];
+ }
+ rest = temp[1];
+ restcols = rest.split(/\s+/);
+
+ tr = document.createElement('tr');
+ td = document.createElement('td');
+ td.innerHTML = a;
+ tr.appendChild(td);
+
+ nColumns = restcols.length;
+ rightAlign = false;
+ for (var j = 1 /* really */; j < nColumns; j++) {
+ col = restcols[j];
+ if (/\d\d:\d\d/.test(col)) {
+ td.innerHTML = td.innerHTML + ' ' + col;
+ } else {
+ td = document.createElement('td');
+ td.innerHTML = restcols[j];
+ if (rightAlign) {
+ td.setAttribute('class', 'flushright');
+ }
+ tr.appendChild(td);
+ }
+ rightAlign = true;
+ }
+ while (nColumns <= nHeaders) {
+ tr.appendChild(document.createElement('td'));
+ nColumns++;
+ }
+
+ // zebra-stripe table rows, from
+ // http://www.alistapart.com/articles/zebratables/
+ // and http://www.alistapart.com/articles/tableruler/
+ tr.style.backgroundColor = odd ? '#eee' : '#fff';
+// tr.onmouseover = function() { this.className = 'ruled'; return false; };
+// tr.onmouseout = function() { this.className = ''; return false; };
+ table.appendChild(tr);
+
+ odd = !odd;
+}
+
+// copy address footer -- probably a much easier way to do this,
+// but it's not always there (depends on httpd.conf options)
+footertext = document.getElementsByTagName('address')[0];
+if (footertext) {
+ footer = document.createElement('address');
+ footer.innerHTML = footertext.innerHTML;
+}
+
+// GreaseMonkey mythology states that wholesale DOM changes should
+// be done on load, rather than in the GM script itself. I don't know
+// if this is still true, or indeed if it was ever true, but
+// a little chicken sacrifice never hurt anyone except the chicken.
+window.addEventListener('load',
+ function() {
+ document.body.innerHTML = '';
+ document.body.appendChild(table);
+ if (footer) {
+ document.body.appendChild(footer);
+ }
+ },
+ true);
+
+// now that everything is semantic and accessible,
+// make it a little prettier too
+addGlobalStyle(
+'table {' +
+' border-collapse: collapse;' +
+' border-spacing: 0px 0px 5px 0px;' +
+' margin-top: 1em;' +
+' width: 100%;' +
+'}' +
+'caption {' +
+' text-align: left;' +
+' font-weight: bold;' +
+' font-size: 180%;' +
+' font-family: Optima, Verdana, sans-serif;' +
+'}' +
+'tr {' +
+' padding-bottom: 5px;' +
+'}' +
+'td, th {' +
+' font-size: medium;' +
+' text-align: right;' +
+'}' +
+'th {' +
+' font-family: Optima, Verdana, sans-serif;' +
+' padding-right: 10px;' +
+' padding-bottom: 0.5em;' +
+'}' +
+'th:first-child {' +
+' padding-left: 20px;' +
+'}' +
+'td:first-child,' +
+'td:last-child,' +
+'th:first-child,' +
+'th:last-child {' +
+' text-align: left;' +
+'}' +
+'td {' +
+' font-family: monospace;' +
+' border-bottom: 1px solid silver;' +
+' padding: 3px 10px 3px 20px;' +
+' border-bottom: 1px dotted #003399;' +
+'}' +
+'td a {' +
+' text-decoration: none;' +
+'}' +
+'tr.ruled {' +
+' background-color: #ffeecc ! important;' +
+'}' +
+'address {' +
+' margin-top: 1em;' +
+' font-style: italic;' +
+' font-family: Optima, Verdana, sans-serif;' +
+' font-size: small;' +
+' background-color: transparent;' +
+' color: silver;' +
+'}');
+
+//
+// ChangeLog:
+// 2005-05-02 - 1.0 - MAP - remove anon function wrapper, require GM 0.3
+// 2005-04-21 - 0.9 - MAP - linted
+// 2005-04-21 - 0.8 - MAP - changed addGlobalStyle to a normal function
+// 2005-04-18 - 0.7 - MAP - tidy code
+// 2005-04-15 - 0.6 - MAP - changed addGlobalStyle function to check for <head> element
+// 2005-04-14 - 0.5 - MAP - older versions of Apache don't insert META tag, so check for page title instead
+//
diff --git a/bookmarkhtmlenhance.user.js b/bookmarkhtmlenhance.user.js
new file mode 100644
index 0000000..3ce0463
--- /dev/null
+++ b/bookmarkhtmlenhance.user.js
@@ -0,0 +1,30 @@
+// ==UserScript==
+// @name bookmark.html.enhance
+// @namespace
+// @description Add Functions to bookmarks.html
+// @include */bookmarks.html
+// ==/UserScript==
+// OpenBCUserImages.user.js
+
+(function() {
+ function addTextArea(e) {
+ linkList=this.nextSibling.nextSibling.getElementsByTagName("a");
+ var html="";
+ for(j=0; j<linkList.length;j++) {
+ html=html + linkList[j].href+"\n";
+ }
+ newE = document.createElement("textarea");
+ newE.innerHTML=html;
+ newE.rows=5;
+ newE.cols=80;
+ this.removeEventListener("mousedown",addTextArea,false);
+ this.appendChild(newE);
+ }
+ window.addEventListener("load", function(e) {
+ var h3List = document.getElementsByTagName("h3");
+ for( i=0; i < h3List.length; i++) {
+ h3List[i].addEventListener("mousedown",addTextArea,false);
+ }
+ }, false);
+})();
+
diff --git a/dfgh.user.js b/dfgh.user.js
new file mode 100644
index 0000000..d1afb42
--- /dev/null
+++ b/dfgh.user.js
@@ -0,0 +1,53 @@
+// ==UserScript==
+// @name dfgh
+// @namespace http://localhost/userscripts
+// @description Ausfuellen von Textfeldern die email-adressen erwarten
+// @include *
+// ==/UserScript==
+
+(function() {
+ function randstring() {
+ var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
+ var string_length = Math.floor(Math.random()*5)+10;
+ var randomstring = '';
+ for (var i=0; i<string_length; i++) {
+ var rnum = Math.floor(Math.random() * chars.length);
+ randomstring += chars.substring(rnum,rnum+1);
+ }
+ return randomstring;
+ }
+ window.addEventListener("load",function(e) {
+ var names= new Array(/^login$/,/^email$/,/^EMAIL$/,/email_address/,/email$/);
+ var email;
+ var RE = /\.(.*\..*)$/
+ RE.exec(location.host)
+ email=RegExp.$1 + '[email protected]';
+ allText = document.evaluate(
+ "//input[@type='text']",
+ // "//input",
+ document,
+ null,
+ XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
+ null);
+ for (var i = 0; i < allText.snapshotLength; i++) {
+ thisText = allText.snapshotItem(i);
+ for(var j = 0; j < names.length; j++)
+ if(names[j].exec(thisText.name)) thisText.value=email;
+ }
+ var foo=document.getElementsByTagName('a');
+ referReg=/(ref=|affid=|aff=|ccbill(=|\/)|campaignid=)/;
+ for(i=0;i<foo.length;i++) {
+ item=foo[i];
+ if(item.href.search(referReg)!=-1){
+ try {
+ item.firstChild.style.border="2px dashed green";
+ item.firstChild.style.MozBorderRadius='5px';
+ item.firstChild.style.padding='3px';
+ } catch(e){}
+ item.href=item.href.replace(referReg,'$1'+randstring());
+ }
+ }
+ },false);
+
+})();
+
diff --git a/flickrexifdecorator.user.js b/flickrexifdecorator.user.js
new file mode 100644
index 0000000..8b2d3dd
--- /dev/null
+++ b/flickrexifdecorator.user.js
@@ -0,0 +1,224 @@
+// ==UserScript==
+// @name Flickr Exif Decorator
+// @namespace http://netcetera.org
+// @include http://*flickr.com/photos/*
+// @description Decorates photos on Flickr with Exif data (Aperture, Exposure, ISO Speed, etc)
+
+window.addEventListener("load", function() { FED_decorate_photo() }, false);
+
+function FED_decorate_photo() {
+
+ var FED_isInFlickrDialog = function(obj) {
+ var re = /.*DialogDiv$/;
+ while (obj) {
+ if (obj.id && obj.id.match(re))
+ return true;
+ obj = obj.parentNode;
+ }
+ return false;
+ };
+
+ var FED_showOverlay = function(overlay, obj) {
+ var pos = FED_getPos(obj);
+ overlay.style.left = pos[0];
+ overlay.style.top = pos[1];
+ overlay.style.visibility = 'visible';
+ };
+
+ var FED_getPos = function(obj) {
+ var x = 0;
+ var y = 0;
+ if (obj.offsetParent) {
+ x = obj.offsetLeft
+ y = obj.offsetTop
+ while (obj = obj.offsetParent) {
+ x += obj.offsetLeft
+ y += obj.offsetTop
+ }
+ }
+ return [x,y];
+ };
+
+ var FED_mouseInsideObj = function(e, obj) {
+ var posx = 0;
+ var posy = 0;
+ if (!e) return false;
+
+ if (e.pageX || e.pageY) {
+ posx = e.pageX;
+ posy = e.pageY;
+ }
+ else if (e.clientX || e.clientY) {
+ posx = e.clientX + document.body.scrollLeft
+ + document.documentElement.scrollLeft;
+ posy = e.clientY + document.body.scrollTop
+ + document.documentElement.scrollTop;
+ }
+
+ // get image coordinates
+ var objpos = FED_getPos(obj);
+ var x = objpos[0];
+ var y = objpos[1];
+
+ // if the mouse pointer is within the bounds
+ // of the object, return true
+ return posx >= x
+ && posx <= (x + obj.offsetWidth - 1)
+ && posy >= y
+ && posy <= (y + obj.offsetHeight - 1);
+ };
+
+ photo_id = location.pathname.split('/')[3];
+ var img = document.getElementById('photoImgDiv' + photo_id);
+
+ GM_xmlhttpRequest({
+ method: 'GET',
+ url: 'http://api.flickr.com/services/rest/?method=flickr.photos.getExif'
+ +'&api_key=45d5d4b7dff9bc653c8eb3e73271c10c'
+ +'&format=json&nojsoncallback=1'
+ +'&photo_id=' + photo_id,
+
+ onload: function(responseDetails) {
+ var data = eval('(' + responseDetails.responseText + ')');
+ var exif_array = data.photo.exif;
+ var exif = new Array();
+ var rawexif = new Array();
+
+ for (i in exif_array) {
+ var e = exif_array[i];
+ var key = e.label;
+
+ rawexif[key] = e.raw._content;
+
+ if (e.clean) {
+ exif[key] = e.clean._content;
+ }
+ else if (!exif[key]) {
+ exif[key] = e.raw._content;
+ }
+ }
+
+ var exif_keys = ['Aperture', 'Exposure', 'ISO Speed', 'Focal Length'];
+
+ // Don't decorate unless there's some Exif data worth showing
+ var keep_going = exif['Model'] ? true : false;
+ for (i in exif_keys) {
+ if (exif[exif_keys[i]]) {
+ keep_going = true;
+ }
+ }
+ if (!keep_going) {
+ return;
+ }
+
+ // Main overlay element
+ var overlay = document.createElement('div');
+ overlay.setAttribute('id', 'FED_overlay');
+ overlay.style.position = 'absolute';
+ overlay.style.top = '0px';
+ overlay.style.left = '0px';
+ overlay.style.visibility = 'hidden';
+ document.body.appendChild(overlay);
+
+ // Add translucent background
+ var obg = document.createElement('div');
+ obg.setAttribute('id', 'FED_obg');
+ obg.style.backgroundColor = '#000';
+ obg.style.opacity = '0.75';
+ obg.style.MozBorderRadiusBottomright = '8px';
+ obg.style.position = 'absolute';
+ obg.style.top = '0px';
+ obg.style.left = '0px';
+ overlay.appendChild(obg);
+
+ // Add overlay text element
+ var ot = document.createElement('div');
+ ot.setAttribute('id', 'FED_ot');
+ ot.style.color = '#fff';
+ ot.style.fontSize = '11px';
+ ot.style.opacity = '1.0';
+ ot.style.position = 'absolute';
+ ot.style.top = '0px';
+ ot.style.left = '0px';
+ ot.style.fontFamily = '"Gill Sans", "Gill Sans MT", Tahoma, Helvetica, Arial';
+ ot.style.padding = '4px 8px 4px 4px';
+ ot.style.textAlign = 'left';
+ overlay.appendChild(ot);
+
+ var first = true;
+ var h = '<nobr>';
+ var flash_arrow_src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAACV0RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgTVggMjAwNId2rM8AAAAVdEVYdENyZWF0aW9uIFRpbWUAMjcvNS8wNyp/1lcAAABcSURBVHicjY7BDYAwDAOviM7SlWBCWCmfLNJH+DRSUxWKX5Fzsp3MjF4icuScL4Ba61lKuQG2P1AAR8g9/yevVtW4ocmT997we7nxDVpWfybOoAD2G0domjiDAB4i61DU2xUj8QAAAABJRU5ErkJggg==";
+
+ if (exif['Model'] || exif['Flash']) {
+ if (exif['Model']) {
+ if (exif['Make'] && !exif['Model'].match(new RegExp(exif['Make'], 'i'))) {
+ h += exif['Make'] + ' ' + exif['Model'];
+ }
+ else {
+ h += exif['Model'];
+ }
+ }
+ // LSB of Flash Exif param's raw value is
+ // 1: flash fired, 0: flash didn't fire
+ if (exif['Flash'] && rawexif['Flash'] & 1) {
+ h += '<img src="' + flash_arrow_src + '" hspace="10" />';
+ }
+ h += '</nobr><br/><nobr>';
+ }
+
+ for (i in exif_keys) {
+ var key = exif_keys[i];
+ if (exif[key]) {
+ if (first) { first = false;}
+ else { h += ', '; }
+ if (key == 'ISO Speed')
+ h += 'ISO ';
+ h += exif[key];
+ }
+ }
+ h += ' (<a style="color: #fff" href="http://www.flickr.com/photo_exif.gne?id=' + photo_id + '">more</a>)';
+ h += '</nobr>';
+ ot.innerHTML = h;
+
+ obg.style.width = ot.offsetWidth + 'px';
+ obg.style.height = ot.offsetHeight + 'px';
+
+ // Event listeners to display the overlay when we
+ // move over an image
+ function mouseMoveListener(e) {
+ if (overlay.style.visibility == 'hidden') {
+ FED_showOverlay(overlay, img);
+ }
+ // Only want this listener to fire once - to get the
+ // overlay displayed if the page loads while the mouse
+ // is moving over the image. Once it's fired we can
+ // remove it.
+ img.removeEventListener('mousemove', mouseMoveListener, false);
+ }
+
+ function mouseOutListener(e) {
+ // don't want to hide the overlay if the mouseout
+ // event happened because we moved into another
+ // element over the image, e.g. a note
+ // Do hide for flickr dialogs though (e.g. Add To Group
+ // drop-down) because otherwise overlay can obscure it
+ // according to correspondence on Flickr Hacks group.
+ if (FED_mouseInsideObj(e, img) && !FED_isInFlickrDialog(e.relatedTarget)) {
+ return;
+ }
+ overlay.style.visibility = 'hidden';
+ }
+
+ function mouseOverListener(e) {
+ if (overlay.style.visibility == 'hidden') {
+ FED_showOverlay(overlay, img);
+ }
+ }
+
+ img.addEventListener('mousemove', mouseMoveListener, false);
+ img.addEventListener('mouseout', mouseOutListener, false);
+ img.addEventListener('mouseover', mouseOverListener, false);
+ overlay.addEventListener('mouseout', mouseOutListener, false);
+ }
+ });
+}
diff --git a/googleimagerelinker.user.js b/googleimagerelinker.user.js
new file mode 100644
index 0000000..279e47d
--- /dev/null
+++ b/googleimagerelinker.user.js
@@ -0,0 +1,67 @@
+/*
+ Rewrite Google Image Search result
+ links to point directly at the images
+ Patrick Cavit, [email protected]
+ http://patcavit.com
+
+ Copy, use, modify, spread as you see fit.
+ Massive thanks go out to Eric Hamiter, this code
+ is just a quick modification of his extesion at
+ http://roachfiend.com/
+*/
+
+// ==UserScript==
+// @name Google Image Relinker
+// @namespace http://patcavit.com/greasemonkey
+// @description Rewrites Google Image Search links to point straight to the pictures
+// @include http://images.google.*/*
+// ==/UserScript==
+
+(function()
+{
+ function selectNodes(doc, context, xpath)
+ {
+ var nodes = doc.evaluate(xpath, context, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
+ var result = new Array( nodes.snapshotLength );
+
+ for (var x=0; x<result.length; x++)
+ {
+ result[x] = nodes.snapshotItem(x);
+ }
+
+ return result;
+ }
+
+ doc = window.document;
+
+ // Get a list of all A tags that have an href attribute containing the start and stop key strings.
+ var googLinks = selectNodes(doc, doc.body, "//A[contains(@href,'/imgres?imgurl=')][contains(@href,'&imgrefurl=')]");
+
+ for (var x=0; x<googLinks.length; x++)
+ {
+ // Capture the stuff between the start and stop key strings.
+ var gmatch = googLinks[x].href.match( /\/imgres\?imgurl\=(.*?)\&imgrefurl\=/ );
+
+ // If it matched successfully...
+ if (gmatch)
+ {
+ // Replace the link's href with the contents of the text captured in the regular expression's parenthesis.
+ googLinks[x].href = decodeURI(gmatch[1]);
+ googLinks[x].addEventListener("mouseover",
+ function(e) {
+ newImg = document.createElement("img");
+ newImg.src=this.href;
+ newImg.style.position="fixed";
+ newImg.style.zIndex='999';
+ newImg.style.top=0;
+ newImg.style.left=0;
+ document.body.appendChild(newImg);
+ x= function(){
+ document.body.removeChild(this);
+ };
+ newImg.addEventListener("click",x,false);
+ newImg.addEventListener("mouseout",x,false);
+ },false);
+ }
+ }
+})();
diff --git a/imagefapthumbresizer.user.js b/imagefapthumbresizer.user.js
new file mode 100644
index 0000000..84266da
--- /dev/null
+++ b/imagefapthumbresizer.user.js
@@ -0,0 +1,176 @@
+// ==UserScript==
+// @name ImageFap enhancer
+// @description enlarges thumbs, alternate gallery view, enhanced 'my clubs' page on ImageFap
+// @include *imagefap.com/*
+// ==/UserScript==
+// imageFapThumbSize.user.js
+
+ var visits = GM_getObject('visits',{});
+ GM_setValue('foo','bar');
+// Add jQuery
+ var GM_JQ = document.createElement('script');
+ var $;
+ var threads=8;
+ var piccontainer;
+ var preload = new Array();
+ var pics = new Array();
+ var gallerypage=window.location.href.match(/\/gallery\/|\/gallery\.php\?gid/)?true:false;
+ var myclubspage=window.location.href.match(/\/clubs\/myclubs\.php/)?true:false;
+ var clubspage=window.location.href.match(/\/clubs\/index\.php\?cid=(.*)/);
+ if( clubspage )
+ clubspage=clubspage[1];
+ GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js';
+ GM_JQ.type = 'text/javascript';
+ document.getElementsByTagName('body')[0].appendChild(GM_JQ);
+
+// Check if jQuery's loaded
+ function GM_wait() {
+ if(typeof unsafeWindow.jQuery == 'undefined') { console.log("waiting for jquery"); window.setTimeout(GM_wait,100); }
+ else { $ = unsafeWindow.jQuery.noConflict(); window.setTimeout(payload,100); }
+ }
+ GM_wait();
+ function showimg( pic, replace ) {
+ piccontainer.show();
+ if( gallerypage || replace ){
+ piccontainer.empty();
+ }
+// $('<img src="'+pic.url+'">')
+ $('[src='+pic.url+']').clone()
+ .appendTo(piccontainer)
+ .css({width:'',left:'',maxHeight:'100%',maxWidth:'100%',marginRight:'255px'})
+ .click(function(){
+ $(this).remove();
+ piccontainer.hide();
+ });
+ }
+
+
+ function payload() {
+ console.log('payload started');
+ resize_thumbs();
+ if( gallerypage )
+ create_alternate_gallery();
+ if( myclubspage )
+ enhance_myclubs();
+ if( clubspage )
+ save_clubvisit( clubspage );
+ }
+ function resize_thumbs() {
+ $('img').each(function () {
+ var s = this.src.search(/\/images\/mini\//);
+ if( s != -1 ) {
+ $(this).replaceWith('<img border="0" src="'+this.src.replace(/images\/mini\//, "images/thumb/")+'">');
+ }
+ });
+ }
+ function save_clubvisit( clubid ) {
+ GM_log('club '+clubid+' visited');
+ dt=new Date();
+ visits['club_'+clubid] = dt.getTime();
+ GM_setObject('visits', visits);
+ }
+ function create_alternate_gallery() {
+ var numfound=0;
+ favlink = $('#gallery').next('a').eq(0);
+ profileLinks = $('#menubar').appendTo('body').append(favlink);
+ thumbholder = $('<div style="position:static; float:right; width: 255px; height: 100%; overflow-x: hidden; overflow-y:scroll"></div>')
+ .appendTo($('body'));
+ thumbholder.css({marginTop:-($('#menubar').height()+2)});
+
+ piccontainer = $('<div style="position:relative;;float:left;255px;height:100%;"></div>').appendTo($('body'));
+ piccontainer.hide();
+ piccontainer.css({width:$('#menubar').width()-255});
+ piccontainer.css({marginTop:-($('#menubar').height()+2)});
+ piccontainer.bind('DOMMouseScroll',function(e){
+ var idx = 0;
+ $.each(pics,function(i,item){
+ lookfor = $('img',piccontainer).attr('src');
+ if( item.url == lookfor ) idx=i;
+ });
+
+ if( e.detail > 0 && idx+1 < pics.length)
+ showimg( pics[idx+1]);
+
+ if( e.detail < 0 && idx-1 >= 0 )
+ showimg( pics[idx-1] );
+ });
+
+ $('a[href*=image.php?id=]').each(function(){
+ $(this).appendTo(thumbholder);
+ var pic = $(this).find('img').eq(0);
+ if( pic.attr && pic.attr('src') ) {
+ var picurl = pic.attr('src').replace(/thumb/,"full" );
+ var picobj = {pic:pic,url:picurl};
+ preload.push(picobj);
+ pics.push(picobj);
+ pic.css({maxWidth:'120px',maxHeight:'120px'});
+ $(this).mouseover(function(){ showimg(picobj); return false; });
+ numfound++;
+ }
+ });
+ $('body > center:first-child').remove();
+ if( numfound > 0 ) {
+ infodiv=$('<div>converted '+numfound+' links</div>')
+ .appendTo('body')
+ .css({position:'fixed',bottom:0,right:0,color:'#aaa',background:'#fff',padding:'5px',margin:'5px',border:'1px solid #88f'});
+
+ var prev = false;
+ loadfunction = function() {
+ try{
+ if( $(this).data('prev') ) {
+ $(this).data('prev').pic.css({outline:'3px solid #080'});
+ }
+ if(preload[0]) {
+ infodiv.empty().append(preload.length+' left');
+ var next=preload.shift();
+ next.pic.css({outline:'3px dotted #f00'});
+ $(this).clone(true).appendTo('body').data('prev',next).attr('src',next.url);
+ } else {
+ infodiv.empty().append('done.');
+ setTimeout(function(){infodiv.hide();},2000);
+ }
+ } catch(e){};
+ }
+ try {
+ var img = $('<img>').css({'position':'absolute','left':'-5000px','width':'10px'});
+ img.bind('load', loadfunction );
+ for( var i=0; i < threads; i++ )
+ setTimeout(function(){img.clone(true).trigger('load');},i*200);
+ } catch(e){ console.log(e); }
+ }
+ }
+ function enhance_myclubs() {
+ GM_log('i has myclubs');
+ $("td[width='100%'][valign='top'] table").each(function(){
+ var glink=$("tr:nth-child(2) ;a[href*='clubs/index.php?cid=']",this).attr('href');
+ if (glink) {
+ var gid=glink.match(/cid=(.*)/)[1];
+ var td=$("tr:nth-child(2) td:nth-child(2)",this);
+ var display=$("tr:nth-child(2) td:nth-child(3)",this);
+ td.append('<div id="club_'+gid+'">');
+ var gdiv=$('#club_'+gid);
+ gdiv.hide().load(glink+' font span',{},function(){
+ $('span',this).each(function(){
+ if( gdate=this.innerHTML.match(/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/) )
+ {
+ var clubid = $(this).parent().attr('id');
+ lastmod= new Date(gdate[1], gdate[2], gdate[3],gdate[4],gdate[5],gdate[6]);
+ console.log( clubid+' lastvisit: '+visits['club_'+clubid] );
+ console.log( clubid+' lastmod: '+lastmod);
+ $(this).parent().parent().next().append(lastmod.toLocaleString());
+ return false;
+ }
+ });
+ });
+ }
+ });
+ }
+function GM_getObject(key, defaultValue) {
+ return (new Function('', 'return (' + GM_getValue(key, 'void 0') + ')'))() || defaultValue;
+}
+
+function GM_setObject(key, value) {
+ GM_setValue(key, value.toSource());
+}
+
+
diff --git a/imagefapthumbresizer_before_ajax.user.js b/imagefapthumbresizer_before_ajax.user.js
new file mode 100644
index 0000000..13b4226
--- /dev/null
+++ b/imagefapthumbresizer_before_ajax.user.js
@@ -0,0 +1,99 @@
+// ==UserScript==
+// @name ImageFap Thumb resizer
+// @namespace
+// @description Shows big images when hovering over mini-Thumbs on ImageFap
+// @include *imagefap.com/*
+// ==/UserScript==
+// imageFapThumbSize.user.js
+// Add jQuery
+ var GM_JQ = document.createElement('script');
+ GM_JQ.src = 'http://127.0.0.1/jquery-latest.js';
+ GM_JQ.type = 'text/javascript';
+ document.getElementsByTagName('head')[0].appendChild(GM_JQ);
+
+// Check if jQuery's loaded
+ function GM_wait() {
+ if(typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(GM_wait,500); }
+ else { $ = unsafeWindow.jQuery; letsJQuery(); }
+ }
+ GM_wait();
+// All your GM code must be inside this function
+ function letsJQuery() {
+ $(function() {
+ var imgList = document.getElementsByTagName("img");
+ var opened;
+ $('<div id="gm_counter">opener ready.</div>').appendTo("body");
+ $('#gm_counter').css( {
+ position:'fixed',
+ top:0,right:0,zIndex:999,
+ border:"2px dashed blue",
+ padding:"2px",
+ cursor:"-moz-grab",
+ background:"#ddd"});
+ showImg = function() {
+ $('.gm_newImage:first').show();
+ $('#gm_counter').unbind('click').bind('click',removeImg);
+ $('#gm_counter').empty().append("remove all");
+ console.log("showed " +$('.gm_newImage').length + " images");
+ };
+ removeImg = function() {
+ if( $('.gm_newImage').length > 0 ) {
+ $('.gm_newImage').remove();
+ console.log( 'all images removed' );
+ }
+
+ $('#gm_counter').unbind('click').bind('click',showImg);
+ $('#gm_counter').empty().append("ready");
+ }
+ $('#gm_counter').bind('click',showImg)
+ for( i=0; i < imgList.length; i++) {
+ var imgName = imgList[i].src;
+ var s = imgName.search(/\/images\/mini|thumb\//);
+ if( s != -1) {
+
+ ow=imgList[i].width;
+ imgList[i].addEventListener("mouseover",
+ function(e){
+ $(this).css("border","2px solid darkGray");
+ $(this).css("padding","2px");
+
+ newImg = document.createElement("img");
+ newSrc = this.src.replace(/images\/mini|thumb\//, "full/");
+ newImg.src = newSrc;
+ newImg.style.maxWidth=window.innerWidth;
+ newImg.style.maxHeight = window.innerHeight;
+ newImg.style.position="fixed";
+ newImg.style.zIndex='1';
+ newImg.style.top=0;
+ newImg.style.left=0;
+ newImg.style.display='none';
+ newImg.className='gm_newImage';
+
+ document.body.appendChild(newImg);
+ var ref = this;
+ fn_error = function() {
+ $(ref).css("border","2px solid red");
+ $('#gm_counter').css("background","#fdd");
+ $(this).remove();
+ $('#gm_counter').empty().append("show " + $('.gm_newImage').length);
+ };
+ fn_load = function() {
+ $(ref).css("border","2px dotted green");
+ };
+ fn_click = function() {
+ $(this).remove();
+ $('.gm_newImage:first').show();
+ };
+ newImg.addEventListener("click",fn_click,false);
+ newImg.addEventListener("load",fn_load,true);
+ newImg.addEventListener("error",fn_error,false);
+ $('#gm_counter').empty().append("show " + $('.gm_newImage').length);
+ $('#gm_counter').unbind('click').bind('click',showImg);
+ },false);
+
+ }
+ }
+ return;
+ });
+};
+
diff --git a/jquery-latest.js b/jquery-latest.js
new file mode 100644
index 0000000..428d42d
--- /dev/null
+++ b/jquery-latest.js
@@ -0,0 +1,2344 @@
+// prevent execution of jQuery if included more than once
+if(typeof window.jQuery == "undefined") {
+/*
+ * jQuery 1.1.3.1 - New Wave Javascript
+ *
+ * Copyright (c) 2007 John Resig (jquery.com)
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * $Date: 2007-07-05 00:43:24 -0400 (Thu, 05 Jul 2007) $
+ * $Rev: 2243 $
+ */
+
+// Global undefined variable
+window.undefined = window.undefined;
+var jQuery = function(a,c) {
+ // If the context is global, return a new object
+ if ( window == this || !this.init )
+ return new jQuery(a,c);
+
+ return this.init(a,c);
+};
+
+// Map over the $ in case of overwrite
+if ( typeof $ != "undefined" )
+ jQuery._$ = $;
+
+// Map the jQuery namespace to the '$' one
+var $ = jQuery;
+
+jQuery.fn = jQuery.prototype = {
+ init: function(a,c) {
+ // Make sure that a selection was provided
+ a = a || document;
+
+ // HANDLE: $(function)
+ // Shortcut for document ready
+ if ( jQuery.isFunction(a) )
+ return new jQuery(document)[ jQuery.fn.ready ? "ready" : "load" ]( a );
+
+ // Handle HTML strings
+ if ( typeof a == "string" ) {
+ // HANDLE: $(html) -> $(array)
+ var m = /^[^<]*(<(.|\s)+>)[^>]*$/.exec(a);
+ if ( m )
+ a = jQuery.clean( [ m[1] ] );
+
+ // HANDLE: $(expr)
+ else
+ return new jQuery( c ).find( a );
+ }
+
+ return this.setArray(
+ // HANDLE: $(array)
+ a.constructor == Array && a ||
+
+ // HANDLE: $(arraylike)
+ // Watch for when an array-like object is passed as the selector
+ (a.jquery || a.length && a != window && !a.nodeType && a[0] != undefined && a[0].nodeType) && jQuery.makeArray( a ) ||
+
+ // HANDLE: $(*)
+ [ a ] );
+ },
+ jquery: "1.1.3.1",
+
+ size: function() {
+ return this.length;
+ },
+
+ length: 0,
+
+ get: function( num ) {
+ return num == undefined ?
+
+ // Return a 'clean' array
+ jQuery.makeArray( this ) :
+
+ // Return just the object
+ this[num];
+ },
+ pushStack: function( a ) {
+ var ret = jQuery(a);
+ ret.prevObject = this;
+ return ret;
+ },
+ setArray: function( a ) {
+ this.length = 0;
+ [].push.apply( this, a );
+ return this;
+ },
+ each: function( fn, args ) {
+ return jQuery.each( this, fn, args );
+ },
+ index: function( obj ) {
+ var pos = -1;
+ this.each(function(i){
+ if ( this == obj ) pos = i;
+ });
+ return pos;
+ },
+
+ attr: function( key, value, type ) {
+ var obj = key;
+
+ // Look for the case where we're accessing a style value
+ if ( key.constructor == String )
+ if ( value == undefined )
+ return this.length && jQuery[ type || "attr" ]( this[0], key ) || undefined;
+ else {
+ obj = {};
+ obj[ key ] = value;
+ }
+
+ // Check to see if we're setting style values
+ return this.each(function(index){
+ // Set all the styles
+ for ( var prop in obj )
+ jQuery.attr(
+ type ? this.style : this,
+ prop, jQuery.prop(this, obj[prop], type, index, prop)
+ );
+ });
+ },
+
+ css: function( key, value ) {
+ return this.attr( key, value, "curCSS" );
+ },
+
+ text: function(e) {
+ if ( typeof e == "string" )
+ return this.empty().append( document.createTextNode( e ) );
+
+ var t = "";
+ jQuery.each( e || this, function(){
+ jQuery.each( this.childNodes, function(){
+ if ( this.nodeType != 8 )
+ t += this.nodeType != 1 ?
+ this.nodeValue : jQuery.fn.text([ this ]);
+ });
+ });
+ return t;
+ },
+
+ wrap: function() {
+ // The elements to wrap the target around
+ var a, args = arguments;
+
+ // Wrap each of the matched elements individually
+ return this.each(function(){
+ if ( !a )
+ a = jQuery.clean(args, this.ownerDocument);
+
+ // Clone the structure that we're using to wrap
+ var b = a[0].cloneNode(true);
+
+ // Insert it before the element to be wrapped
+ this.parentNode.insertBefore( b, this );
+
+ // Find the deepest point in the wrap structure
+ while ( b.firstChild )
+ b = b.firstChild;
+
+ // Move the matched element to within the wrap structure
+ b.appendChild( this );
+ });
+ },
+ append: function() {
+ return this.domManip(arguments, true, 1, function(a){
+ this.appendChild( a );
+ });
+ },
+ prepend: function() {
+ return this.domManip(arguments, true, -1, function(a){
+ this.insertBefore( a, this.firstChild );
+ });
+ },
+ before: function() {
+ return this.domManip(arguments, false, 1, function(a){
+ this.parentNode.insertBefore( a, this );
+ });
+ },
+ after: function() {
+ return this.domManip(arguments, false, -1, function(a){
+ this.parentNode.insertBefore( a, this.nextSibling );
+ });
+ },
+ end: function() {
+ return this.prevObject || jQuery([]);
+ },
+ find: function(t) {
+ var data = jQuery.map(this, function(a){ return jQuery.find(t,a); });
+ return this.pushStack( /[^+>] [^+>]/.test( t ) || t.indexOf("..") > -1 ?
+ jQuery.unique( data ) : data );
+ },
+ clone: function(deep) {
+ // Need to remove events on the element and its descendants
+ var $this = this.add(this.find("*"));
+ $this.each(function() {
+ this._$events = {};
+ for (var type in this.$events)
+ this._$events[type] = jQuery.extend({},this.$events[type]);
+ }).unbind();
+
+ // Do the clone
+ var r = this.pushStack( jQuery.map( this, function(a){
+ return a.cloneNode( deep != undefined ? deep : true );
+ }) );
+
+ // Add the events back to the original and its descendants
+ $this.each(function() {
+ var events = this._$events;
+ for (var type in events)
+ for (var handler in events[type])
+ jQuery.event.add(this, type, events[type][handler], events[type][handler].data);
+ this._$events = null;
+ });
+
+ // Return the cloned set
+ return r;
+ },
+
+ filter: function(t) {
+ return this.pushStack(
+ jQuery.isFunction( t ) &&
+ jQuery.grep(this, function(el, index){
+ return t.apply(el, [index])
+ }) ||
+
+ jQuery.multiFilter(t,this) );
+ },
+
+ not: function(t) {
+ return this.pushStack(
+ t.constructor == String &&
+ jQuery.multiFilter(t, this, true) ||
+
+ jQuery.grep(this, function(a) {
+ return ( t.constructor == Array || t.jquery )
+ ? jQuery.inArray( a, t ) < 0
+ : a != t;
+ })
+ );
+ },
+
+ add: function(t) {
+ return this.pushStack( jQuery.merge(
+ this.get(),
+ t.constructor == String ?
+ jQuery(t).get() :
+ t.length != undefined && (!t.nodeName || t.nodeName == "FORM") ?
+ t : [t] )
+ );
+ },
+ is: function(expr) {
+ return expr ? jQuery.multiFilter(expr,this).length > 0 : false;
+ },
+
+ val: function( val ) {
+ return val == undefined ?
+ ( this.length ? this[0].value : null ) :
+ this.attr( "value", val );
+ },
+
+ html: function( val ) {
+ return val == undefined ?
+ ( this.length ? this[0].innerHTML : null ) :
+ this.empty().append( val );
+ },
+ domManip: function(args, table, dir, fn){
+ var clone = this.length > 1, a;
+
+ return this.each(function(){
+ if ( !a ) {
+ a = jQuery.clean(args, this.ownerDocument);
+ if ( dir < 0 )
+ a.reverse();
+ }
+
+ var obj = this;
+
+ if ( table && jQuery.nodeName(this, "table") && jQuery.nodeName(a[0], "tr") )
+ obj = this.getElementsByTagName("tbody")[0] || this.appendChild(document.createElement("tbody"));
+
+ jQuery.each( a, function(){
+ fn.apply( obj, [ clone ? this.cloneNode(true) : this ] );
+ });
+
+ });
+ }
+};
+
+jQuery.extend = jQuery.fn.extend = function() {
+ // copy reference to target object
+ var target = arguments[0], a = 1;
+
+ // extend jQuery itself if only one argument is passed
+ if ( arguments.length == 1 ) {
+ target = this;
+ a = 0;
+ }
+ var prop;
+ while ( (prop = arguments[a++]) != null )
+ // Extend the base object
+ for ( var i in prop ) target[i] = prop[i];
+
+ // Return the modified object
+ return target;
+};
+
+jQuery.extend({
+ noConflict: function() {
+ if ( jQuery._$ )
+ $ = jQuery._$;
+ return jQuery;
+ },
+
+ // This may seem like some crazy code, but trust me when I say that this
+ // is the only cross-browser way to do this. --John
+ isFunction: function( fn ) {
+ return !!fn && typeof fn != "string" && !fn.nodeName &&
+ fn.constructor != Array && /function/i.test( fn + "" );
+ },
+
+ // check if an element is in a XML document
+ isXMLDoc: function(elem) {
+ return elem.tagName && elem.ownerDocument && !elem.ownerDocument.body;
+ },
+
+ nodeName: function( elem, name ) {
+ return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
+ },
+ // args is for internal usage only
+ each: function( obj, fn, args ) {
+ if ( obj.length == undefined )
+ for ( var i in obj )
+ fn.apply( obj[i], args || [i, obj[i]] );
+ else
+ for ( var i = 0, ol = obj.length; i < ol; i++ )
+ if ( fn.apply( obj[i], args || [i, obj[i]] ) === false ) break;
+ return obj;
+ },
+
+ prop: function(elem, value, type, index, prop){
+ // Handle executable functions
+ if ( jQuery.isFunction( value ) )
+ value = value.call( elem, [index] );
+
+ // exclude the following css properties to add px
+ var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i;
+
+ // Handle passing in a number to a CSS property
+ return value && value.constructor == Number && type == "curCSS" && !exclude.test(prop) ?
+ value + "px" :
+ value;
+ },
+
+ className: {
+ // internal only, use addClass("class")
+ add: function( elem, c ){
+ jQuery.each( c.split(/\s+/), function(i, cur){
+ if ( !jQuery.className.has( elem.className, cur ) )
+ elem.className += ( elem.className ? " " : "" ) + cur;
+ });
+ },
+
+ // internal only, use removeClass("class")
+ remove: function( elem, c ){
+ elem.className = c != undefined ?
+ jQuery.grep( elem.className.split(/\s+/), function(cur){
+ return !jQuery.className.has( c, cur );
+ }).join(" ") : "";
+ },
+
+ // internal only, use is(".class")
+ has: function( t, c ) {
+ return jQuery.inArray( c, (t.className || t).toString().split(/\s+/) ) > -1;
+ }
+ },
+ swap: function(e,o,f) {
+ for ( var i in o ) {
+ e.style["old"+i] = e.style[i];
+ e.style[i] = o[i];
+ }
+ f.apply( e, [] );
+ for ( var i in o )
+ e.style[i] = e.style["old"+i];
+ },
+
+ css: function(e,p) {
+ if ( p == "height" || p == "width" ) {
+ var old = {}, oHeight, oWidth, d = ["Top","Bottom","Right","Left"];
+
+ jQuery.each( d, function(){
+ old["padding" + this] = 0;
+ old["border" + this + "Width"] = 0;
+ });
+
+ jQuery.swap( e, old, function() {
+ if ( jQuery(e).is(':visible') ) {
+ oHeight = e.offsetHeight;
+ oWidth = e.offsetWidth;
+ } else {
+ e = jQuery(e.cloneNode(true))
+ .find(":radio").removeAttr("checked").end()
+ .css({
+ visibility: "hidden", position: "absolute", display: "block", right: "0", left: "0"
+ }).appendTo(e.parentNode)[0];
+
+ var parPos = jQuery.css(e.parentNode,"position") || "static";
+ if ( parPos == "static" )
+ e.parentNode.style.position = "relative";
+
+ oHeight = e.clientHeight;
+ oWidth = e.clientWidth;
+
+ if ( parPos == "static" )
+ e.parentNode.style.position = "static";
+
+ e.parentNode.removeChild(e);
+ }
+ });
+
+ return p == "height" ? oHeight : oWidth;
+ }
+
+ return jQuery.curCSS( e, p );
+ },
+
+ curCSS: function(elem, prop, force) {
+ var ret;
+
+ if (prop == "opacity" && jQuery.browser.msie) {
+ ret = jQuery.attr(elem.style, "opacity");
+ return ret == "" ? "1" : ret;
+ }
+
+ if (prop.match(/float/i))
+ prop = jQuery.styleFloat;
+
+ if (!force && elem.style[prop])
+ ret = elem.style[prop];
+
+ else if (document.defaultView && document.defaultView.getComputedStyle) {
+
+ if (prop.match(/float/i))
+ prop = "float";
+
+ prop = prop.replace(/([A-Z])/g,"-$1").toLowerCase();
+ var cur = document.defaultView.getComputedStyle(elem, null);
+
+ if ( cur )
+ ret = cur.getPropertyValue(prop);
+ else if ( prop == "display" )
+ ret = "none";
+ else
+ jQuery.swap(elem, { display: "block" }, function() {
+ var c = document.defaultView.getComputedStyle(this, "");
+ ret = c && c.getPropertyValue(prop) || "";
+ });
+
+ } else if (elem.currentStyle) {
+ var newProp = prop.replace(/\-(\w)/g,function(m,c){return c.toUpperCase();});
+ ret = elem.currentStyle[prop] || elem.currentStyle[newProp];
+ }
+
+ return ret;
+ },
+
+ clean: function(a, doc) {
+ var r = [];
+ doc = doc || document;
+
+ jQuery.each( a, function(i,arg){
+ if ( !arg ) return;
+
+ if ( arg.constructor == Number )
+ arg = arg.toString();
+
+ // Convert html string into DOM nodes
+ if ( typeof arg == "string" ) {
+ // Trim whitespace, otherwise indexOf won't work as expected
+ var s = jQuery.trim(arg).toLowerCase(), div = doc.createElement("div"), tb = [];
+
+ var wrap =
+ // option or optgroup
+ !s.indexOf("<opt") &&
+ [1, "<select>", "</select>"] ||
+
+ !s.indexOf("<leg") &&
+ [1, "<fieldset>", "</fieldset>"] ||
+
+ (!s.indexOf("<thead") || !s.indexOf("<tbody") || !s.indexOf("<tfoot") || !s.indexOf("<colg")) &&
+ [1, "<table>", "</table>"] ||
+
+ !s.indexOf("<tr") &&
+ [2, "<table><tbody>", "</tbody></table>"] ||
+
+ // <thead> matched above
+ (!s.indexOf("<td") || !s.indexOf("<th")) &&
+ [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
+
+ !s.indexOf("<col") &&
+ [2, "<table><colgroup>", "</colgroup></table>"] ||
+
+ [0,"",""];
+
+ // Go to html and back, then peel off extra wrappers
+ div.innerHTML = wrap[1] + arg + wrap[2];
+
+ // Move to the right depth
+ while ( wrap[0]-- )
+ div = div.firstChild;
+
+ // Remove IE's autoinserted <tbody> from table fragments
+ if ( jQuery.browser.msie ) {
+
+ // String was a <table>, *may* have spurious <tbody>
+ if ( !s.indexOf("<table") && s.indexOf("<tbody") < 0 )
+ tb = div.firstChild && div.firstChild.childNodes;
+
+ // String was a bare <thead> or <tfoot>
+ else if ( wrap[1] == "<table>" && s.indexOf("<tbody") < 0 )
+ tb = div.childNodes;
+
+ for ( var n = tb.length-1; n >= 0 ; --n )
+ if ( jQuery.nodeName(tb[n], "tbody") && !tb[n].childNodes.length )
+ tb[n].parentNode.removeChild(tb[n]);
+
+ }
+
+ arg = jQuery.makeArray( div.childNodes );
+ }
+
+ if ( 0 === arg.length && (!jQuery.nodeName(arg, "form") && !jQuery.nodeName(arg, "select")) )
+ return;
+
+ if ( arg[0] == undefined || jQuery.nodeName(arg, "form") || arg.options )
+ r.push( arg );
+ else
+ r = jQuery.merge( r, arg );
+
+ });
+
+ return r;
+ },
+
+ attr: function(elem, name, value){
+ var fix = jQuery.isXMLDoc(elem) ? {} : jQuery.props;
+
+ // Certain attributes only work when accessed via the old DOM 0 way
+ if ( fix[name] ) {
+ if ( value != undefined ) elem[fix[name]] = value;
+ return elem[fix[name]];
+
+ } else if ( value == undefined && jQuery.browser.msie && jQuery.nodeName(elem, "form") && (name == "action" || name == "method") )
+ return elem.getAttributeNode(name).nodeValue;
+
+ // IE elem.getAttribute passes even for style
+ else if ( elem.tagName ) {
+
+
+ if ( value != undefined ) elem.setAttribute( name, value );
+ if ( jQuery.browser.msie && /href|src/.test(name) && !jQuery.isXMLDoc(elem) )
+ return elem.getAttribute( name, 2 );
+ return elem.getAttribute( name );
+
+ // elem is actually elem.style ... set the style
+ } else {
+ // IE actually uses filters for opacity
+ if ( name == "opacity" && jQuery.browser.msie ) {
+ if ( value != undefined ) {
+ // IE has trouble with opacity if it does not have layout
+ // Force it by setting the zoom level
+ elem.zoom = 1;
+
+ // Set the alpha filter to set the opacity
+ elem.filter = (elem.filter || "").replace(/alpha\([^)]*\)/,"") +
+ (parseFloat(value).toString() == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
+ }
+
+ return elem.filter ?
+ (parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100).toString() : "";
+ }
+ name = name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();});
+ if ( value != undefined ) elem[name] = value;
+ return elem[name];
+ }
+ },
+ trim: function(t){
+ return t.replace(/^\s+|\s+$/g, "");
+ },
+
+ makeArray: function( a ) {
+ var r = [];
+
+ // Need to use typeof to fight Safari childNodes crashes
+ if ( typeof a != "array" )
+ for ( var i = 0, al = a.length; i < al; i++ )
+ r.push( a[i] );
+ else
+ r = a.slice( 0 );
+
+ return r;
+ },
+
+ inArray: function( b, a ) {
+ for ( var i = 0, al = a.length; i < al; i++ )
+ if ( a[i] == b )
+ return i;
+ return -1;
+ },
+ merge: function(first, second) {
+ // We have to loop this way because IE & Opera overwrite the length
+ // expando of getElementsByTagName
+ for ( var i = 0; second[i]; i++ )
+ first.push(second[i]);
+ return first;
+ },
+ unique: function(first) {
+ var r = [], num = jQuery.mergeNum++;
+
+ for ( var i = 0, fl = first.length; i < fl; i++ )
+ if ( num != first[i].mergeNum ) {
+ first[i].mergeNum = num;
+ r.push(first[i]);
+ }
+
+ return r;
+ },
+
+ mergeNum: 0,
+ grep: function(elems, fn, inv) {
+ // If a string is passed in for the function, make a function
+ // for it (a handy shortcut)
+ if ( typeof fn == "string" )
+ fn = new Function("a","i","return " + fn);
+
+ var result = [];
+
+ // Go through the array, only saving the items
+ // that pass the validator function
+ for ( var i = 0, el = elems.length; i < el; i++ )
+ if ( !inv && fn(elems[i],i) || inv && !fn(elems[i],i) )
+ result.push( elems[i] );
+
+ return result;
+ },
+ map: function(elems, fn) {
+ // If a string is passed in for the function, make a function
+ // for it (a handy shortcut)
+ if ( typeof fn == "string" )
+ fn = new Function("a","return " + fn);
+
+ var result = [];
+
+ // Go through the array, translating each of the items to their
+ // new value (or values).
+ for ( var i = 0, el = elems.length; i < el; i++ ) {
+ var val = fn(elems[i],i);
+
+ if ( val !== null && val != undefined ) {
+ if ( val.constructor != Array ) val = [val];
+ result = result.concat( val );
+ }
+ }
+
+ return result;
+ }
+});
+
+/*
+ * Whether the W3C compliant box model is being used.
+ *
+ * @property
+ * @name $.boxModel
+ * @type Boolean
+ * @cat JavaScript
+ */
+new function() {
+ var b = navigator.userAgent.toLowerCase();
+
+ // Figure out what browser is being used
+ jQuery.browser = {
+ version: (b.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
+ safari: /webkit/.test(b),
+ opera: /opera/.test(b),
+ msie: /msie/.test(b) && !/opera/.test(b),
+ mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b)
+ };
+
+ // Check to see if the W3C box model is being used
+ jQuery.boxModel = !jQuery.browser.msie || document.compatMode == "CSS1Compat";
+
+ jQuery.styleFloat = jQuery.browser.msie ? "styleFloat" : "cssFloat",
+
+ jQuery.props = {
+ "for": "htmlFor",
+ "class": "className",
+ "float": jQuery.styleFloat,
+ cssFloat: jQuery.styleFloat,
+ styleFloat: jQuery.styleFloat,
+ innerHTML: "innerHTML",
+ className: "className",
+ value: "value",
+ disabled: "disabled",
+ checked: "checked",
+ readonly: "readOnly",
+ selected: "selected",
+ maxlength: "maxLength"
+ };
+};
+
+jQuery.each({
+ parent: "a.parentNode",
+ parents: "jQuery.parents(a)",
+ next: "jQuery.nth(a,2,'nextSibling')",
+ prev: "jQuery.nth(a,2,'previousSibling')",
+ siblings: "jQuery.sibling(a.parentNode.firstChild,a)",
+ children: "jQuery.sibling(a.firstChild)"
+}, function(i,n){
+ jQuery.fn[ i ] = function(a) {
+ var ret = jQuery.map(this,n);
+ if ( a && typeof a == "string" )
+ ret = jQuery.multiFilter(a,ret);
+ return this.pushStack( ret );
+ };
+});
+
+jQuery.each({
+ appendTo: "append",
+ prependTo: "prepend",
+ insertBefore: "before",
+ insertAfter: "after"
+}, function(i,n){
+ jQuery.fn[ i ] = function(){
+ var a = arguments;
+ return this.each(function(){
+ for ( var j = 0, al = a.length; j < al; j++ )
+ jQuery(a[j])[n]( this );
+ });
+ };
+});
+
+jQuery.each( {
+ removeAttr: function( key ) {
+ jQuery.attr( this, key, "" );
+ this.removeAttribute( key );
+ },
+ addClass: function(c){
+ jQuery.className.add(this,c);
+ },
+ removeClass: function(c){
+ jQuery.className.remove(this,c);
+ },
+ toggleClass: function( c ){
+ jQuery.className[ jQuery.className.has(this,c) ? "remove" : "add" ](this, c);
+ },
+ remove: function(a){
+ if ( !a || jQuery.filter( a, [this] ).r.length )
+ this.parentNode.removeChild( this );
+ },
+ empty: function() {
+ while ( this.firstChild )
+ this.removeChild( this.firstChild );
+ }
+}, function(i,n){
+ jQuery.fn[ i ] = function() {
+ return this.each( n, arguments );
+ };
+});
+
+jQuery.each( [ "eq", "lt", "gt", "contains" ], function(i,n){
+ jQuery.fn[ n ] = function(num,fn) {
+ return this.filter( ":" + n + "(" + num + ")", fn );
+ };
+});
+
+jQuery.each( [ "height", "width" ], function(i,n){
+ jQuery.fn[ n ] = function(h) {
+ return h == undefined ?
+ ( this.length ? jQuery.css( this[0], n ) : null ) :
+ this.css( n, h.constructor == String ? h : h + "px" );
+ };
+});
+jQuery.extend({
+ expr: {
+ "": "m[2]=='*'||jQuery.nodeName(a,m[2])",
+ "#": "a.getAttribute('id')==m[2]",
+ ":": {
+ // Position Checks
+ lt: "i<m[3]-0",
+ gt: "i>m[3]-0",
+ nth: "m[3]-0==i",
+ eq: "m[3]-0==i",
+ first: "i==0",
+ last: "i==r.length-1",
+ even: "i%2==0",
+ odd: "i%2",
+
+ // Child Checks
+ "first-child": "a.parentNode.getElementsByTagName('*')[0]==a",
+ "last-child": "jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a",
+ "only-child": "!jQuery.nth(a.parentNode.lastChild,2,'previousSibling')",
+
+ // Parent Checks
+ parent: "a.firstChild",
+ empty: "!a.firstChild",
+
+ // Text Check
+ contains: "(a.textContent||a.innerText||'').indexOf(m[3])>=0",
+
+ // Visibility
+ visible: '"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"',
+ hidden: '"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden"',
+
+ // Form attributes
+ enabled: "!a.disabled",
+ disabled: "a.disabled",
+ checked: "a.checked",
+ selected: "a.selected||jQuery.attr(a,'selected')",
+
+ // Form elements
+ text: "'text'==a.type",
+ radio: "'radio'==a.type",
+ checkbox: "'checkbox'==a.type",
+ file: "'file'==a.type",
+ password: "'password'==a.type",
+ submit: "'submit'==a.type",
+ image: "'image'==a.type",
+ reset: "'reset'==a.type",
+ button: '"button"==a.type||jQuery.nodeName(a,"button")',
+ input: "/input|select|textarea|button/i.test(a.nodeName)"
+ },
+ "[": "jQuery.find(m[2],a).length"
+ },
+
+ // The regular expressions that power the parsing engine
+ parse: [
+ // Match: [@value='test'], [@foo]
+ /^\[ *(@)([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,
+
+ // Match: [div], [div p]
+ /^(\[)\s*(.*?(\[.*?\])?[^[]*?)\s*\]/,
+
+ // Match: :contains('foo')
+ /^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,
+
+ // Match: :even, :last-chlid, #id, .class
+ new RegExp("^([:.#]*)(" +
+ ( jQuery.chars = jQuery.browser.safari && jQuery.browser.version < "3.0.0" ? "\\w" : "(?:[\\w\u0128-\uFFFF*_-]|\\\\.)" ) + "+)")
+ ],
+
+ multiFilter: function( expr, elems, not ) {
+ var old, cur = [];
+
+ while ( expr && expr != old ) {
+ old = expr;
+ var f = jQuery.filter( expr, elems, not );
+ expr = f.t.replace(/^\s*,\s*/, "" );
+ cur = not ? elems = f.r : jQuery.merge( cur, f.r );
+ }
+
+ return cur;
+ },
+ find: function( t, context ) {
+ // Quickly handle non-string expressions
+ if ( typeof t != "string" )
+ return [ t ];
+
+ // Make sure that the context is a DOM Element
+ if ( context && !context.nodeType )
+ context = null;
+
+ // Set the correct context (if none is provided)
+ context = context || document;
+
+ // Handle the common XPath // expression
+ if ( !t.indexOf("//") ) {
+ context = context.documentElement;
+ t = t.substr(2,t.length);
+
+ // And the / root expression
+ } else if ( !t.indexOf("/") && !context.ownerDocument ) {
+ context = context.documentElement;
+ t = t.substr(1,t.length);
+ if ( t.indexOf("/") >= 1 )
+ t = t.substr(t.indexOf("/"),t.length);
+ }
+
+ // Initialize the search
+ var ret = [context], done = [], last;
+
+ // Continue while a selector expression exists, and while
+ // we're no longer looping upon ourselves
+ while ( t && last != t ) {
+ var r = [];
+ last = t;
+
+ t = jQuery.trim(t).replace( /^\/\//, "" );
+
+ var foundToken = false;
+
+ // An attempt at speeding up child selectors that
+ // point to a specific element tag
+ var re = new RegExp("^[/>]\\s*(" + jQuery.chars + "+)");
+ var m = re.exec(t);
+
+ if ( m ) {
+ var nodeName = m[1].toUpperCase();
+
+ // Perform our own iteration and filter
+ for ( var i = 0; ret[i]; i++ )
+ for ( var c = ret[i].firstChild; c; c = c.nextSibling )
+ if ( c.nodeType == 1 && (nodeName == "*" || c.nodeName.toUpperCase() == nodeName.toUpperCase()) )
+ r.push( c );
+
+ ret = r;
+ t = t.replace( re, "" );
+ if ( t.indexOf(" ") == 0 ) continue;
+ foundToken = true;
+ } else {
+ re = /^((\/?\.\.)|([>\/+~]))\s*([a-z]*)/i;
+
+ if ( (m = re.exec(t)) != null ) {
+ r = [];
+
+ var nodeName = m[4], mergeNum = jQuery.mergeNum++;
+ m = m[1];
+
+ for ( var j = 0, rl = ret.length; j < rl; j++ )
+ if ( m.indexOf("..") < 0 ) {
+ var n = m == "~" || m == "+" ? ret[j].nextSibling : ret[j].firstChild;
+ for ( ; n; n = n.nextSibling )
+ if ( n.nodeType == 1 ) {
+ if ( m == "~" && n.mergeNum == mergeNum ) break;
+
+ if (!nodeName || n.nodeName.toUpperCase() == nodeName.toUpperCase() ) {
+ if ( m == "~" ) n.mergeNum = mergeNum;
+ r.push( n );
+ }
+
+ if ( m == "+" ) break;
+ }
+ } else
+ r.push( ret[j].parentNode );
+
+ ret = r;
+
+ // And remove the token
+ t = jQuery.trim( t.replace( re, "" ) );
+ foundToken = true;
+ }
+ }
+
+ // See if there's still an expression, and that we haven't already
+ // matched a token
+ if ( t && !foundToken ) {
+ // Handle multiple expressions
+ if ( !t.indexOf(",") ) {
+ // Clean the result set
+ if ( context == ret[0] ) ret.shift();
+
+ // Merge the result sets
+ done = jQuery.merge( done, ret );
+
+ // Reset the context
+ r = ret = [context];
+
+ // Touch up the selector string
+ t = " " + t.substr(1,t.length);
+
+ } else {
+ // Optomize for the case nodeName#idName
+ var re2 = new RegExp("^(" + jQuery.chars + "+)(#)(" + jQuery.chars + "+)");
+ var m = re2.exec(t);
+
+ // Re-organize the results, so that they're consistent
+ if ( m ) {
+ m = [ 0, m[2], m[3], m[1] ];
+
+ } else {
+ // Otherwise, do a traditional filter check for
+ // ID, class, and element selectors
+ re2 = new RegExp("^([#.]?)(" + jQuery.chars + "*)");
+ m = re2.exec(t);
+ }
+
+ m[2] = m[2].replace(/\\/g, "");
+
+ var elem = ret[ret.length-1];
+
+ // Try to do a global search by ID, where we can
+ if ( m[1] == "#" && elem && elem.getElementById ) {
+ // Optimization for HTML document case
+ var oid = elem.getElementById(m[2]);
+
+ // Do a quick check for the existence of the actual ID attribute
+ // to avoid selecting by the name attribute in IE
+ // also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
+ if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
+ oid = jQuery('[@id="'+m[2]+'"]', elem)[0];
+
+ // Do a quick check for node name (where applicable) so
+ // that div#foo searches will be really fast
+ ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
+ } else {
+ // We need to find all descendant elements
+ for ( var i = 0; ret[i]; i++ ) {
+ // Grab the tag name being searched for
+ var tag = m[1] != "" || m[0] == "" ? "*" : m[2];
+
+ // Handle IE7 being really dumb about <object>s
+ if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
+ tag = "param";
+
+ r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
+ }
+
+ // It's faster to filter by class and be done with it
+ if ( m[1] == "." )
+ r = jQuery.classFilter( r, m[2] );
+
+ // Same with ID filtering
+ if ( m[1] == "#" ) {
+ var tmp = [];
+
+ // Try to find the element with the ID
+ for ( var i = 0; r[i]; i++ )
+ if ( r[i].getAttribute("id") == m[2] ) {
+ tmp = [ r[i] ];
+ break;
+ }
+
+ r = tmp;
+ }
+
+ ret = r;
+ }
+
+ t = t.replace( re2, "" );
+ }
+
+ }
+
+ // If a selector string still exists
+ if ( t ) {
+ // Attempt to filter it
+ var val = jQuery.filter(t,r);
+ ret = r = val.r;
+ t = jQuery.trim(val.t);
+ }
+ }
+
+ // An error occurred with the selector;
+ // just return an empty set instead
+ if ( t )
+ ret = [];
+
+ // Remove the root context
+ if ( ret && context == ret[0] )
+ ret.shift();
+
+ // And combine the results
+ done = jQuery.merge( done, ret );
+
+ return done;
+ },
+
+ classFilter: function(r,m,not){
+ m = " " + m + " ";
+ var tmp = [];
+ for ( var i = 0; r[i]; i++ ) {
+ var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
+ if ( !not && pass || not && !pass )
+ tmp.push( r[i] );
+ }
+ return tmp;
+ },
+
+ filter: function(t,r,not) {
+ var last;
+
+ // Look for common filter expressions
+ while ( t && t != last ) {
+ last = t;
+
+ var p = jQuery.parse, m;
+
+ for ( var i = 0; p[i]; i++ ) {
+ m = p[i].exec( t );
+
+ if ( m ) {
+ // Remove what we just matched
+ t = t.substring( m[0].length );
+
+ m[2] = m[2].replace(/\\/g, "");
+ break;
+ }
+ }
+
+ if ( !m )
+ break;
+
+ // :not() is a special case that can be optimized by
+ // keeping it out of the expression list
+ if ( m[1] == ":" && m[2] == "not" )
+ r = jQuery.filter(m[3], r, true).r;
+
+ // We can get a big speed boost by filtering by class here
+ else if ( m[1] == "." )
+ r = jQuery.classFilter(r, m[2], not);
+
+ else if ( m[1] == "@" ) {
+ var tmp = [], type = m[3];
+
+ for ( var i = 0, rl = r.length; i < rl; i++ ) {
+ var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];
+
+ if ( z == null || /href|src/.test(m[2]) )
+ z = jQuery.attr(a,m[2]) || '';
+
+ if ( (type == "" && !!z ||
+ type == "=" && z == m[5] ||
+ type == "!=" && z != m[5] ||
+ type == "^=" && z && !z.indexOf(m[5]) ||
+ type == "$=" && z.substr(z.length - m[5].length) == m[5] ||
+ (type == "*=" || type == "~=") && z.indexOf(m[5]) >= 0) ^ not )
+ tmp.push( a );
+ }
+
+ r = tmp;
+
+ // We can get a speed boost by handling nth-child here
+ } else if ( m[1] == ":" && m[2] == "nth-child" ) {
+ var num = jQuery.mergeNum++, tmp = [],
+ test = /(\d*)n\+?(\d*)/.exec(
+ m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
+ !/\D/.test(m[3]) && "n+" + m[3] || m[3]),
+ first = (test[1] || 1) - 0, last = test[2] - 0;
+
+ for ( var i = 0, rl = r.length; i < rl; i++ ) {
+ var node = r[i], parentNode = node.parentNode;
+
+ if ( num != parentNode.mergeNum ) {
+ var c = 1;
+
+ for ( var n = parentNode.firstChild; n; n = n.nextSibling )
+ if ( n.nodeType == 1 )
+ n.nodeIndex = c++;
+
+ parentNode.mergeNum = num;
+ }
+
+ var add = false;
+
+ if ( first == 1 ) {
+ if ( last == 0 || node.nodeIndex == last )
+ add = true;
+ } else if ( (node.nodeIndex + last) % first == 0 )
+ add = true;
+
+ if ( add ^ not )
+ tmp.push( node );
+ }
+
+ r = tmp;
+
+ // Otherwise, find the expression to execute
+ } else {
+ var f = jQuery.expr[m[1]];
+ if ( typeof f != "string" )
+ f = jQuery.expr[m[1]][m[2]];
+
+ // Build a custom macro to enclose it
+ eval("f = function(a,i){return " + f + "}");
+
+ // Execute it against the current filter
+ r = jQuery.grep( r, f, not );
+ }
+ }
+
+ // Return an array of filtered elements (r)
+ // and the modified expression string (t)
+ return { r: r, t: t };
+ },
+ parents: function( elem ){
+ var matched = [];
+ var cur = elem.parentNode;
+ while ( cur && cur != document ) {
+ matched.push( cur );
+ cur = cur.parentNode;
+ }
+ return matched;
+ },
+ nth: function(cur,result,dir,elem){
+ result = result || 1;
+ var num = 0;
+
+ for ( ; cur; cur = cur[dir] )
+ if ( cur.nodeType == 1 && ++num == result )
+ break;
+
+ return cur;
+ },
+ sibling: function( n, elem ) {
+ var r = [];
+
+ for ( ; n; n = n.nextSibling ) {
+ if ( n.nodeType == 1 && (!elem || n != elem) )
+ r.push( n );
+ }
+
+ return r;
+ }
+});
+/*
+ * A number of helper functions used for managing events.
+ * Many of the ideas behind this code orignated from
+ * Dean Edwards' addEvent library.
+ */
+jQuery.event = {
+
+ // Bind an event to an element
+ // Original by Dean Edwards
+ add: function(element, type, handler, data) {
+ // For whatever reason, IE has trouble passing the window object
+ // around, causing it to be cloned in the process
+ if ( jQuery.browser.msie && element.setInterval != undefined )
+ element = window;
+
+ // Make sure that the function being executed has a unique ID
+ if ( !handler.guid )
+ handler.guid = this.guid++;
+
+ // if data is passed, bind to handler
+ if( data != undefined ) {
+ // Create temporary function pointer to original handler
+ var fn = handler;
+
+ // Create unique handler function, wrapped around original handler
+ handler = function() {
+ // Pass arguments and context to original handler
+ return fn.apply(this, arguments);
+ };
+
+ // Store data in unique handler
+ handler.data = data;
+
+ // Set the guid of unique handler to the same of original handler, so it can be removed
+ handler.guid = fn.guid;
+ }
+
+ // Init the element's event structure
+ if (!element.$events)
+ element.$events = {};
+
+ if (!element.$handle)
+ element.$handle = function() {
+ // returned undefined or false
+ var val;
+
+ // Handle the second event of a trigger and when
+ // an event is called after a page has unloaded
+ if ( typeof jQuery == "undefined" || jQuery.event.triggered )
+ return val;
+
+ val = jQuery.event.handle.apply(element, arguments);
+
+ return val;
+ };
+
+ // Get the current list of functions bound to this event
+ var handlers = element.$events[type];
+
+ // Init the event handler queue
+ if (!handlers) {
+ handlers = element.$events[type] = {};
+
+ // And bind the global event handler to the element
+ if (element.addEventListener)
+ element.addEventListener(type, element.$handle, false);
+ else
+ element.attachEvent("on" + type, element.$handle);
+ }
+
+ // Add the function to the element's handler list
+ handlers[handler.guid] = handler;
+
+ // Remember the function in a global list (for triggering)
+ if (!this.global[type])
+ this.global[type] = [];
+ // Only add the element to the global list once
+ if (jQuery.inArray(element, this.global[type]) == -1)
+ this.global[type].push( element );
+ },
+
+ guid: 1,
+ global: {},
+
+ // Detach an event or set of events from an element
+ remove: function(element, type, handler) {
+ var events = element.$events, ret, index;
+
+ if ( events ) {
+ // type is actually an event object here
+ if ( type && type.type ) {
+ handler = type.handler;
+ type = type.type;
+ }
+
+ if ( !type ) {
+ for ( type in events )
+ this.remove( element, type );
+
+ } else if ( events[type] ) {
+ // remove the given handler for the given type
+ if ( handler )
+ delete events[type][handler.guid];
+
+ // remove all handlers for the given type
+ else
+ for ( handler in element.$events[type] )
+ delete events[type][handler];
+
+ // remove generic event handler if no more handlers exist
+ for ( ret in events[type] ) break;
+ if ( !ret ) {
+ if (element.removeEventListener)
+ element.removeEventListener(type, element.$handle, false);
+ else
+ element.detachEvent("on" + type, element.$handle);
+ ret = null;
+ delete events[type];
+
+ // Remove element from the global event type cache
+ while ( this.global[type] && ( (index = jQuery.inArray(element, this.global[type])) >= 0 ) )
+ delete this.global[type][index];
+ }
+ }
+
+ // Remove the expando if it's no longer used
+ for ( ret in events ) break;
+ if ( !ret )
+ element.$handle = element.$events = null;
+ }
+ },
+
+ trigger: function(type, data, element) {
+ // Clone the incoming data, if any
+ data = jQuery.makeArray(data || []);
+
+ // Handle a global trigger
+ if ( !element )
+ jQuery.each( this.global[type] || [], function(){
+ jQuery.event.trigger( type, data, this );
+ });
+
+ // Handle triggering a single element
+ else {
+ var val, ret, fn = jQuery.isFunction( element[ type ] || null );
+
+ // Pass along a fake event
+ data.unshift( this.fix({ type: type, target: element }) );
+
+ // Trigger the event
+ if ( jQuery.isFunction(element.$handle) && (val = element.$handle.apply( element, data )) !== false )
+ this.triggered = true;
+
+ if ( fn && val !== false && !jQuery.nodeName(element, 'a') )
+ element[ type ]();
+
+ this.triggered = false;
+ }
+ },
+
+ handle: function(event) {
+ // returned undefined or false
+ var val;
+
+ // Empty object is for triggered events with no data
+ event = jQuery.event.fix( event || window.event || {} );
+
+ var c = this.$events && this.$events[event.type], args = [].slice.call( arguments, 1 );
+ args.unshift( event );
+
+ for ( var j in c ) {
+ // Pass in a reference to the handler function itself
+ // So that we can later remove it
+ args[0].handler = c[j];
+ args[0].data = c[j].data;
+
+ if ( c[j].apply( this, args ) === false ) {
+ event.preventDefault();
+ event.stopPropagation();
+ val = false;
+ }
+ }
+
+ // Clean up added properties in IE to prevent memory leak
+ if (jQuery.browser.msie)
+ event.target = event.preventDefault = event.stopPropagation =
+ event.handler = event.data = null;
+
+ return val;
+ },
+
+ fix: function(event) {
+ // store a copy of the original event object
+ // and clone to set read-only properties
+ var originalEvent = event;
+ event = jQuery.extend({}, originalEvent);
+
+ // add preventDefault and stopPropagation since
+ // they will not work on the clone
+ event.preventDefault = function() {
+ // if preventDefault exists run it on the original event
+ if (originalEvent.preventDefault)
+ return originalEvent.preventDefault();
+ // otherwise set the returnValue property of the original event to false (IE)
+ originalEvent.returnValue = false;
+ };
+ event.stopPropagation = function() {
+ // if stopPropagation exists run it on the original event
+ if (originalEvent.stopPropagation)
+ return originalEvent.stopPropagation();
+ // otherwise set the cancelBubble property of the original event to true (IE)
+ originalEvent.cancelBubble = true;
+ };
+
+ // Fix target property, if necessary
+ if ( !event.target && event.srcElement )
+ event.target = event.srcElement;
+
+ // check if target is a textnode (safari)
+ if (jQuery.browser.safari && event.target.nodeType == 3)
+ event.target = originalEvent.target.parentNode;
+
+ // Add relatedTarget, if necessary
+ if ( !event.relatedTarget && event.fromElement )
+ event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
+
+ // Calculate pageX/Y if missing and clientX/Y available
+ if ( event.pageX == null && event.clientX != null ) {
+ var e = document.documentElement, b = document.body;
+ event.pageX = event.clientX + (e && e.scrollLeft || b.scrollLeft);
+ event.pageY = event.clientY + (e && e.scrollTop || b.scrollTop);
+ }
+
+ // Add which for key events
+ if ( !event.which && (event.charCode || event.keyCode) )
+ event.which = event.charCode || event.keyCode;
+
+ // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
+ if ( !event.metaKey && event.ctrlKey )
+ event.metaKey = event.ctrlKey;
+
+ // Add which for click: 1 == left; 2 == middle; 3 == right
+ // Note: button is not normalized, so don't use it
+ if ( !event.which && event.button )
+ event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
+
+ return event;
+ }
+};
+
+jQuery.fn.extend({
+ bind: function( type, data, fn ) {
+ return type == "unload" ? this.one(type, data, fn) : this.each(function(){
+ jQuery.event.add( this, type, fn || data, fn && data );
+ });
+ },
+ one: function( type, data, fn ) {
+ return this.each(function(){
+ jQuery.event.add( this, type, function(event) {
+ jQuery(this).unbind(event);
+ return (fn || data).apply( this, arguments);
+ }, fn && data);
+ });
+ },
+ unbind: function( type, fn ) {
+ return this.each(function(){
+ jQuery.event.remove( this, type, fn );
+ });
+ },
+ trigger: function( type, data ) {
+ return this.each(function(){
+ jQuery.event.trigger( type, data, this );
+ });
+ },
+ toggle: function() {
+ // Save reference to arguments for access in closure
+ var a = arguments;
+
+ return this.click(function(e) {
+ // Figure out which function to execute
+ this.lastToggle = 0 == this.lastToggle ? 1 : 0;
+
+ // Make sure that clicks stop
+ e.preventDefault();
+
+ // and execute the function
+ return a[this.lastToggle].apply( this, [e] ) || false;
+ });
+ },
+ hover: function(f,g) {
+
+ // A private function for handling mouse 'hovering'
+ function handleHover(e) {
+ // Check if mouse(over|out) are still within the same parent element
+ var p = e.relatedTarget;
+
+ // Traverse up the tree
+ while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
+
+ // If we actually just moused on to a sub-element, ignore it
+ if ( p == this ) return false;
+
+ // Execute the right function
+ return (e.type == "mouseover" ? f : g).apply(this, [e]);
+ }
+
+ // Bind the function to the two event listeners
+ return this.mouseover(handleHover).mouseout(handleHover);
+ },
+ ready: function(f) {
+ // If the DOM is already ready
+ if ( jQuery.isReady )
+ // Execute the function immediately
+ f.apply( document, [jQuery] );
+
+ // Otherwise, remember the function for later
+ else
+ // Add the function to the wait list
+ jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
+
+ return this;
+ }
+});
+
+jQuery.extend({
+ /*
+ * All the code that makes DOM Ready work nicely.
+ */
+ isReady: false,
+ readyList: [],
+
+ // Handle when the DOM is ready
+ ready: function() {
+ // Make sure that the DOM is not already loaded
+ if ( !jQuery.isReady ) {
+ // Remember that the DOM is ready
+ jQuery.isReady = true;
+
+ // If there are functions bound, to execute
+ if ( jQuery.readyList ) {
+ // Execute all of them
+ jQuery.each( jQuery.readyList, function(){
+ this.apply( document );
+ });
+
+ // Reset the list of functions
+ jQuery.readyList = null;
+ }
+ // Remove event listener to avoid memory leak
+ if ( jQuery.browser.mozilla || jQuery.browser.opera )
+ document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
+
+ // Remove script element used by IE hack
+ if( !window.frames.length ) // don't remove if frames are present (#1187)
+ jQuery(window).load(function(){ jQuery("#__ie_init").remove(); });
+ }
+ }
+});
+
+new function(){
+
+ jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
+ "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
+ "submit,keydown,keypress,keyup,error").split(","), function(i,o){
+
+ // Handle event binding
+ jQuery.fn[o] = function(f){
+ return f ? this.bind(o, f) : this.trigger(o);
+ };
+
+ });
+
+ // If Mozilla is used
+ if ( jQuery.browser.mozilla || jQuery.browser.opera )
+ // Use the handy event callback
+ document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
+
+ // If IE is used, use the excellent hack by Matthias Miller
+ // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
+ else if ( jQuery.browser.msie ) {
+
+ // Only works if you document.write() it
+ document.write("<scr" + "ipt id=__ie_init defer=true " +
+ "src=//:><\/script>");
+
+ // Use the defer script hack
+ var script = document.getElementById("__ie_init");
+
+ // script does not exist if jQuery is loaded dynamically
+ if ( script )
+ script.onreadystatechange = function() {
+ if ( this.readyState != "complete" ) return;
+ jQuery.ready();
+ };
+
+ // Clear from memory
+ script = null;
+
+ // If Safari is used
+ } else if ( jQuery.browser.safari )
+ // Continually check to see if the document.readyState is valid
+ jQuery.safariTimer = setInterval(function(){
+ // loaded and complete are both valid states
+ if ( document.readyState == "loaded" ||
+ document.readyState == "complete" ) {
+
+ // If either one are found, remove the timer
+ clearInterval( jQuery.safariTimer );
+ jQuery.safariTimer = null;
+
+ // and execute any waiting functions
+ jQuery.ready();
+ }
+ }, 10);
+
+ // A fallback to window.onload, that will always work
+ jQuery.event.add( window, "load", jQuery.ready );
+
+};
+
+// Clean up after IE to avoid memory leaks
+if (jQuery.browser.msie)
+ jQuery(window).one("unload", function() {
+ var global = jQuery.event.global;
+ for ( var type in global ) {
+ var els = global[type], i = els.length;
+ if ( i && type != 'unload' )
+ do
+ els[i-1] && jQuery.event.remove(els[i-1], type);
+ while (--i);
+ }
+ });
+jQuery.fn.extend({
+ loadIfModified: function( url, params, callback ) {
+ this.load( url, params, callback, 1 );
+ },
+ load: function( url, params, callback, ifModified ) {
+ if ( jQuery.isFunction( url ) )
+ return this.bind("load", url);
+
+ callback = callback || function(){};
+
+ // Default to a GET request
+ var type = "GET";
+
+ // If the second parameter was provided
+ if ( params )
+ // If it's a function
+ if ( jQuery.isFunction( params ) ) {
+ // We assume that it's the callback
+ callback = params;
+ params = null;
+
+ // Otherwise, build a param string
+ } else {
+ params = jQuery.param( params );
+ type = "POST";
+ }
+
+ var self = this;
+
+ // Request the remote document
+ jQuery.ajax({
+ url: url,
+ type: type,
+ data: params,
+ ifModified: ifModified,
+ complete: function(res, status){
+ if ( status == "success" || !ifModified && status == "notmodified" )
+ // Inject the HTML into all the matched elements
+ self.attr("innerHTML", res.responseText)
+ // Execute all the scripts inside of the newly-injected HTML
+ .evalScripts()
+ // Execute callback
+ .each( callback, [res.responseText, status, res] );
+ else
+ callback.apply( self, [res.responseText, status, res] );
+ }
+ });
+ return this;
+ },
+ serialize: function() {
+ return jQuery.param( this );
+ },
+ evalScripts: function() {
+ return this.find("script").each(function(){
+ if ( this.src )
+ jQuery.getScript( this.src );
+ else
+ jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" );
+ }).end();
+ }
+
+});
+
+// Attach a bunch of functions for handling common AJAX events
+
+jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
+ jQuery.fn[o] = function(f){
+ return this.bind(o, f);
+ };
+});
+
+jQuery.extend({
+ get: function( url, data, callback, type, ifModified ) {
+ // shift arguments if data argument was ommited
+ if ( jQuery.isFunction( data ) ) {
+ callback = data;
+ data = null;
+ }
+
+ return jQuery.ajax({
+ type: "GET",
+ url: url,
+ data: data,
+ success: callback,
+ dataType: type,
+ ifModified: ifModified
+ });
+ },
+ getIfModified: function( url, data, callback, type ) {
+ return jQuery.get(url, data, callback, type, 1);
+ },
+ getScript: function( url, callback ) {
+ return jQuery.get(url, null, callback, "script");
+ },
+ getJSON: function( url, data, callback ) {
+ return jQuery.get(url, data, callback, "json");
+ },
+ post: function( url, data, callback, type ) {
+ if ( jQuery.isFunction( data ) ) {
+ callback = data;
+ data = {};
+ }
+
+ return jQuery.ajax({
+ type: "POST",
+ url: url,
+ data: data,
+ success: callback,
+ dataType: type
+ });
+ },
+ ajaxTimeout: function( timeout ) {
+ jQuery.ajaxSettings.timeout = timeout;
+ },
+ ajaxSetup: function( settings ) {
+ jQuery.extend( jQuery.ajaxSettings, settings );
+ },
+
+ ajaxSettings: {
+ global: true,
+ type: "GET",
+ timeout: 0,
+ contentType: "application/x-www-form-urlencoded",
+ processData: true,
+ async: true,
+ data: null
+ },
+
+ // Last-Modified header cache for next request
+ lastModified: {},
+ ajax: function( s ) {
+ // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
+ s = jQuery.extend({}, jQuery.ajaxSettings, s);
+
+ // if data available
+ if ( s.data ) {
+ // convert data if not already a string
+ if (s.processData && typeof s.data != "string")
+ s.data = jQuery.param(s.data);
+ // append data to url for get requests
+ if( s.type.toLowerCase() == "get" ) {
+ // "?" + data or "&" + data (in case there are already params)
+ s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
+ // IE likes to send both get and post data, prevent this
+ s.data = null;
+ }
+ }
+
+ // Watch for a new set of requests
+ if ( s.global && ! jQuery.active++ )
+ jQuery.event.trigger( "ajaxStart" );
+
+ var requestDone = false;
+
+ // Create the request object; Microsoft failed to properly
+ // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
+ var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
+
+ // Open the socket
+ xml.open(s.type, s.url, s.async);
+
+ // Set the correct header, if data is being sent
+ if ( s.data )
+ xml.setRequestHeader("Content-Type", s.contentType);
+
+ // Set the If-Modified-Since header, if ifModified mode.
+ if ( s.ifModified )
+ xml.setRequestHeader("If-Modified-Since",
+ jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
+
+ // Set header so the called script knows that it's an XMLHttpRequest
+ xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+
+ // Allow custom headers/mimetypes
+ if( s.beforeSend )
+ s.beforeSend(xml);
+
+ if ( s.global )
+ jQuery.event.trigger("ajaxSend", [xml, s]);
+
+ // Wait for a response to come back
+ var onreadystatechange = function(isTimeout){
+ // The transfer is complete and the data is available, or the request timed out
+ if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
+ requestDone = true;
+
+ // clear poll interval
+ if (ival) {
+ clearInterval(ival);
+ ival = null;
+ }
+
+ var status;
+ try {
+ status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
+ s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
+ // Make sure that the request was successful or notmodified
+ if ( status != "error" ) {
+ // Cache Last-Modified header, if ifModified mode.
+ var modRes;
+ try {
+ modRes = xml.getResponseHeader("Last-Modified");
+ } catch(e) {} // swallow exception thrown by FF if header is not available
+
+ if ( s.ifModified && modRes )
+ jQuery.lastModified[s.url] = modRes;
+
+ // process the data (runs the xml through httpData regardless of callback)
+ var data = jQuery.httpData( xml, s.dataType );
+
+ // If a local callback was specified, fire it and pass it the data
+ if ( s.success )
+ s.success( data, status );
+
+ // Fire the global callback
+ if( s.global )
+ jQuery.event.trigger( "ajaxSuccess", [xml, s] );
+ } else
+ jQuery.handleError(s, xml, status);
+ } catch(e) {
+ status = "error";
+ jQuery.handleError(s, xml, status, e);
+ }
+
+ // The request was completed
+ if( s.global )
+ jQuery.event.trigger( "ajaxComplete", [xml, s] );
+
+ // Handle the global AJAX counter
+ if ( s.global && ! --jQuery.active )
+ jQuery.event.trigger( "ajaxStop" );
+
+ // Process result
+ if ( s.complete )
+ s.complete(xml, status);
+
+ // Stop memory leaks
+ if(s.async)
+ xml = null;
+ }
+ };
+
+ // don't attach the handler to the request, just poll it instead
+ var ival = setInterval(onreadystatechange, 13);
+
+ // Timeout checker
+ if ( s.timeout > 0 )
+ setTimeout(function(){
+ // Check to see if the request is still happening
+ if ( xml ) {
+ // Cancel the request
+ xml.abort();
+
+ if( !requestDone )
+ onreadystatechange( "timeout" );
+ }
+ }, s.timeout);
+
+ // Send the data
+ try {
+ xml.send(s.data);
+ } catch(e) {
+ jQuery.handleError(s, xml, null, e);
+ }
+
+ // firefox 1.5 doesn't fire statechange for sync requests
+ if ( !s.async )
+ onreadystatechange();
+
+ // return XMLHttpRequest to allow aborting the request etc.
+ return xml;
+ },
+
+ handleError: function( s, xml, status, e ) {
+ // If a local callback was specified, fire it
+ if ( s.error ) s.error( xml, status, e );
+
+ // Fire the global callback
+ if ( s.global )
+ jQuery.event.trigger( "ajaxError", [xml, s, e] );
+ },
+
+ // Counter for holding the number of active queries
+ active: 0,
+
+ // Determines if an XMLHttpRequest was successful or not
+ httpSuccess: function( r ) {
+ try {
+ return !r.status && location.protocol == "file:" ||
+ ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
+ jQuery.browser.safari && r.status == undefined;
+ } catch(e){}
+ return false;
+ },
+
+ // Determines if an XMLHttpRequest returns NotModified
+ httpNotModified: function( xml, url ) {
+ try {
+ var xmlRes = xml.getResponseHeader("Last-Modified");
+
+ // Firefox always returns 200. check Last-Modified date
+ return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
+ jQuery.browser.safari && xml.status == undefined;
+ } catch(e){}
+ return false;
+ },
+
+ /* Get the data out of an XMLHttpRequest.
+ * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
+ * otherwise return plain text.
+ * (String) data - The type of data that you're expecting back,
+ * (e.g. "xml", "html", "script")
+ */
+ httpData: function( r, type ) {
+ var ct = r.getResponseHeader("content-type");
+ var data = !type && ct && ct.indexOf("xml") >= 0;
+ data = type == "xml" || data ? r.responseXML : r.responseText;
+
+ // If the type is "script", eval it in global context
+ if ( type == "script" )
+ jQuery.globalEval( data );
+
+ // Get the JavaScript object, if JSON is used.
+ if ( type == "json" )
+ data = eval("(" + data + ")");
+
+ // evaluate scripts within html
+ if ( type == "html" )
+ jQuery("<div>").html(data).evalScripts();
+
+ return data;
+ },
+
+ // Serialize an array of form elements or a set of
+ // key/values into a query string
+ param: function( a ) {
+ var s = [];
+
+ // If an array was passed in, assume that it is an array
+ // of form elements
+ if ( a.constructor == Array || a.jquery )
+ // Serialize the form elements
+ jQuery.each( a, function(){
+ s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
+ });
+
+ // Otherwise, assume that it's an object of key/value pairs
+ else
+ // Serialize the key/values
+ for ( var j in a )
+ // If the value is an array then the key names need to be repeated
+ if ( a[j] && a[j].constructor == Array )
+ jQuery.each( a[j], function(){
+ s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
+ });
+ else
+ s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
+
+ // Return the resulting serialization
+ return s.join("&");
+ },
+
+ // evalulates a script in global context
+ // not reliable for safari
+ globalEval: function( data ) {
+ if ( window.execScript )
+ window.execScript( data );
+ else if ( jQuery.browser.safari )
+ // safari doesn't provide a synchronous global eval
+ window.setTimeout( data, 0 );
+ else
+ eval.call( window, data );
+ }
+
+});
+jQuery.fn.extend({
+
+ show: function(speed,callback){
+ return speed ?
+ this.animate({
+ height: "show", width: "show", opacity: "show"
+ }, speed, callback) :
+
+ this.filter(":hidden").each(function(){
+ this.style.display = this.oldblock ? this.oldblock : "";
+ if ( jQuery.css(this,"display") == "none" )
+ this.style.display = "block";
+ }).end();
+ },
+
+ hide: function(speed,callback){
+ return speed ?
+ this.animate({
+ height: "hide", width: "hide", opacity: "hide"
+ }, speed, callback) :
+
+ this.filter(":visible").each(function(){
+ this.oldblock = this.oldblock || jQuery.css(this,"display");
+ if ( this.oldblock == "none" )
+ this.oldblock = "block";
+ this.style.display = "none";
+ }).end();
+ },
+
+ // Save the old toggle function
+ _toggle: jQuery.fn.toggle,
+ toggle: function( fn, fn2 ){
+ return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
+ this._toggle( fn, fn2 ) :
+ fn ?
+ this.animate({
+ height: "toggle", width: "toggle", opacity: "toggle"
+ }, fn, fn2) :
+ this.each(function(){
+ jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
+ });
+ },
+ slideDown: function(speed,callback){
+ return this.animate({height: "show"}, speed, callback);
+ },
+ slideUp: function(speed,callback){
+ return this.animate({height: "hide"}, speed, callback);
+ },
+ slideToggle: function(speed, callback){
+ return this.animate({height: "toggle"}, speed, callback);
+ },
+ fadeIn: function(speed, callback){
+ return this.animate({opacity: "show"}, speed, callback);
+ },
+ fadeOut: function(speed, callback){
+ return this.animate({opacity: "hide"}, speed, callback);
+ },
+ fadeTo: function(speed,to,callback){
+ return this.animate({opacity: to}, speed, callback);
+ },
+ animate: function( prop, speed, easing, callback ) {
+ return this.queue(function(){
+ var hidden = jQuery(this).is(":hidden"),
+ opt = jQuery.speed(speed, easing, callback),
+ self = this;
+
+ for ( var p in prop ) {
+ if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
+ return jQuery.isFunction(opt.complete) && opt.complete.apply(this);
+
+ if ( p == "height" || p == "width" ) {
+ // Store display property
+ opt.display = jQuery.css(this, "display");
+
+ // Make sure that nothing sneaks out
+ opt.overflow = this.style.overflow;
+ }
+ }
+
+ if ( opt.overflow != null )
+ this.style.overflow = "hidden";
+
+ this.curAnim = jQuery.extend({}, prop);
+
+ jQuery.each( prop, function(name, val){
+ var e = new jQuery.fx( self, opt, name );
+ if ( val.constructor == Number )
+ e.custom( e.cur(), val );
+ else
+ e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
+ });
+ });
+ },
+ queue: function(type,fn){
+ if ( !fn ) {
+ fn = type;
+ type = "fx";
+ }
+
+ return this.each(function(){
+ if ( !this.queue )
+ this.queue = {};
+
+ if ( !this.queue[type] )
+ this.queue[type] = [];
+
+ this.queue[type].push( fn );
+
+ if ( this.queue[type].length == 1 )
+ fn.apply(this);
+ });
+ }
+
+});
+
+jQuery.extend({
+
+ speed: function(speed, easing, fn) {
+ var opt = speed && speed.constructor == Object ? speed : {
+ complete: fn || !fn && easing ||
+ jQuery.isFunction( speed ) && speed,
+ duration: speed,
+ easing: fn && easing || easing && easing.constructor != Function && easing || (jQuery.easing.swing ? "swing" : "linear")
+ };
+
+ opt.duration = (opt.duration && opt.duration.constructor == Number ?
+ opt.duration :
+ { slow: 600, fast: 200 }[opt.duration]) || 400;
+
+ // Queueing
+ opt.old = opt.complete;
+ opt.complete = function(){
+ jQuery.dequeue(this, "fx");
+ if ( jQuery.isFunction( opt.old ) )
+ opt.old.apply( this );
+ };
+
+ return opt;
+ },
+
+ easing: {
+ linear: function( p, n, firstNum, diff ) {
+ return firstNum + diff * p;
+ },
+ swing: function( p, n, firstNum, diff ) {
+ return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
+ }
+ },
+
+ queue: {},
+
+ dequeue: function(elem,type){
+ type = type || "fx";
+
+ if ( elem.queue && elem.queue[type] ) {
+ // Remove self
+ elem.queue[type].shift();
+
+ // Get next function
+ var f = elem.queue[type][0];
+
+ if ( f ) f.apply( elem );
+ }
+ },
+
+ timers: [],
+
+ /*
+ * I originally wrote fx() as a clone of moo.fx and in the process
+ * of making it small in size the code became illegible to sane
+ * people. You've been warned.
+ */
+
+ fx: function( elem, options, prop ){
+
+ var z = this;
+
+ // The styles
+ var y = elem.style;
+
+ // Simple function for setting a style value
+ z.a = function(){
+ if ( options.step )
+ options.step.apply( elem, [ z.now ] );
+
+ if ( prop == "opacity" )
+ jQuery.attr(y, "opacity", z.now); // Let attr handle opacity
+ else {
+ y[prop] = parseInt(z.now) + "px";
+ y.display = "block"; // Set display property to block for animation
+ }
+ };
+
+ // Figure out the maximum number to run to
+ z.max = function(){
+ return parseFloat( jQuery.css(elem,prop) );
+ };
+
+ // Get the current size
+ z.cur = function(){
+ var r = parseFloat( jQuery.curCSS(elem, prop) );
+ return r && r > -10000 ? r : z.max();
+ };
+
+ // Start an animation from one number to another
+ z.custom = function(from,to){
+ z.startTime = (new Date()).getTime();
+ z.now = from;
+ z.a();
+
+ jQuery.timers.push(function(){
+ return z.step(from, to);
+ });
+
+ if ( jQuery.timers.length == 1 ) {
+ var timer = setInterval(function(){
+ var timers = jQuery.timers;
+
+ for ( var i = 0; i < timers.length; i++ )
+ if ( !timers[i]() )
+ timers.splice(i--, 1);
+
+ if ( !timers.length )
+ clearInterval( timer );
+ }, 13);
+ }
+ };
+
+ // Simple 'show' function
+ z.show = function(){
+ if ( !elem.orig ) elem.orig = {};
+
+ // Remember where we started, so that we can go back to it later
+ elem.orig[prop] = jQuery.attr( elem.style, prop );
+
+ options.show = true;
+
+ // Begin the animation
+ z.custom(0, this.cur());
+
+ // Make sure that we start at a small width/height to avoid any
+ // flash of content
+ if ( prop != "opacity" )
+ y[prop] = "1px";
+
+ // Start by showing the element
+ jQuery(elem).show();
+ };
+
+ // Simple 'hide' function
+ z.hide = function(){
+ if ( !elem.orig ) elem.orig = {};
+
+ // Remember where we started, so that we can go back to it later
+ elem.orig[prop] = jQuery.attr( elem.style, prop );
+
+ options.hide = true;
+
+ // Begin the animation
+ z.custom(this.cur(), 0);
+ };
+
+ // Each step of an animation
+ z.step = function(firstNum, lastNum){
+ var t = (new Date()).getTime();
+
+ if (t > options.duration + z.startTime) {
+ z.now = lastNum;
+ z.a();
+
+ if (elem.curAnim) elem.curAnim[ prop ] = true;
+
+ var done = true;
+ for ( var i in elem.curAnim )
+ if ( elem.curAnim[i] !== true )
+ done = false;
+
+ if ( done ) {
+ if ( options.display != null ) {
+ // Reset the overflow
+ y.overflow = options.overflow;
+
+ // Reset the display
+ y.display = options.display;
+ if ( jQuery.css(elem, "display") == "none" )
+ y.display = "block";
+ }
+
+ // Hide the element if the "hide" operation was done
+ if ( options.hide )
+ y.display = "none";
+
+ // Reset the properties, if the item has been hidden or shown
+ if ( options.hide || options.show )
+ for ( var p in elem.curAnim )
+ jQuery.attr(y, p, elem.orig[p]);
+ }
+
+ // If a callback was provided, execute it
+ if ( done && jQuery.isFunction( options.complete ) )
+ // Execute the complete function
+ options.complete.apply( elem );
+
+ return false;
+ } else {
+ var n = t - this.startTime;
+ // Figure out where in the animation we are and set the number
+ var p = n / options.duration;
+
+ // Perform the easing function, defaults to swing
+ z.now = jQuery.easing[options.easing](p, n, firstNum, (lastNum-firstNum), options.duration);
+
+ // Perform the next step of the animation
+ z.a();
+ }
+
+ return true;
+ };
+
+ }
+});
+}
diff --git a/linkips.user.js b/linkips.user.js
new file mode 100644
index 0000000..fb1f1c0
--- /dev/null
+++ b/linkips.user.js
@@ -0,0 +1,79 @@
+// ==UserScript==
+// @name linkIps
+// @description Turn text IPs in clickable links
+// @include *
+// ==/UserScript==
+
+
+var nodesWithUris = new Array();
+var uriRe = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g;
+
+function main()
+{
+ addCSS();
+ makeLinks(document.documentElement);
+}
+
+function makeLinks(baseNode)
+{
+ getNodesWithUris(baseNode);
+
+ for (var i in nodesWithUris)
+ {
+ var nodes = new Array(nodesWithUris[i]); // We're going to add more nodes as we find/make them
+ while (nodes.length > 0)
+ {
+ var node = nodes.shift();
+ var uriMatches = node.nodeValue.match(uriRe); // array of matches
+ if (uriMatches == null) continue;
+ var firstMatch = uriMatches[0].toLowerCase();
+ var pos = node.nodeValue.toLowerCase().indexOf(firstMatch);
+
+ if (pos == -1) continue; // shouldn't happen, but you should always have safe regex
+ else if (pos == 0) // if starts with URI
+ {
+ if (node.nodeValue.length > firstMatch.length)
+ {
+ node.splitText(firstMatch.length);
+ nodes.push(node.nextSibling);
+ }
+
+ var linky = document.createElement("a");
+ linky.className = "linkified_ip";
+ linky.href = 'http://www.dnsstuff.com/tools/ptr.ch?ip='+node.nodeValue;
+ node.parentNode.insertBefore(linky, node);
+ linky.appendChild(node);
+ }
+ else // if URI is in the text, but not at the beginning
+ {
+ node.splitText(pos);
+ nodes.unshift(node.nextSibling);
+ }
+ }
+ }
+}
+
+function getNodesWithUris(node)
+{
+ if (node.nodeType == 3)
+ {
+ if (node.nodeValue.search(uriRe) != -1)
+ nodesWithUris.push(node);
+ }
+ else if (node && node.nodeType == 1 && node.hasChildNodes() && !node.tagName.match(/^(a|head|object|embed|script|style|frameset|frame|iframe|textarea|input|button|select|option)$/i))
+ for (var i in node.childNodes)
+ getNodesWithUris(node.childNodes[i]);
+}
+function addCSS() {
+ var head, style,css;
+ head = document.getElementsByTagName('head')[0];
+ if (!head) { return; }
+ css='a.linkified_ip:hover { border: 2px solid #e08000; padding: 3px; -moz-border-radius: 5px;}';
+ style = document.createElement('style');
+ style.type = 'text/css';
+ style.innerHTML = css;
+ head.appendChild(style);
+}
+
+main();
+
diff --git a/newbienudesnerv.user.js b/newbienudesnerv.user.js
new file mode 100644
index 0000000..00947fa
--- /dev/null
+++ b/newbienudesnerv.user.js
@@ -0,0 +1,33 @@
+// ==UserScript==
+// @name Newbienudes-nerv
+// @description onRightClick, window open
+// @include newbienudes.com
+// ==/UserScript==
+
+(function() {
+ var allImg;
+ allLinks = document.getElementsByTagName('a');
+ for (var i=0; i<allLinks.length;i++) {
+ var l = allLinks[i];
+ var h = l.href;
+ var s = h.search(/javascript:ViewPhoto/);
+ if(s!=-1) {
+ l.href=h.replace(/javascript:ViewPhoto\(\'/,"http://www.newbienudes.com/Photos/");
+ l.target="_blank";
+ }
+ }
+ allImg = document.getElementsByTagName('img');
+ for (var i=0; i<allImg.length;i++) {
+ var l = allImg[i];
+ if(l.getAttribute('oncontextmenu') ) {
+ p=l.parentNode.parentNode;
+ if( p )
+ {
+ p.removeChild(p.firstChild);
+ p.appendChild(l);
+ }
+ l.setAttribute('oncontextmenu','');
+ l.setAttribute('galleryimg','yes');
+ }
+ }
+})();
diff --git a/openbcuserimagesmouseove.user.js b/openbcuserimagesmouseove.user.js
new file mode 100644
index 0000000..54810b9
--- /dev/null
+++ b/openbcuserimagesmouseove.user.js
@@ -0,0 +1,66 @@
+// ==UserScript==
+// @name OpenBC UserImages MouseOver
+// @namespace
+// @description Shows big images when hovering over userImages in OpenBC/Xing.
+// @include *xing.com/*
+// ==/UserScript==
+// OpenBCUserImages.user.js
+
+/*
+This is a Greasemonkey user script.
+
+To install, you need Greasemonkey: http://greasemonkey.mozdev.org/
+Then restart Firefox and revisit this script.
+Under Tools, there will be a new menu item to "Install User Script".
+Accept the default configuration and install.
+
+To uninstall, go to Tools/Manage User Scripts,
+select "OpenBCImageSize", and click Uninstall.
+*/
+
+(function() {
+ function cumulativeOffset(element) {
+ var valueT = 0, valueL = 0;
+ do {
+ valueT += element.offsetTop || 0;
+ valueL += element.offsetLeft || 0;
+ element = element.offsetParent;
+ } while (element);
+ return [valueL, valueT];
+ }
+
+
+ window.addEventListener("load", function(e) {
+ var imgList = document.getElementsByTagName("img");
+ for( i=0; i < imgList.length; i++) {
+ var imgName = imgList[i].src;
+ var s = imgName.search(/\/img\/users\/.+\_s(1|2|3)?\.(jpg|gif|png)$/);
+ if( s != -1) {
+ bigimage=imgName.replace(/\_s(1|2|3)?\./, ".");
+ newImg = document.createElement("img");
+
+ ow=imgList[i].width;
+ imgList[i].addEventListener("mouseover",
+ function(e){
+ newX=cumulativeOffset(this)[0]
+ newY=cumulativeOffset(this)[1]
+ newImg.src=this.src.replace(/\_s(1|2|3)?\./, ".");
+ newImg.style.width="140px";
+ newImg.style.height = "185px";
+ newImg.style.position="absolute";
+ newImg.style.zIndex='999';
+ newImg.style.top=(newY-185/2).toString() + 'px';
+ newImg.style.left=(newX+ow).toString() + 'px';
+ document.body.appendChild(newImg);
+ },false);
+ imgList[i].addEventListener("mouseout",
+ function(e){
+ document.body.removeChild(newImg);
+ },false);
+
+ }
+ }
+ return;
+ }, false);
+})();
+
diff --git a/twitterimagesmouseover.user.js b/twitterimagesmouseover.user.js
new file mode 100644
index 0000000..0f73138
--- /dev/null
+++ b/twitterimagesmouseover.user.js
@@ -0,0 +1,66 @@
+// ==UserScript==
+// @name Twitter UserImages MouseOver
+// @namespace
+// @description Shows big images when hovering over userImages
+// @include *twitter.com/*
+// ==/UserScript==
+// TwitterImages.user.js
+
+/*
+This is a Greasemonkey user script.
+
+To install, you need Greasemonkey: http://greasemonkey.mozdev.org/
+Then restart Firefox and revisit this script.
+Under Tools, there will be a new menu item to "Install User Script".
+Accept the default configuration and install.
+
+To uninstall, go to Tools/Manage User Scripts,
+select "OpenBCImageSize", and click Uninstall.
+*/
+
+(function() {
+ function cumulativeOffset(element) {
+ var valueT = 0, valueL = 0;
+ do {
+ valueT += element.offsetTop || 0;
+ valueL += element.offsetLeft || 0;
+ element = element.offsetParent;
+ } while (element);
+ return [valueL, valueT];
+ }
+
+
+ window.addEventListener("load", function(e) {
+ var imgList = document.getElementsByTagName("img");
+ for( i=0; i < imgList.length; i++) {
+ var imgName = imgList[i].src;
+ var s = imgName.search(/\/profile_images\/.*\/.+\_mini\.(jpg|gif|png)$/);
+ if( s != -1) {
+ bigimage=imgName.replace(/\_mini/, "");
+ newImg = document.createElement("img");
+
+ ow=imgList[i].width;
+ imgList[i].addEventListener("mouseover",
+ function(e){
+ newX=cumulativeOffset(this)[0]
+ newY=cumulativeOffset(this)[1]
+ newImg.src=this.src.replace(/\_s(1|2|3)?\./, ".");
+ newImg.style.width="140px";
+ newImg.style.height = "185px";
+ newImg.style.position="absolute";
+ newImg.style.zIndex='999';
+ newImg.style.top=(newY-185/2).toString() + 'px';
+ newImg.style.left=(newX+ow).toString() + 'px';
+ document.body.appendChild(newImg);
+ },false);
+ imgList[i].addEventListener("mouseout",
+ function(e){
+ document.body.removeChild(newImg);
+ },false);
+
+ }
+ }
+ return;
+ }, false);
+})();
+
|
codyps/wdfs
|
37a7df5e1b4da2ec5115db42a00ac19c565712f5
|
travis ci
|
diff --git a/.travis.yml b/.travis.yml
index d4cb4a8..2e290bd 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,9 +1,9 @@
before_script:
- sudo apt-get install libfuse-dev -y
- - sudo apt-get install libneon-dev -y
+ - sudo apt-get install libneon27-dev -y
script: ./configure && make
language: c
compiler:
- clang
- gcc
|
codyps/wdfs
|
5603483db2b0e6895c1a27f1f08f2369acd49131
|
travis ci
|
diff --git a/.travis.yml b/.travis.yml
index 9d2998d..d4cb4a8 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,6 +1,9 @@
+before_script:
+ - sudo apt-get install libfuse-dev -y
+ - sudo apt-get install libneon-dev -y
script: ./configure && make
language: c
compiler:
- clang
- gcc
|
codyps/wdfs
|
5e7e337916b284f8c30dfb128d0299f44085bf13
|
travis ci
|
diff --git a/README b/README
index 1e07677..cf621bb 100644
--- a/README
+++ b/README
@@ -1,129 +1,130 @@
abstract:
wdfs is a webdav filesystem with special features for accessing subversion
repositories. it is based on fuse v2.5+ and neon v0.24.7+.
author of wdfs:
(c) 2005 - 2007 jens m. noedler, [email protected]
license:
wdfs is distributed under the terms of the gnu general public license.
see file COPYING for details.
home and svn repository of wdfs:
http://noedler.de/projekte/wdfs/
http[s]://svn.projectai.org/svn/projects_private/wdfs/
features:
- generic webdav filesystem
- http redirect support
- https support
- file locking support (different modes)
- access to all revisions of a webdav exported subversion repository
- versioning filesystem for autoversioning enabled subversion repositories
(see section "wdfs, subversion and apache" in this document)
dependencies:
- operating systems: linux (kernel 2.4 or 2.6), freebsd (6.x or 7.x), mac os x
hint for linux user: using a kernel 2.6.15 or later is recommended.
- fuse (filesystem in userspace) v2.5 or later (http://fuse.sourceforge.net/)
- neon webdav library v0.24.7 or later (http://www.webdav.org/neon/)
installation:
$ tar xfz wdfs-1.x.x.tar.gz
$ cd wdfs-1.x.x
$ ./configure && make
$ su -c "make install"
usage:
$ mkdir ~/mountpoint
$ wdfs http[s]://server[:port][/directory/] ~/mountpoint [options]
$ wdfs -h # prints wdfs and fuse options
mounting wdfs using fstab:
example entry for the /etc/fstab file:
wdfs#http://server /mnt/wdfs fuse users,locking=simple 0 0
hint: due to a bug in fuse 2.6.3 and earlier it's not possible to add
the option "username=abc" to the option list. this will be fixed with
later versions of fuse.
wdfs, subversion and apache:
wdfs may be used to access subversion repositories that are exported as
webdav using the apache webserver. you need to load the required apache
modules for webdav and for subversion and add a location directive like
the following.
<Location "/svn">
DAV svn
SVNPath /home/jens/repositories/wdfs
SVNAutoversioning on
AuthType None
</Location>
version number conventions:
- the major number will never change.
- the minor number changes if new features are introduced or
if parts of the api are changed.
warning: this may include backward-incompatible changes!
- the last number changes on bug fixes and little non-api changes.
e.g. v1.1.0 introduced new features from it's predecessor v1.0.1
limitations of this implementation:
- wdfs is not (yet) multithread safe. it always uses fuse single thread mode.
- read/write of big files (~ 50 MB+) is slow, because the _complete_ file
will be GET/PUT on a request.
- svn mode: only up to 2^31-1 revisions can be accessed,
because "latest_revision" is an integer variable.
- svn mode: if a subdirectory of a subversion repository is mounted, the
"svn_basedir" shows the content of the repository root and not only the
content of the mounted subdir. [caused by svn_get_remotepath()]
- http redirect support:
* there is no redirect support for the mountpoint. please mount the new
location, that will be printed as an error message.
* the redirect support is limited to the webdav server, that is mounted.
redirects to another server are not supported.
limitations of wdfs, caused by other limitations:
- wdfs supports only utf-8 encoded file and directory names for svn access.
use utf8 capable applications or pure ascii (no iso8859!) encoded names.
(limitation caused by subversion, which stores all data utf-8 encoded)
- wdfs does not support setting file attributes with utime() or utimes().
(e.g. used by "touch file -m -t 200601010000"). see wdfs_setattr() for
details. (limitation caused by webdav specification rfc 2518)
source code conventions:
- variable name "remotepath" is used for WebDAV access (/remote/dir/file)
- variable name "localpath" is used for local access (/file)
- variable name "ret" is used for the return values of methods
- methods and structs starting with "ne_" are part of the neon library
- error output:
- "## " prefix for warnings and error messages
- debug output:
- ">> " prefix for fuse callback methods
- "** " prefix for cache related messages (no errors)
- "++ " prefix for locking related messages (no errors)
- the code is formated with tabs (tab width 4 characters)
- every line should not be longer than 80 characters
acknowledgements:
helmut neukirchen for supervising my bachelor thesis and the development
of wdfs. miklos szeredi for developing fuse and being a great maintainer.
the members of the fuse-devel mailing list for helping me and everybody
who is contributing to wdfs. thanks!
+
|
codyps/wdfs
|
c37cdf0e31e8f3dedd0e4897feda0e6c5602e722
|
travis ci
|
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..9d2998d
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,6 @@
+script: ./configure && make
+language: c
+compiler:
+ - clang
+ - gcc
+
|
codyps/wdfs
|
0b7c720c515f0945a0efc210471b4e6fd06aade3
|
comments
|
diff --git a/src/wdfs-main.c b/src/wdfs-main.c
index 98917b3..a1520df 100644
--- a/src/wdfs-main.c
+++ b/src/wdfs-main.c
@@ -1,571 +1,573 @@
/*
* this file is part of wdfs --> http://noedler.de/projekte/wdfs/
*
* wdfs is a webdav filesystem with special features for accessing subversion
* repositories. it is based on fuse v2.5+ and neon v0.24.7+.
*
* copyright (c) 2005 - 2007 jens m. noedler, [email protected]
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* This program is released under the GPL with the additional exemption
* that compiling, linking and/or using OpenSSL is allowed.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <assert.h>
#include <unistd.h>
#include <glib.h>
#include <fuse_opt.h>
#include <ne_props.h>
#include <ne_dates.h>
#include <ne_redirect.h>
#include "wdfs-main.h"
#include "webdav.h"
#include "cache.h"
#include "svn.h"
/* there are four locking modes available. the simple locking mode locks a file
* on open()ing it and unlocks it on close()ing the file. the advanced mode
* prevents data curruption by locking the file on open() and holds the lock
* until the file was writen and closed or the lock timed out. the eternity
* mode holds the lock until wdfs is unmounted or the lock times out. the last
* mode is to do no locking at all which is the default behaviour. */
#define NO_LOCK 0
#define SIMPLE_LOCK 1
#define ADVANCED_LOCK 2
#define ETERNITY_LOCK 3
static void print_help();
static int call_fuse_main(struct fuse_args *args);
+
+/* waitman - define these two for use in wdfs_create() */
static int wdfs_mknod(const char *localpath, mode_t mode, dev_t rdev);
static int wdfs_open(const char *localpath, struct fuse_file_info *fi);
/* define package name and version if config.h is not available. */
#ifndef HAVE_CONFIG_H
#define PACKAGE_NAME "wdfs"
#define PACKAGE_VERSION "unknown"
#endif
/* product string according RFC 2616, that is included in every request. */
const char *project_name = PACKAGE_NAME"/"PACKAGE_VERSION;
/* homepage of this filesystem */
const char *project_uri = "http://noedler.de/projekte/wdfs/";
/* init settings with default values */
struct wdfs_conf wdfs = {
.debug = false,
.accept_certificate = false,
.username = NULL,
.password = NULL,
.redirect = true,
.svn_mode = false,
.locking_mode = NO_LOCK,
.locking_timeout = 300,
.webdav_resource = NULL,
};
enum {
KEY_HELP,
KEY_VERSION,
KEY_VERSION_FULL,
KEY_DEBUG,
KEY_LOCKING_MODE,
KEY_NOOP,
};
#define WDFS_OPT(t, p, v) { t, offsetof(struct wdfs_conf, p), v }
static struct fuse_opt wdfs_opts[] = {
FUSE_OPT_KEY("-h", KEY_HELP),
FUSE_OPT_KEY("--help", KEY_HELP),
FUSE_OPT_KEY("-v", KEY_VERSION),
FUSE_OPT_KEY("--version", KEY_VERSION),
FUSE_OPT_KEY("-vv", KEY_VERSION_FULL),
FUSE_OPT_KEY("--all-versions", KEY_VERSION_FULL),
FUSE_OPT_KEY("-D", KEY_DEBUG),
FUSE_OPT_KEY("wdfs_debug", KEY_DEBUG),
FUSE_OPT_KEY("-m %u", KEY_LOCKING_MODE),
FUSE_OPT_KEY("-a", KEY_NOOP),
WDFS_OPT("-D", debug, true),
WDFS_OPT("wdfs_debug", debug, true),
WDFS_OPT("-ac", accept_certificate, true),
WDFS_OPT("accept_sslcert", accept_certificate, true),
WDFS_OPT("-u %s", username, 0),
WDFS_OPT("username=%s", username, 0),
WDFS_OPT("-p %s", password, 0),
WDFS_OPT("password=%s", password, 0),
WDFS_OPT("no_redirect", redirect, false),
WDFS_OPT("-S", svn_mode, true),
WDFS_OPT("svn_mode", svn_mode, true),
WDFS_OPT("-l", locking_mode, SIMPLE_LOCK),
WDFS_OPT("locking", locking_mode, SIMPLE_LOCK),
WDFS_OPT("locking=0", locking_mode, NO_LOCK),
WDFS_OPT("locking=none", locking_mode, NO_LOCK),
WDFS_OPT("locking=1", locking_mode, SIMPLE_LOCK),
WDFS_OPT("locking=simple", locking_mode, SIMPLE_LOCK),
WDFS_OPT("locking=2", locking_mode, ADVANCED_LOCK),
WDFS_OPT("locking=advanced", locking_mode, ADVANCED_LOCK),
WDFS_OPT("locking=3", locking_mode, ETERNITY_LOCK),
WDFS_OPT("locking=eternity", locking_mode, ETERNITY_LOCK),
WDFS_OPT("-t %u", locking_timeout, 300),
WDFS_OPT("locking_timeout=%u", locking_timeout, 300),
FUSE_OPT_END
};
static int wdfs_opt_proc(
void *data, const char *option, int key, struct fuse_args *option_list)
{
switch (key) {
case KEY_HELP:
print_help();
fuse_opt_add_arg(option_list, "-ho");
call_fuse_main(option_list);
exit(1);
case KEY_VERSION:
fprintf(stderr, "%s version: %s\n", PACKAGE_NAME, PACKAGE_VERSION);
exit(0);
case KEY_VERSION_FULL:
fprintf(stderr, "%s version: %s\n", PACKAGE_NAME, PACKAGE_VERSION);
fprintf(stderr, "%s homepage: %s\n", PACKAGE_NAME, project_uri);
fprintf(stderr, "neon version: 0.%d\n", NEON_VERSION);
fuse_opt_add_arg(option_list, "--version");
call_fuse_main(option_list);
exit(0);
case KEY_DEBUG:
return fuse_opt_add_arg(option_list, "-f");
case KEY_LOCKING_MODE:
if (option[3] != '\0' || option[2] < '0' || option[2] > '3') {
fprintf(stderr, "%s: unknown locking mode '%s'\n",
wdfs.program_name, option + 2);
exit(1);
} else {
wdfs.locking_mode = option[2] - '0';
}
return 0;
case KEY_NOOP:
return 0;
case FUSE_OPT_KEY_NONOPT:
if (wdfs.webdav_resource == NULL &&
strncmp(option, "http", 4) == 0) {
wdfs.webdav_resource = strdup(option);
return 0;
}
return 1;
case FUSE_OPT_KEY_OPT:
return 1;
default:
fprintf(stderr, "%s: unknown option '%s'\n",
wdfs.program_name, option);
exit(1);
}
}
/* webdav server base directory. if you are connected to "http://server/dir/"
* remotepath_basedir is set to "/dir" (starting slash, no ending slash).
* if connected to the root directory (http://server/) it will be set to "". */
char *remotepath_basedir;
/* infos about an open file. used by open(), read(), write() and release() */
struct open_file {
unsigned long fh; /* this file's filehandle */
bool_t modified; /* set true if the filehandle's content is modified */
};
/* webdav properties used to get file attributes */
static const ne_propname properties_fileattr[] = {
{ "DAV:", "resourcetype" },
{ "DAV:", "getcontentlength" },
{ "DAV:", "getlastmodified" },
{ "DAV:", "creationdate" },
{ NULL } /* MUST be NULL terminated! */
};
/* +++ exported method +++ */
/* free()s each char passed that is not NULL and sets it to NULL after freeing */
void free_chars(char **arg, ...)
{
va_list ap;
va_start(ap, arg);
while (arg) {
if (*arg != NULL)
free(*arg);
*arg = NULL;
/* get the next parameter */
arg = va_arg(ap, char **);
}
va_end(ap);
}
/* removes all trailing slashes from the path.
* returns the new malloc()d path or NULL on error. */
char* remove_ending_slashes(const char *path)
{
char *new_path = strdup(path);
int pos = strlen(path) - 1;
while(pos >= 0 && new_path[pos] == '/')
new_path[pos--] = '\0';
return new_path;
}
/* unifies the given path by removing the ending slash and escaping or
* unescaping the path. returns the new malloc()d string or NULL on error. */
char* unify_path(const char *path_in, int mode)
{
assert(path_in);
char *path_tmp, *path_out = NULL;
path_tmp = strdup(path_in);
if (path_tmp == NULL)
return NULL;
/* some servers send the complete URI not only the path.
* hence remove the server part and use the path only.
* example1: before: "https://server.com/path/to/hell/"
* after: "/path/to/hell/"
* example2: before: "http://server.com"
* after: "" */
if (g_str_has_prefix(path_tmp, "http")) {
char *tmp0 = strdup(path_in);
FREE(path_tmp);
/* jump to the 1st '/' of http[s]:// */
char *tmp1 = strchr(tmp0, '/');
/* jump behind '//' and get the next '/'. voila: the path! */
char *tmp2 = strchr(tmp1 + 2, '/');
if (tmp2 == NULL)
path_tmp = strdup("");
else
path_tmp = strdup(tmp2);
FREE(tmp0);
}
if (mode & LEAVESLASH) {
mode &= ~LEAVESLASH;
} else {
path_tmp = remove_ending_slashes(path_tmp);
}
if (path_tmp == NULL)
return NULL;
switch (mode) {
case ESCAPE:
path_out = ne_path_escape(path_tmp);
break;
case UNESCAPE:
path_out = ne_path_unescape(path_tmp);
break;
default:
fprintf(stderr, "## fatal error: unknown mode in %s()\n", __func__);
exit(1);
}
FREE(path_tmp);
if (path_out == NULL)
return NULL;
return path_out;
}
/* mac os x lacks support for strndup() because it's a gnu extension.
* be gentle to the apples and define the required method. */
#ifndef HAVE_STRNDUP
char* strndup(const char *str, size_t len1)
{
size_t len2 = strlen(str);
if (len1 < len2)
len2 = len1;
char *result = (char *)malloc(len2 + 1);
if (result == NULL)
return NULL;
result[len2] = '\0';
return (char *)memcpy(result, str, len2);
}
#endif
/* +++ helper methods +++ */
/* this method prints some debug output and sets the http user agent string to
* a more informative value. */
static void print_debug_infos(const char *method, const char *parameter)
{
assert(method);
fprintf(stderr, ">> %s(%s)\n", method, parameter);
char *useragent =
ne_concat(project_name, " ", method, "(", parameter, ")", NULL);
ne_set_useragent(session, useragent);
FREE(useragent);
}
/* returns the malloc()ed escaped remotepath on success or NULL on error */
static char* get_remotepath(const char *localpath)
{
assert(localpath);
char *remotepath = ne_concat(remotepath_basedir, localpath, NULL);
if (remotepath == NULL)
return NULL;
char *remotepath2 = unify_path(remotepath, ESCAPE | LEAVESLASH);
FREE(remotepath);
if (remotepath2 == NULL)
return NULL;
return remotepath2;
}
/* returns a filehandle for read and write on success or -1 on error */
static int get_filehandle()
{
char dummyfile[] = "/tmp/wdfs-tmp-XXXXXX";
/* mkstemp() replaces XXXXXX by unique random chars and
* returns a filehandle for reading and writing */
int fh = mkstemp(dummyfile);
if (fh == -1)
fprintf(stderr, "## mkstemp(%s) error\n", dummyfile);
if (unlink(dummyfile))
fprintf(stderr, "## unlink() error\n");
return fh;
}
/* evaluates the propfind result set and sets the file's attributes (stat) */
static void set_stat(struct stat* stat, const ne_prop_result_set *results)
{
if (wdfs.debug == true)
print_debug_infos(__func__, "");
const char *resourcetype, *contentlength, *lastmodified, *creationdate;
assert(stat && results);
memset(stat, 0, sizeof(struct stat));
/* get the values from the propfind result set */
resourcetype = ne_propset_value(results, &properties_fileattr[0]);
contentlength = ne_propset_value(results, &properties_fileattr[1]);
lastmodified = ne_propset_value(results, &properties_fileattr[2]);
creationdate = ne_propset_value(results, &properties_fileattr[3]);
/* webdav collection == directory entry */
if (resourcetype != NULL && !strstr("<collection", resourcetype)) {
/* "DT_DIR << 12" equals "S_IFDIR" */
stat->st_mode = S_IFDIR | 0777;
stat->st_size = 4096;
} else {
stat->st_mode = S_IFREG | 0666;
if (contentlength != NULL)
stat->st_size = atoll(contentlength);
else
stat->st_size = 0;
}
stat->st_nlink = 1;
stat->st_atime = time(NULL);
if (lastmodified != NULL)
stat->st_mtime = ne_rfc1123_parse(lastmodified);
else
stat->st_mtime = 0;
if (creationdate != NULL)
stat->st_ctime = ne_iso8601_parse(creationdate);
else
stat->st_ctime = 0;
/* calculate number of 512 byte blocks */
stat->st_blocks = (stat->st_size + 511) / 512;
/* no need to set a restrict mode, because fuse filesystems can
* only be accessed by the user that mounted the filesystem. */
stat->st_mode &= ~umask(0);
stat->st_uid = getuid();
stat->st_gid = getgid();
}
/* this method is invoked, if a redirect needs to be done. therefore the current
* remotepath is freed and set to the redirect target. returns -1 and prints an
* error if the current host and new host differ. returns 0 on success and -1
* on error. side effect: remotepath is freed on error. */
static int handle_redirect(char **remotepath)
{
if (wdfs.debug == true)
print_debug_infos(__func__, *remotepath);
/* free the old value of remotepath, because it's no longer needed */
FREE(*remotepath);
/* get the current_uri and new_uri structs */
ne_uri current_uri;
ne_fill_server_uri(session, ¤t_uri);
const ne_uri *new_uri = ne_redirect_location(session);
if (strcasecmp(current_uri.host, new_uri->host)) {
fprintf(stderr,
"## error: wdfs does not support redirecting to another host!\n");
free_chars(¤t_uri.host, ¤t_uri.scheme, NULL);
return -1;
}
/* can't use ne_uri_free() here, because only host and scheme are mallocd */
free_chars(¤t_uri.host, ¤t_uri.scheme, NULL);
/* set the new remotepath to the redirect target path */
*remotepath = ne_strdup(new_uri->path);
return 0;
}
/* +++ fuse callback methods +++ */
/* this method is called by ne_simple_propfind() from wdfs_getattr() for a
* specific file. it sets the file's attributes and and them to the cache. */
static void wdfs_getattr_propfind_callback(
#if NEON_VERSION >= 26
void *userdata, const ne_uri* href_uri, const ne_prop_result_set *results)
#else
void *userdata, const char *remotepath, const ne_prop_result_set *results)
#endif
{
#if NEON_VERSION >= 26
char *remotepath = ne_uri_unparse(href_uri);
#endif
if (wdfs.debug == true)
print_debug_infos(__func__, remotepath);
struct stat *stat = (struct stat*)userdata;
memset(stat, 0, sizeof(struct stat));
assert(stat && remotepath);
set_stat(stat, results);
cache_add_item(stat, remotepath);
#if NEON_VERSION >= 26
FREE(remotepath);
#endif
}
/* this method returns the file attributes (stat) for a requested file either
* from the cache or directly from the webdav server by performing a propfind
* request. */
static int wdfs_getattr(const char *localpath, struct stat *stat)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath && stat);
char *remotepath;
/* for details about the svn_mode, please have a look at svn.c */
/* get the stat for the svn_basedir, if localpath equals svn_basedir. */
if (wdfs.svn_mode == true && !strcmp(localpath, svn_basedir)) {
*stat = svn_get_static_dir_stat();
return 0;
}
/* if svn_mode is enabled and string localpath starts with svn_basedir... */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir)) {
/* ...get stat for the level 1 directories... */
if (svn_get_level1_stat(stat, localpath) == 0) {
return 0;
/* ...or get remotepath and go on. */
} else {
remotepath = svn_get_remotepath(localpath);
}
/* normal mode; no svn mode */
} else {
remotepath = get_remotepath(localpath);
}
if (remotepath == NULL)
return -ENOMEM;
/* stat not found in the cache? perform a propfind to get stat! */
if (cache_get_item(stat, remotepath)) {
int ret = ne_simple_propfind(
session, remotepath, NE_DEPTH_ZERO, properties_fileattr,
wdfs_getattr_propfind_callback, stat);
/* handle the redirect and retry the propfind with the new target */
if (ret == NE_REDIRECT && wdfs.redirect == true) {
if (handle_redirect(&remotepath))
return -ENOENT;
ret = ne_simple_propfind(
session, remotepath, NE_DEPTH_ZERO, properties_fileattr,
wdfs_getattr_propfind_callback, stat);
}
if (ret != NE_OK) {
fprintf(stderr, "## PROPFIND error in %s(): %s\n",
__func__, ne_get_error(session));
FREE(remotepath);
return -ENOENT;
}
}
FREE(remotepath);
return 0;
}
/* this method is called by ne_simple_propfind() from wdfs_readdir() for each
* member (file) of the requested collection. this method extracts the file's
* attributes from the webdav response, adds it to the cache and calls the fuse
* filler method to add the file to the requested directory. */
static void wdfs_readdir_propfind_callback(
#if NEON_VERSION >= 26
void *userdata, const ne_uri* href_uri, const ne_prop_result_set *results)
#else
void *userdata, const char *remotepath0, const ne_prop_result_set *results)
#endif
{
@@ -767,670 +769,670 @@ static int wdfs_read(
off_t offset, struct fuse_file_info *fi)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath && buf && &fi);
struct open_file *file = (struct open_file*)(uintptr_t)fi->fh;
int ret = pread(file->fh, buf, size, offset);
if (ret < 0) {
fprintf(stderr, "## pread() error: %d\n", ret);
return -EIO;
}
return ret;
}
/* writes data to the filehandle with pwrite() to fulfill write requests */
static int wdfs_write(
const char *localpath, const char *buf, size_t size,
off_t offset, struct fuse_file_info *fi)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath && buf && &fi);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
return -EROFS;
struct open_file *file = (struct open_file*)(uintptr_t)fi->fh;
int ret = pwrite(file->fh, buf, size, offset);
if (ret < 0) {
fprintf(stderr, "## pwrite() error: %d\n", ret);
return -EIO;
}
/* set this flag, to indicate that data has been modified and needs to be
* put to the webdav server. */
file->modified = true;
return ret;
}
/* author jens, 13.08.2005 11:28:40, location: unknown, refactored in goettingen
* wdfs_release is called by fuse, when the last reference to the filehandle is
* removed. this happens if the file is closed. after closing the file it's
* time to put it to the server, but only if it was modified. */
static int wdfs_release(const char *localpath, struct fuse_file_info *fi)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
struct open_file *file = (struct open_file*)(uintptr_t)fi->fh;
char *remotepath = get_remotepath(localpath);
if (remotepath == NULL)
return -ENOMEM;
/* put the file only to the server, if it was modified. */
if (file->modified == true) {
if (ne_put(session, remotepath, file->fh)) {
fprintf(stderr, "## PUT error: %s\n", ne_get_error(session));
FREE(remotepath);
return -EIO;
}
if (wdfs.debug == true)
fprintf(stderr, ">> wdfs_release(): PUT the file to the server.\n");
/* attributes for this file are no longer up to date.
* so remove it from cache. */
cache_delete_item(remotepath);
/* unlock if locking is enabled and mode is ADVANCED_LOCK, because data
* has been read and writen and so now it's time to remove the lock. */
if (wdfs.locking_mode == ADVANCED_LOCK) {
if (unlockfile(remotepath)) {
FREE(remotepath);
return -EACCES;
}
}
}
/* if locking is enabled and mode is SIMPLE_LOCK, simple unlock on close() */
if (wdfs.locking_mode == SIMPLE_LOCK) {
if (unlockfile(remotepath)) {
FREE(remotepath);
return -EACCES;
}
}
/* close filehandle and free memory */
close(file->fh);
FREE(file);
FREE(remotepath);
return 0;
}
/* author jens, 13.08.2005 11:32:20, location: unknown, refactored in goettingen
* wdfs_truncate is called by fuse, when a file is opened with the O_TRUNC flag
* or truncate() is called. according to 'man truncate' if the file previously
* was larger than this size, the extra data is lost. if the file previously
* was shorter, it is extended, and the extended part is filled with zero bytes.
*/
static int wdfs_truncate(const char *localpath, off_t size)
{
if (wdfs.debug == true) {
print_debug_infos(__func__, localpath);
fprintf(stderr, ">> truncate() at offset %li\n", (long int)size);
}
assert(localpath);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
return -EROFS;
/* the truncate procedure:
* 1. get the complete file and write into fh_in
* 2. read size bytes from fh_in to buffer
* 3. write size bytes from buffer to fh_out
* 4. read from fh_out and put file to the server
*/
char *remotepath = get_remotepath(localpath);
if (remotepath == NULL)
return -ENOMEM;
int ret;
int fh_in = get_filehandle();
int fh_out = get_filehandle();
if (fh_in == -1 || fh_out == -1)
return -EIO;
char buffer[size];
memset(buffer, 0, size);
/* if truncate(0) is called, there is no need to get the data, because it
* would not be used. */
if (size != 0) {
if (ne_get(session, remotepath, fh_in)) {
fprintf(stderr, "## GET error: %s\n", ne_get_error(session));
close(fh_in);
close(fh_out);
FREE(remotepath);
return -ENOENT;
}
ret = pread(fh_in, buffer, size, 0);
if (ret < 0) {
fprintf(stderr, "## pread() error: %d\n", ret);
close(fh_in);
close(fh_out);
FREE(remotepath);
return -EIO;
}
}
ret = pwrite(fh_out, buffer, size, 0);
if (ret < 0) {
fprintf(stderr, "## pwrite() error: %d\n", ret);
close(fh_in);
close(fh_out);
FREE(remotepath);
return -EIO;
}
if (ne_put(session, remotepath, fh_out)) {
fprintf(stderr, "## PUT error: %s\n", ne_get_error(session));
close(fh_in);
close(fh_out);
FREE(remotepath);
return -EIO;
}
/* stat for this file is no longer up to date. remove it from the cache. */
cache_delete_item(remotepath);
close(fh_in);
close(fh_out);
FREE(remotepath);
return 0;
}
/* author jens, 12.03.2006 19:44:23, location: goettingen in the winter
* ftruncate is called on already opened files, truncate on not yet opened
* files. ftruncate is supported since wdfs 1.2.0 and needs at least
* fuse 2.5.0 and linux kernel 2.6.15. */
static int wdfs_ftruncate(
const char *localpath, off_t size, struct fuse_file_info *fi)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath && &fi);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
return -EROFS;
char *remotepath = get_remotepath(localpath);
if (remotepath == NULL)
return -ENOMEM;
struct open_file *file = (struct open_file*)(uintptr_t)fi->fh;
int ret = ftruncate(file->fh, size);
if (ret < 0) {
fprintf(stderr, "## ftruncate() error: %d\n", ret);
FREE(remotepath);
return -EIO;
}
/* set this flag, to indicate that data has been modified and needs to be
* put to the webdav server. */
file->modified = true;
/* update the cache item of the ftruncate()d file */
struct stat stat;
if (cache_get_item(&stat, remotepath) < 0) {
fprintf(stderr,
"## cache_get_item() error: item '%s' not found!\n", remotepath);
FREE(remotepath);
return -EIO;
}
/* set the new size after the ftruncate() call */
stat.st_size = size;
/* calculate number of 512 byte blocks */
stat.st_blocks = (stat.st_size + 511) / 512;
/* update the cache */
cache_add_item(&stat, remotepath);
FREE(remotepath);
return 0;
}
/* author waitman, 08.11.2015 implement create for fuse */
static int wdfs_create(const char *localpath, mode_t mode, struct fuse_file_info *fi)
{
int ret;
dev_t rdev;
rdev = (dev_t)0;
ret = wdfs_mknod(localpath,mode,rdev);
if (ret!=0)
{
return ret;
}
ret = wdfs_open(localpath, fi);
return ret;
}
/* author jens, 28.07.2005 18:15:12, location: noedlers garden in trubenhausen
* this method creates a empty file using the webdav method put. */
static int wdfs_mknod(const char *localpath, mode_t mode, dev_t rdev)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
return -EROFS;
char *remotepath = get_remotepath(localpath);
if (remotepath == NULL)
return -ENOMEM;
int fh = get_filehandle();
if (fh == -1) {
FREE(remotepath);
return -EIO;
}
if (ne_put(session, remotepath, fh)) {
fprintf(stderr, "## PUT error: %s\n", ne_get_error(session));
close(fh);
FREE(remotepath);
return -EIO;
}
close(fh);
FREE(remotepath);
return 0;
}
/* author jens, 03.08.2005 12:03:40, location: goettingen
* this method creates a directory / collection using the webdav method mkcol. */
static int wdfs_mkdir(const char *localpath, mode_t mode)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
return -EROFS;
char *remotepath = get_remotepath(localpath);
if (remotepath == NULL)
return -ENOMEM;
if (ne_mkcol(session, remotepath)) {
fprintf(stderr, "MKCOL error: %s\n", ne_get_error(session));
FREE(remotepath);
return -ENOENT;
}
FREE(remotepath);
return 0;
}
/* author jens, 30.07.2005 13:08:11, location: heli at heinemanns
* this methods removes a file or directory using the webdav method delete. */
static int wdfs_unlink(const char *localpath)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
return -EROFS;
char *remotepath = get_remotepath(localpath);
if (remotepath == NULL)
return -ENOMEM;
/* unlock the file, to be able to unlink it */
if (wdfs.locking_mode != NO_LOCK) {
if (unlockfile(remotepath)) {
FREE(remotepath);
return -EACCES;
}
}
int ret = ne_delete(session, remotepath);
if (ret == NE_REDIRECT && wdfs.redirect == true) {
if (handle_redirect(&remotepath))
return -ENOENT;
ret = ne_delete(session, remotepath);
}
/* file successfully deleted! remove it also from the cache. */
if (ret == 0) {
cache_delete_item(remotepath);
/* return more specific error message in case of permission problems */
} else if (!strcmp(ne_get_error(session), "403 Forbidden")) {
ret = -EPERM;
} else {
fprintf(stderr, "## DELETE error: %s\n", ne_get_error(session));
ret = -EIO;
}
FREE(remotepath);
return ret;
}
/* author jens, 31.07.2005 19:13:39, location: heli at heinemanns
* this methods renames a file. it uses the webdav method move to do that. */
static int wdfs_rename(const char *localpath_src, const char *localpath_dest)
{
if (wdfs.debug == true) {
print_debug_infos(__func__, localpath_src);
print_debug_infos(__func__, localpath_dest);
}
assert(localpath_src && localpath_dest);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true &&
(g_str_has_prefix(localpath_src, svn_basedir) ||
g_str_has_prefix(localpath_dest, svn_basedir)))
return -EROFS;
char *remotepath_src = get_remotepath(localpath_src);
char *remotepath_dest = get_remotepath(localpath_dest);
if (remotepath_src == NULL || remotepath_dest == NULL )
return -ENOMEM;
/* unlock the source file, before renaming */
if (wdfs.locking_mode != NO_LOCK) {
if (unlockfile(remotepath_src)) {
FREE(remotepath_src);
return -EACCES;
}
}
int ret = ne_move(session, 1, remotepath_src, remotepath_dest);
if (ret == NE_REDIRECT && wdfs.redirect == true) {
if (handle_redirect(&remotepath_src))
return -ENOENT;
ret = ne_move(session, 1, remotepath_src, remotepath_dest);
}
if (ret == 0) {
/* rename was successful and the source file no longer exists.
* hence, remove it from the cache. */
cache_delete_item(remotepath_src);
} else {
fprintf(stderr, "## MOVE error: %s\n", ne_get_error(session));
ret = -EIO;
}
free_chars(&remotepath_src, &remotepath_dest, NULL);
return ret;
}
/* this is just a dummy implementation to avoid errors, when running chmod. */
int wdfs_chmod(const char *localpath, mode_t mode)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
fprintf(stderr, "## error: chmod() is not (yet) implemented.\n");
return 0;
}
/* this is just a dummy implementation to avoid errors, when setting attributes.
* a usefull implementation is not possible, because the webdav standard only
* defines a "getlastmodified" property that is read-only and just updated when
* the file's content or properties change. */
static int wdfs_setattr(const char *localpath, struct utimbuf *buf)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
return 0;
}
/* this is a dummy implementation that pretends to have 1000 GB free space :D */
static int wdfs_statfs(const char *localpath, struct statvfs *buf)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
/* taken from sshfs v1.7, thanks miklos! */
buf->f_bsize = 512;
buf->f_blocks = buf->f_bfree = buf->f_bavail =
1000ULL * 1024 * 1024 * 1024 / buf->f_bsize;
buf->f_files = buf->f_ffree = 1000000000;
return 0;
}
/* just say hello when fuse takes over control. */
#if FUSE_VERSION >= 26
static void* wdfs_init(struct fuse_conn_info *conn)
#else
static void* wdfs_init()
#endif
{
if (wdfs.debug == true)
fprintf(stderr, ">> %s()\n", __func__);
return NULL;
}
/* author jens, 04.08.2005 17:41:12, location: goettingen
* this method is called, when the filesystems is unmounted. time to clean up! */
static void wdfs_destroy()
{
if (wdfs.debug == true)
fprintf(stderr, ">> freeing globaly used memory\n");
/* free globaly used memory */
cache_destroy();
unlock_all_files();
ne_session_destroy(session);
FREE(remotepath_basedir);
svn_free_repository_root();
}
static struct fuse_operations wdfs_operations = {
- .create = wdfs_create,
+ .create = wdfs_create, /* added by waitman */
.getattr = wdfs_getattr,
.readdir = wdfs_readdir,
.open = wdfs_open,
.read = wdfs_read,
.write = wdfs_write,
.release = wdfs_release,
.truncate = wdfs_truncate,
.ftruncate = wdfs_ftruncate,
.mknod = wdfs_mknod,
.mkdir = wdfs_mkdir,
/* webdav treats file and directory deletions equal, both use wdfs_unlink */
.unlink = wdfs_unlink,
.rmdir = wdfs_unlink,
.rename = wdfs_rename,
.chmod = wdfs_chmod,
/* utime should be better named setattr
* see: http://sourceforge.net/mailarchive/message.php?msg_id=11344401 */
.utime = wdfs_setattr,
.statfs = wdfs_statfs,
.init = wdfs_init,
.destroy = wdfs_destroy,
};
/* author jens, 26.08.2005 12:26:59, location: lystrup near aarhus
* this method prints help and usage information, call fuse to print its
* help information. */
static void print_help()
{
fprintf(stderr,
"usage: %s http[s]://server[:port][/directory/] mountpoint [options]\n\n"
"wdfs options:\n"
" -v, --version show version of wdfs\n"
" -vv, --all-versions show versions of wdfs, neon and fuse\n"
" -h, --help show this help page\n"
" -D, -o wdfs_debug enable wdfs debug output\n"
" -o accept_sslcert accept ssl certificate, don't prompt the user\n"
" -o username=arg replace arg with username of the webdav resource\n"
" -o password=arg replace arg with password of the webdav resource\n"
" username/password can also be entered interactively\n"
" -o no_redirect disable http redirect support\n"
" -o svn_mode enable subversion mode to access all revisions\n"
" -o locking same as -o locking=simple\n"
" -o locking=mode select a file locking mode:\n"
" 0 or none: disable file locking (default)\n"
" 1 or simple: from open until close\n"
" 2 or advanced: from open until write + close\n"
" 3 or eternity: from open until umount or timeout\n"
" -o locking_timeout=sec timeout for a lock in seconds, -1 means infinite\n"
" default is 300 seconds (5 minutes)\n\n"
"wdfs backwards compatibility options: (used until wdfs 1.3.1)\n"
" -a uri address of the webdav resource to mount\n"
" -ac same as -o accept_sslcert\n"
" -u arg same as -o username=arg\n"
" -p arg same as -o password=arg\n"
" -S same as -o svn_mode\n"
" -l same as -o locking=simple\n"
" -m locking_mode same as -o locking=mode (only numerical modes)\n"
" -t seconds same as -o locking_timeout=sec\n\n",
wdfs.program_name);
}
/* just a simple wrapper for fuse_main(), because the interface changed... */
static int call_fuse_main(struct fuse_args *args)
{
#if FUSE_VERSION >= 26
return fuse_main(args->argc, args->argv, &wdfs_operations, NULL);
#else
return fuse_main(args->argc, args->argv, &wdfs_operations);
#endif
}
/* the main method does the option parsing using fuse_opt_parse(), establishes
* the connection to the webdav resource and finally calls main_fuse(). */
int main(int argc, char *argv[])
{
int status_program_exec = 1;
struct fuse_args options = FUSE_ARGS_INIT(argc, argv);
wdfs.program_name = argv[0];
if (fuse_opt_parse(&options, &wdfs, wdfs_opts, wdfs_opt_proc) == -1)
exit(1);
if (!wdfs.webdav_resource) {
fprintf(stderr, "%s: missing webdav uri\n", wdfs.program_name);
exit(1);
}
if (wdfs.locking_timeout < -1 || wdfs.locking_timeout == 0) {
fprintf(stderr, "## error: timeout must be bigger than 0 or -1!\n");
exit(1);
}
if (wdfs.debug == true) {
fprintf(stderr,
"wdfs settings:\n program_name: %s\n webdav_resource: %s\n"
" accept_certificate: %s\n username: %s\n password: %s\n"
" redirect: %s\n svn_mode: %s\n locking_mode: %i\n"
" locking_timeout: %i\n",
wdfs.program_name,
wdfs.webdav_resource ? wdfs.webdav_resource : "NULL",
wdfs.accept_certificate == true ? "true" : "false",
wdfs.username ? wdfs.username : "NULL",
wdfs.password ? "****" : "NULL",
wdfs.redirect == true ? "true" : "false",
wdfs.svn_mode == true ? "true" : "false",
wdfs.locking_mode, wdfs.locking_timeout);
}
/* set a nice name for /proc/mounts */
char *fsname = ne_concat("-ofsname=wdfs (", wdfs.webdav_resource, ")", NULL);
fuse_opt_add_arg(&options, fsname);
FREE(fsname);
/* ensure that wdfs is called in single thread mode */
fuse_opt_add_arg(&options, "-s");
/* wdfs must not use the fuse caching of names (entries) and attributes! */
fuse_opt_add_arg(&options, "-oentry_timeout=0");
fuse_opt_add_arg(&options, "-oattr_timeout=0");
/* reset parameters to avoid storing sensitive data in the process table */
int arg_number = 1;
for (; arg_number < argc; arg_number++)
memset(argv[arg_number], 0, strlen(argv[arg_number]));
/* set up webdav connection, exit on error */
if (setup_webdav_session(wdfs.webdav_resource, wdfs.username, wdfs.password)) {
status_program_exec = 1;
goto cleanup;
}
if (wdfs.svn_mode == true) {
if(svn_set_repository_root()) {
fprintf(stderr,
"## error: could not set subversion repository root.\n");
ne_session_destroy(session);
status_program_exec = 1;
goto cleanup;
}
}
cache_initialize();
/* finally call fuse */
status_program_exec = call_fuse_main(&options);
/* clean up and quit wdfs */
cleanup:
free_chars(&wdfs.webdav_resource, &wdfs.username, &wdfs.password, NULL);
fuse_opt_free_args(&options);
return status_program_exec;
}
|
codyps/wdfs
|
1801ab8c4679e88d1fb1760a404bd256bfcc6a97
|
gitignore
|
diff --git a/.gitignore b/.gitignore
index efd0e29..2e57bce 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,8 @@
*.log
.deps
src/.deps/
Makefile
+src/Makefile
*.status
src/config.h
src/stamp-h1
diff --git a/src/Makefile b/src/Makefile
deleted file mode 100644
index d59bdd0..0000000
--- a/src/Makefile
+++ /dev/null
@@ -1,427 +0,0 @@
-# Makefile.in generated by automake 1.9.6 from Makefile.am.
-# src/Makefile. Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005 Free Software Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-
-srcdir = .
-top_srcdir = ..
-
-pkgdatadir = $(datadir)/wdfs
-pkglibdir = $(libdir)/wdfs
-pkgincludedir = $(includedir)/wdfs
-top_builddir = ..
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-INSTALL = /usr/bin/install -c
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-bin_PROGRAMS = wdfs$(EXEEXT)
-subdir = src
-DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \
- $(srcdir)/config.h.in
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
- $(ACLOCAL_M4)
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = config.h
-CONFIG_CLEAN_FILES =
-am__installdirs = "$(DESTDIR)$(bindir)"
-binPROGRAMS_INSTALL = $(INSTALL_PROGRAM)
-PROGRAMS = $(bin_PROGRAMS)
-am_wdfs_OBJECTS = cache.$(OBJEXT) svn.$(OBJEXT) wdfs-main.$(OBJEXT) \
- webdav.$(OBJEXT)
-wdfs_OBJECTS = $(am_wdfs_OBJECTS)
-wdfs_LDADD = $(LDADD)
-DEFAULT_INCLUDES = -I. -I$(srcdir) -I.
-depcomp = $(SHELL) $(top_srcdir)/depcomp
-am__depfiles_maybe = depfiles
-COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
- $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
-CCLD = $(CC)
-LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
-SOURCES = $(wdfs_SOURCES)
-DIST_SOURCES = $(wdfs_SOURCES)
-ETAGS = etags
-CTAGS = ctags
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-ACLOCAL = ${SHELL} /xj/waitman/wdfs/missing --run aclocal-1.9
-AMDEP_FALSE = #
-AMDEP_TRUE =
-AMTAR = ${SHELL} /xj/waitman/wdfs/missing --run tar
-AUTOCONF = ${SHELL} /xj/waitman/wdfs/missing --run autoconf
-AUTOHEADER = ${SHELL} /xj/waitman/wdfs/missing --run autoheader
-AUTOMAKE = ${SHELL} /xj/waitman/wdfs/missing --run automake-1.9
-AWK = nawk
-CC = cc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2 -I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include -Wall -D_GNU_SOURCE -D_REENTRANT
-CPP = cc -E
-CPPFLAGS =
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-ECHO_C =
-ECHO_N = -n
-ECHO_T =
-EGREP = /usr/bin/grep -E
-EXEEXT =
-GREP = /usr/bin/grep
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = ${SHELL} $(install_sh) -c -s
-LDFLAGS =
-LIBOBJS =
-LIBS = -L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl
-LTLIBOBJS =
-MAKEINFO = ${SHELL} /xj/waitman/wdfs/missing --run makeinfo
-OBJEXT = o
-PACKAGE = wdfs
-PACKAGE_BUGREPORT = [email protected]
-PACKAGE_NAME = wdfs
-PACKAGE_STRING = wdfs 1.4.2
-PACKAGE_TARNAME = wdfs
-PACKAGE_VERSION = 1.4.2
-PATH_SEPARATOR = :
-PKG_CONFIG = /usr/local/bin/pkg-config
-SET_MAKE =
-SHELL = /bin/sh
-STRIP =
-VERSION = 1.4.2
-WDFS_CFLAGS = -I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include
-WDFS_LIBS = -L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl
-ac_ct_CC =
-am__fastdepCC_FALSE = #
-am__fastdepCC_TRUE =
-am__include = include
-am__leading_dot = .
-am__quote =
-am__tar = ${AMTAR} chof - "$$tardir"
-am__untar = ${AMTAR} xf -
-bindir = ${exec_prefix}/bin
-build_alias =
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host_alias =
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = /xj/waitman/wdfs/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = $(install_sh) -d
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-sysconfdir = ${prefix}/etc
-target_alias =
-wdfs_SOURCES = cache.c cache.h svn.c svn.h wdfs-main.c wdfs-main.h webdav.c webdav.h
-all: config.h
- $(MAKE) $(AM_MAKEFLAGS) all-am
-
-.SUFFIXES:
-.SUFFIXES: .c .o .obj
-$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
- @for dep in $?; do \
- case '$(am__configure_deps)' in \
- *$$dep*) \
- cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
- && exit 0; \
- exit 1;; \
- esac; \
- done; \
- echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \
- cd $(top_srcdir) && \
- $(AUTOMAKE) --gnu src/Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
- @case '$?' in \
- *config.status*) \
- cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
- *) \
- echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
- cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
- esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
- cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-$(top_srcdir)/configure: $(am__configure_deps)
- cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-$(ACLOCAL_M4): $(am__aclocal_m4_deps)
- cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-
-config.h: stamp-h1
- @if test ! -f $@; then \
- rm -f stamp-h1; \
- $(MAKE) stamp-h1; \
- else :; fi
-
-stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status
- @rm -f stamp-h1
- cd $(top_builddir) && $(SHELL) ./config.status src/config.h
-$(srcdir)/config.h.in: $(am__configure_deps)
- cd $(top_srcdir) && $(AUTOHEADER)
- rm -f stamp-h1
- touch $@
-
-distclean-hdr:
- -rm -f config.h stamp-h1
-install-binPROGRAMS: $(bin_PROGRAMS)
- @$(NORMAL_INSTALL)
- test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)"
- @list='$(bin_PROGRAMS)'; for p in $$list; do \
- p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \
- if test -f $$p \
- ; then \
- f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
- echo " $(INSTALL_PROGRAM_ENV) $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
- $(INSTALL_PROGRAM_ENV) $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
- else :; fi; \
- done
-
-uninstall-binPROGRAMS:
- @$(NORMAL_UNINSTALL)
- @list='$(bin_PROGRAMS)'; for p in $$list; do \
- f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \
- echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
- rm -f "$(DESTDIR)$(bindir)/$$f"; \
- done
-
-clean-binPROGRAMS:
- -test -z "$(bin_PROGRAMS)" || rm -f $(bin_PROGRAMS)
-wdfs$(EXEEXT): $(wdfs_OBJECTS) $(wdfs_DEPENDENCIES)
- @rm -f wdfs$(EXEEXT)
- $(LINK) $(wdfs_LDFLAGS) $(wdfs_OBJECTS) $(wdfs_LDADD) $(LIBS)
-
-mostlyclean-compile:
- -rm -f *.$(OBJEXT)
-
-distclean-compile:
- -rm -f *.tab.c
-
-include ./$(DEPDIR)/cache.Po
-include ./$(DEPDIR)/svn.Po
-include ./$(DEPDIR)/wdfs-main.Po
-include ./$(DEPDIR)/webdav.Po
-
-.c.o:
- if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
- then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
-# source='$<' object='$@' libtool=no \
-# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-# $(COMPILE) -c $<
-
-.c.obj:
- if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
- then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
-# source='$<' object='$@' libtool=no \
-# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
-# $(COMPILE) -c `$(CYGPATH_W) '$<'`
-uninstall-info-am:
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
- list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
- unique=`for i in $$list; do \
- if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
- done | \
- $(AWK) ' { files[$$0] = 1; } \
- END { for (i in files) print i; }'`; \
- mkid -fID $$unique
-tags: TAGS
-
-TAGS: $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \
- $(TAGS_FILES) $(LISP)
- tags=; \
- here=`pwd`; \
- list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \
- unique=`for i in $$list; do \
- if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
- done | \
- $(AWK) ' { files[$$0] = 1; } \
- END { for (i in files) print i; }'`; \
- if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
- test -n "$$unique" || unique=$$empty_fix; \
- $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
- $$tags $$unique; \
- fi
-ctags: CTAGS
-CTAGS: $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \
- $(TAGS_FILES) $(LISP)
- tags=; \
- here=`pwd`; \
- list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \
- unique=`for i in $$list; do \
- if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
- done | \
- $(AWK) ' { files[$$0] = 1; } \
- END { for (i in files) print i; }'`; \
- test -z "$(CTAGS_ARGS)$$tags$$unique" \
- || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
- $$tags $$unique
-
-GTAGS:
- here=`$(am__cd) $(top_builddir) && pwd` \
- && cd $(top_srcdir) \
- && gtags -i $(GTAGS_ARGS) $$here
-
-distclean-tags:
- -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
- @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
- topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
- list='$(DISTFILES)'; for file in $$list; do \
- case $$file in \
- $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
- $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
- esac; \
- if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
- dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
- if test "$$dir" != "$$file" && test "$$dir" != "."; then \
- dir="/$$dir"; \
- $(mkdir_p) "$(distdir)$$dir"; \
- else \
- dir=''; \
- fi; \
- if test -d $$d/$$file; then \
- if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
- cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
- fi; \
- cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
- else \
- test -f $(distdir)/$$file \
- || cp -p $$d/$$file $(distdir)/$$file \
- || exit 1; \
- fi; \
- done
-check-am: all-am
-check: check-am
-all-am: Makefile $(PROGRAMS) config.h
-installdirs:
- for dir in "$(DESTDIR)$(bindir)"; do \
- test -z "$$dir" || $(mkdir_p) "$$dir"; \
- done
-install: install-am
-install-exec: install-exec-am
-install-data: install-data-am
-uninstall: uninstall-am
-
-install-am: all-am
- @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-am
-install-strip:
- $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
- install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
- `test -z '$(STRIP)' || \
- echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
- -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-
-maintainer-clean-generic:
- @echo "This command is intended for maintainers to use"
- @echo "it deletes files that may require special tools to rebuild."
-clean: clean-am
-
-clean-am: clean-binPROGRAMS clean-generic mostlyclean-am
-
-distclean: distclean-am
- -rm -rf ./$(DEPDIR)
- -rm -f Makefile
-distclean-am: clean-am distclean-compile distclean-generic \
- distclean-hdr distclean-tags
-
-dvi: dvi-am
-
-dvi-am:
-
-html: html-am
-
-info: info-am
-
-info-am:
-
-install-data-am:
-
-install-exec-am: install-binPROGRAMS
-
-install-info: install-info-am
-
-install-man:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-am
- -rm -rf ./$(DEPDIR)
- -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-am
-
-mostlyclean-am: mostlyclean-compile mostlyclean-generic
-
-pdf: pdf-am
-
-pdf-am:
-
-ps: ps-am
-
-ps-am:
-
-uninstall-am: uninstall-binPROGRAMS uninstall-info-am
-
-.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \
- clean-generic ctags distclean distclean-compile \
- distclean-generic distclean-hdr distclean-tags distdir dvi \
- dvi-am html html-am info info-am install install-am \
- install-binPROGRAMS install-data install-data-am install-exec \
- install-exec-am install-info install-info-am install-man \
- install-strip installcheck installcheck-am installdirs \
- maintainer-clean maintainer-clean-generic mostlyclean \
- mostlyclean-compile mostlyclean-generic pdf pdf-am ps ps-am \
- tags uninstall uninstall-am uninstall-binPROGRAMS \
- uninstall-info-am
-
-
-# this flag is set via "#define FUSE_USE_VERSION XY" in wdfs-main.c
-# wdfs_CPPFLAGS = -DFUSE_USE_VERSION=
-
-# eof
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
|
codyps/wdfs
|
960a7a1a5a8e8603e5227384c3260d645fad85b0
|
gitignore
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..efd0e29
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+*.log
+.deps
+src/.deps/
+Makefile
+*.status
+src/config.h
+src/stamp-h1
diff --git a/Makefile b/Makefile
deleted file mode 100644
index 7992ffd..0000000
--- a/Makefile
+++ /dev/null
@@ -1,562 +0,0 @@
-# Makefile.in generated by automake 1.9.6 from Makefile.am.
-# Makefile. Generated from Makefile.in by configure.
-
-# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005 Free Software Foundation, Inc.
-# This Makefile.in is free software; the Free Software Foundation
-# gives unlimited permission to copy and/or distribute it,
-# with or without modifications, as long as this notice is preserved.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
-# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-
-
-srcdir = .
-top_srcdir = .
-
-pkgdatadir = $(datadir)/wdfs
-pkglibdir = $(libdir)/wdfs
-pkgincludedir = $(includedir)/wdfs
-top_builddir = .
-am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-INSTALL = /usr/bin/install -c
-install_sh_DATA = $(install_sh) -c -m 644
-install_sh_PROGRAM = $(install_sh) -c
-install_sh_SCRIPT = $(install_sh) -c
-INSTALL_HEADER = $(INSTALL_DATA)
-transform = $(program_transform_name)
-NORMAL_INSTALL = :
-PRE_INSTALL = :
-POST_INSTALL = :
-NORMAL_UNINSTALL = :
-PRE_UNINSTALL = :
-POST_UNINSTALL = :
-subdir = .
-DIST_COMMON = README $(am__configure_deps) $(srcdir)/Makefile.am \
- $(srcdir)/Makefile.in $(top_srcdir)/configure AUTHORS COPYING \
- ChangeLog INSTALL NEWS TODO depcomp install-sh missing
-ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
-am__aclocal_m4_deps = $(top_srcdir)/configure.ac
-am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
- $(ACLOCAL_M4)
-am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \
- configure.lineno configure.status.lineno
-mkinstalldirs = $(install_sh) -d
-CONFIG_HEADER = $(top_builddir)/src/config.h
-CONFIG_CLEAN_FILES =
-SOURCES =
-DIST_SOURCES =
-RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
- html-recursive info-recursive install-data-recursive \
- install-exec-recursive install-info-recursive \
- install-recursive installcheck-recursive installdirs-recursive \
- pdf-recursive ps-recursive uninstall-info-recursive \
- uninstall-recursive
-ETAGS = etags
-CTAGS = ctags
-DIST_SUBDIRS = $(SUBDIRS)
-DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
-distdir = $(PACKAGE)-$(VERSION)
-top_distdir = $(distdir)
-am__remove_distdir = \
- { test ! -d $(distdir) \
- || { find $(distdir) -type d ! -perm -200 -exec chmod u+w {} ';' \
- && rm -fr $(distdir); }; }
-DIST_ARCHIVES = $(distdir).tar.gz
-GZIP_ENV = --best
-distuninstallcheck_listfiles = find . -type f -print
-distcleancheck_listfiles = find . -type f -print
-ACLOCAL = ${SHELL} /xj/waitman/wdfs/missing --run aclocal-1.9
-AMDEP_FALSE = #
-AMDEP_TRUE =
-AMTAR = ${SHELL} /xj/waitman/wdfs/missing --run tar
-AUTOCONF = ${SHELL} /xj/waitman/wdfs/missing --run autoconf
-AUTOHEADER = ${SHELL} /xj/waitman/wdfs/missing --run autoheader
-AUTOMAKE = ${SHELL} /xj/waitman/wdfs/missing --run automake-1.9
-AWK = nawk
-CC = cc
-CCDEPMODE = depmode=gcc3
-CFLAGS = -g -O2 -I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include -Wall -D_GNU_SOURCE -D_REENTRANT
-CPP = cc -E
-CPPFLAGS =
-CYGPATH_W = echo
-DEFS = -DHAVE_CONFIG_H
-DEPDIR = .deps
-ECHO_C =
-ECHO_N = -n
-ECHO_T =
-EGREP = /usr/bin/grep -E
-EXEEXT =
-GREP = /usr/bin/grep
-INSTALL_DATA = ${INSTALL} -m 644
-INSTALL_PROGRAM = ${INSTALL}
-INSTALL_SCRIPT = ${INSTALL}
-INSTALL_STRIP_PROGRAM = ${SHELL} $(install_sh) -c -s
-LDFLAGS =
-LIBOBJS =
-LIBS = -L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl
-LTLIBOBJS =
-MAKEINFO = ${SHELL} /xj/waitman/wdfs/missing --run makeinfo
-OBJEXT = o
-PACKAGE = wdfs
-PACKAGE_BUGREPORT = [email protected]
-PACKAGE_NAME = wdfs
-PACKAGE_STRING = wdfs 1.4.2
-PACKAGE_TARNAME = wdfs
-PACKAGE_VERSION = 1.4.2
-PATH_SEPARATOR = :
-PKG_CONFIG = /usr/local/bin/pkg-config
-SET_MAKE =
-SHELL = /bin/sh
-STRIP =
-VERSION = 1.4.2
-WDFS_CFLAGS = -I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include
-WDFS_LIBS = -L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl
-ac_ct_CC =
-am__fastdepCC_FALSE = #
-am__fastdepCC_TRUE =
-am__include = include
-am__leading_dot = .
-am__quote =
-am__tar = ${AMTAR} chof - "$$tardir"
-am__untar = ${AMTAR} xf -
-bindir = ${exec_prefix}/bin
-build_alias =
-datadir = ${datarootdir}
-datarootdir = ${prefix}/share
-docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
-dvidir = ${docdir}
-exec_prefix = ${prefix}
-host_alias =
-htmldir = ${docdir}
-includedir = ${prefix}/include
-infodir = ${datarootdir}/info
-install_sh = /xj/waitman/wdfs/install-sh
-libdir = ${exec_prefix}/lib
-libexecdir = ${exec_prefix}/libexec
-localedir = ${datarootdir}/locale
-localstatedir = ${prefix}/var
-mandir = ${datarootdir}/man
-mkdir_p = $(install_sh) -d
-oldincludedir = /usr/include
-pdfdir = ${docdir}
-prefix = /usr/local
-program_transform_name = s,x,x,
-psdir = ${docdir}
-sbindir = ${exec_prefix}/sbin
-sharedstatedir = ${prefix}/com
-sysconfdir = ${prefix}/etc
-target_alias =
-SUBDIRS = src
-all: all-recursive
-
-.SUFFIXES:
-am--refresh:
- @:
-$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
- @for dep in $?; do \
- case '$(am__configure_deps)' in \
- *$$dep*) \
- echo ' cd $(srcdir) && $(AUTOMAKE) --gnu '; \
- cd $(srcdir) && $(AUTOMAKE) --gnu \
- && exit 0; \
- exit 1;; \
- esac; \
- done; \
- echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu Makefile'; \
- cd $(top_srcdir) && \
- $(AUTOMAKE) --gnu Makefile
-.PRECIOUS: Makefile
-Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
- @case '$?' in \
- *config.status*) \
- echo ' $(SHELL) ./config.status'; \
- $(SHELL) ./config.status;; \
- *) \
- echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \
- cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \
- esac;
-
-$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
- $(SHELL) ./config.status --recheck
-
-$(top_srcdir)/configure: $(am__configure_deps)
- cd $(srcdir) && $(AUTOCONF)
-$(ACLOCAL_M4): $(am__aclocal_m4_deps)
- cd $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS)
-uninstall-info-am:
-
-# This directory's subdirectories are mostly independent; you can cd
-# into them and run `make' without going through this Makefile.
-# To change the values of `make' variables: instead of editing Makefiles,
-# (1) if the variable is set in `config.status', edit `config.status'
-# (which will cause the Makefiles to be regenerated when you run `make');
-# (2) otherwise, pass the desired values on the `make' command line.
-$(RECURSIVE_TARGETS):
- @failcom='exit 1'; \
- for f in x $$MAKEFLAGS; do \
- case $$f in \
- *=* | --[!k]*);; \
- *k*) failcom='fail=yes';; \
- esac; \
- done; \
- dot_seen=no; \
- target=`echo $@ | sed s/-recursive//`; \
- list='$(SUBDIRS)'; for subdir in $$list; do \
- echo "Making $$target in $$subdir"; \
- if test "$$subdir" = "."; then \
- dot_seen=yes; \
- local_target="$$target-am"; \
- else \
- local_target="$$target"; \
- fi; \
- (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
- || eval $$failcom; \
- done; \
- if test "$$dot_seen" = "no"; then \
- $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
- fi; test -z "$$fail"
-
-mostlyclean-recursive clean-recursive distclean-recursive \
-maintainer-clean-recursive:
- @failcom='exit 1'; \
- for f in x $$MAKEFLAGS; do \
- case $$f in \
- *=* | --[!k]*);; \
- *k*) failcom='fail=yes';; \
- esac; \
- done; \
- dot_seen=no; \
- case "$@" in \
- distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
- *) list='$(SUBDIRS)' ;; \
- esac; \
- rev=''; for subdir in $$list; do \
- if test "$$subdir" = "."; then :; else \
- rev="$$subdir $$rev"; \
- fi; \
- done; \
- rev="$$rev ."; \
- target=`echo $@ | sed s/-recursive//`; \
- for subdir in $$rev; do \
- echo "Making $$target in $$subdir"; \
- if test "$$subdir" = "."; then \
- local_target="$$target-am"; \
- else \
- local_target="$$target"; \
- fi; \
- (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
- || eval $$failcom; \
- done && test -z "$$fail"
-tags-recursive:
- list='$(SUBDIRS)'; for subdir in $$list; do \
- test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
- done
-ctags-recursive:
- list='$(SUBDIRS)'; for subdir in $$list; do \
- test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
- done
-
-ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
- list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
- unique=`for i in $$list; do \
- if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
- done | \
- $(AWK) ' { files[$$0] = 1; } \
- END { for (i in files) print i; }'`; \
- mkid -fID $$unique
-tags: TAGS
-
-TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
- $(TAGS_FILES) $(LISP)
- tags=; \
- here=`pwd`; \
- if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
- include_option=--etags-include; \
- empty_fix=.; \
- else \
- include_option=--include; \
- empty_fix=; \
- fi; \
- list='$(SUBDIRS)'; for subdir in $$list; do \
- if test "$$subdir" = .; then :; else \
- test ! -f $$subdir/TAGS || \
- tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \
- fi; \
- done; \
- list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
- unique=`for i in $$list; do \
- if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
- done | \
- $(AWK) ' { files[$$0] = 1; } \
- END { for (i in files) print i; }'`; \
- if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
- test -n "$$unique" || unique=$$empty_fix; \
- $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
- $$tags $$unique; \
- fi
-ctags: CTAGS
-CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
- $(TAGS_FILES) $(LISP)
- tags=; \
- here=`pwd`; \
- list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
- unique=`for i in $$list; do \
- if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
- done | \
- $(AWK) ' { files[$$0] = 1; } \
- END { for (i in files) print i; }'`; \
- test -z "$(CTAGS_ARGS)$$tags$$unique" \
- || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
- $$tags $$unique
-
-GTAGS:
- here=`$(am__cd) $(top_builddir) && pwd` \
- && cd $(top_srcdir) \
- && gtags -i $(GTAGS_ARGS) $$here
-
-distclean-tags:
- -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-
-distdir: $(DISTFILES)
- $(am__remove_distdir)
- mkdir $(distdir)
- @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
- topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
- list='$(DISTFILES)'; for file in $$list; do \
- case $$file in \
- $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
- $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
- esac; \
- if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
- dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
- if test "$$dir" != "$$file" && test "$$dir" != "."; then \
- dir="/$$dir"; \
- $(mkdir_p) "$(distdir)$$dir"; \
- else \
- dir=''; \
- fi; \
- if test -d $$d/$$file; then \
- if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
- cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
- fi; \
- cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
- else \
- test -f $(distdir)/$$file \
- || cp -p $$d/$$file $(distdir)/$$file \
- || exit 1; \
- fi; \
- done
- list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
- if test "$$subdir" = .; then :; else \
- test -d "$(distdir)/$$subdir" \
- || $(mkdir_p) "$(distdir)/$$subdir" \
- || exit 1; \
- distdir=`$(am__cd) $(distdir) && pwd`; \
- top_distdir=`$(am__cd) $(top_distdir) && pwd`; \
- (cd $$subdir && \
- $(MAKE) $(AM_MAKEFLAGS) \
- top_distdir="$$top_distdir" \
- distdir="$$distdir/$$subdir" \
- distdir) \
- || exit 1; \
- fi; \
- done
- -find $(distdir) -type d ! -perm -777 -exec chmod a+rwx {} \; -o \
- ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \
- ! -type d ! -perm -400 -exec chmod a+r {} \; -o \
- ! -type d ! -perm -444 -exec $(SHELL) $(install_sh) -c -m a+r {} {} \; \
- || chmod -R a+r $(distdir)
-dist-gzip: distdir
- tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
- $(am__remove_distdir)
-
-dist-bzip2: distdir
- tardir=$(distdir) && $(am__tar) | bzip2 -9 -c >$(distdir).tar.bz2
- $(am__remove_distdir)
-
-dist-tarZ: distdir
- tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z
- $(am__remove_distdir)
-
-dist-shar: distdir
- shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz
- $(am__remove_distdir)
-
-dist-zip: distdir
- -rm -f $(distdir).zip
- zip -rq $(distdir).zip $(distdir)
- $(am__remove_distdir)
-
-dist dist-all: distdir
- tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
- $(am__remove_distdir)
-
-# This target untars the dist file and tries a VPATH configuration. Then
-# it guarantees that the distribution is self-contained by making another
-# tarfile.
-distcheck: dist
- case '$(DIST_ARCHIVES)' in \
- *.tar.gz*) \
- GZIP=$(GZIP_ENV) gunzip -c $(distdir).tar.gz | $(am__untar) ;;\
- *.tar.bz2*) \
- bunzip2 -c $(distdir).tar.bz2 | $(am__untar) ;;\
- *.tar.Z*) \
- uncompress -c $(distdir).tar.Z | $(am__untar) ;;\
- *.shar.gz*) \
- GZIP=$(GZIP_ENV) gunzip -c $(distdir).shar.gz | unshar ;;\
- *.zip*) \
- unzip $(distdir).zip ;;\
- esac
- chmod -R a-w $(distdir); chmod a+w $(distdir)
- mkdir $(distdir)/_build
- mkdir $(distdir)/_inst
- chmod a-w $(distdir)
- dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \
- && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \
- && cd $(distdir)/_build \
- && ../configure --srcdir=.. --prefix="$$dc_install_base" \
- $(DISTCHECK_CONFIGURE_FLAGS) \
- && $(MAKE) $(AM_MAKEFLAGS) \
- && $(MAKE) $(AM_MAKEFLAGS) dvi \
- && $(MAKE) $(AM_MAKEFLAGS) check \
- && $(MAKE) $(AM_MAKEFLAGS) install \
- && $(MAKE) $(AM_MAKEFLAGS) installcheck \
- && $(MAKE) $(AM_MAKEFLAGS) uninstall \
- && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \
- distuninstallcheck \
- && chmod -R a-w "$$dc_install_base" \
- && ({ \
- (cd ../.. && umask 077 && mkdir "$$dc_destdir") \
- && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \
- && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \
- && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \
- distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \
- } || { rm -rf "$$dc_destdir"; exit 1; }) \
- && rm -rf "$$dc_destdir" \
- && $(MAKE) $(AM_MAKEFLAGS) dist \
- && rm -rf $(DIST_ARCHIVES) \
- && $(MAKE) $(AM_MAKEFLAGS) distcleancheck
- $(am__remove_distdir)
- @(echo "$(distdir) archives ready for distribution: "; \
- list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \
- sed -e '1{h;s/./=/g;p;x;}' -e '$${p;x;}'
-distuninstallcheck:
- @cd $(distuninstallcheck_dir) \
- && test `$(distuninstallcheck_listfiles) | wc -l` -le 1 \
- || { echo "ERROR: files left after uninstall:" ; \
- if test -n "$(DESTDIR)"; then \
- echo " (check DESTDIR support)"; \
- fi ; \
- $(distuninstallcheck_listfiles) ; \
- exit 1; } >&2
-distcleancheck: distclean
- @if test '$(srcdir)' = . ; then \
- echo "ERROR: distcleancheck can only run from a VPATH build" ; \
- exit 1 ; \
- fi
- @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \
- || { echo "ERROR: files left in build directory after distclean:" ; \
- $(distcleancheck_listfiles) ; \
- exit 1; } >&2
-check-am: all-am
-check: check-recursive
-all-am: Makefile
-installdirs: installdirs-recursive
-installdirs-am:
-install: install-recursive
-install-exec: install-exec-recursive
-install-data: install-data-recursive
-uninstall: uninstall-recursive
-
-install-am: all-am
- @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
-
-installcheck: installcheck-recursive
-install-strip:
- $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
- install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
- `test -z '$(STRIP)' || \
- echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
-mostlyclean-generic:
-
-clean-generic:
-
-distclean-generic:
- -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-
-maintainer-clean-generic:
- @echo "This command is intended for maintainers to use"
- @echo "it deletes files that may require special tools to rebuild."
-clean: clean-recursive
-
-clean-am: clean-generic mostlyclean-am
-
-distclean: distclean-recursive
- -rm -f $(am__CONFIG_DISTCLEAN_FILES)
- -rm -f Makefile
-distclean-am: clean-am distclean-generic distclean-tags
-
-dvi: dvi-recursive
-
-dvi-am:
-
-html: html-recursive
-
-info: info-recursive
-
-info-am:
-
-install-data-am:
-
-install-exec-am:
-
-install-info: install-info-recursive
-
-install-man:
-
-installcheck-am:
-
-maintainer-clean: maintainer-clean-recursive
- -rm -f $(am__CONFIG_DISTCLEAN_FILES)
- -rm -rf $(top_srcdir)/autom4te.cache
- -rm -f Makefile
-maintainer-clean-am: distclean-am maintainer-clean-generic
-
-mostlyclean: mostlyclean-recursive
-
-mostlyclean-am: mostlyclean-generic
-
-pdf: pdf-recursive
-
-pdf-am:
-
-ps: ps-recursive
-
-ps-am:
-
-uninstall-am: uninstall-info-am
-
-uninstall-info: uninstall-info-recursive
-
-.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am am--refresh check \
- check-am clean clean-generic clean-recursive ctags \
- ctags-recursive dist dist-all dist-bzip2 dist-gzip dist-shar \
- dist-tarZ dist-zip distcheck distclean distclean-generic \
- distclean-recursive distclean-tags distcleancheck distdir \
- distuninstallcheck dvi dvi-am html html-am info info-am \
- install install-am install-data install-data-am install-exec \
- install-exec-am install-info install-info-am install-man \
- install-strip installcheck installcheck-am installdirs \
- installdirs-am maintainer-clean maintainer-clean-generic \
- maintainer-clean-recursive mostlyclean mostlyclean-generic \
- mostlyclean-recursive pdf pdf-am ps ps-am tags tags-recursive \
- uninstall uninstall-am uninstall-info-am
-
-
-# eof
-# Tell versions [3.59,3.63) of GNU make to not export all variables.
-# Otherwise a system limit (for SysV at least) may be exceeded.
-.NOEXPORT:
diff --git a/config.log b/config.log
deleted file mode 100644
index 886eae9..0000000
--- a/config.log
+++ /dev/null
@@ -1,440 +0,0 @@
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-
-It was created by wdfs configure 1.4.2, which was
-generated by GNU Autoconf 2.61. Invocation command line was
-
- $ ./configure
-
-## --------- ##
-## Platform. ##
-## --------- ##
-
-hostname = afia.waitman.net
-uname -m = amd64
-uname -r = 11.0-CURRENT
-uname -s = FreeBSD
-uname -v = FreeBSD 11.0-CURRENT #0 r290480M: Fri Nov 6 20:43:01 PST 2015 [email protected]:/usr/obj/usr/src/sys/AFIA
-
-/usr/bin/uname -p = amd64
-/bin/uname -X = unknown
-
-/bin/arch = unknown
-/usr/bin/arch -k = unknown
-/usr/convex/getsysinfo = unknown
-/usr/bin/hostinfo = unknown
-/bin/machine = unknown
-/usr/bin/oslevel = unknown
-/bin/universe = unknown
-
-PATH: /sbin
-PATH: /bin
-PATH: /usr/sbin
-PATH: /usr/bin
-PATH: /usr/local/sbin
-PATH: /usr/local/bin
-PATH: /root/bin
-
-
-## ----------- ##
-## Core tests. ##
-## ----------- ##
-
-configure:1779: checking for a BSD-compatible install
-configure:1835: result: /usr/bin/install -c
-configure:1846: checking whether build environment is sane
-configure:1889: result: yes
-configure:1954: checking for gawk
-configure:1984: result: no
-configure:1954: checking for mawk
-configure:1984: result: no
-configure:1954: checking for nawk
-configure:1970: found /usr/bin/nawk
-configure:1981: result: nawk
-configure:1992: checking whether make sets $(MAKE)
-configure:2013: result: yes
-configure:2212: checking for style of include used by make
-configure:2240: result: GNU
-configure:2313: checking for gcc
-configure:2343: result: no
-configure:2410: checking for cc
-configure:2431: found /usr/bin/cc
-configure:2454: result: cc
-configure:2578: checking for C compiler version
-configure:2585: cc --version >&5
-FreeBSD clang version 3.7.0 (tags/RELEASE_370/final 246257) 20150906
-Target: x86_64-unknown-freebsd11.0
-Thread model: posix
-configure:2588: $? = 0
-configure:2595: cc -v >&5
-FreeBSD clang version 3.7.0 (tags/RELEASE_370/final 246257) 20150906
-Target: x86_64-unknown-freebsd11.0
-Thread model: posix
-configure:2598: $? = 0
-configure:2605: cc -V >&5
-cc: error: argument to '-V' is missing (expected 1 value)
-cc: error: no input files
-configure:2608: $? = 1
-configure:2631: checking for C compiler default output file name
-configure:2658: cc conftest.c >&5
-configure:2661: $? = 0
-configure:2699: result: a.out
-configure:2716: checking whether the C compiler works
-configure:2726: ./a.out
-configure:2729: $? = 0
-configure:2746: result: yes
-configure:2753: checking whether we are cross compiling
-configure:2755: result: no
-configure:2758: checking for suffix of executables
-configure:2765: cc -o conftest conftest.c >&5
-configure:2768: $? = 0
-configure:2792: result:
-configure:2798: checking for suffix of object files
-configure:2824: cc -c conftest.c >&5
-configure:2827: $? = 0
-configure:2850: result: o
-configure:2854: checking whether we are using the GNU C compiler
-configure:2883: cc -c conftest.c >&5
-configure:2889: $? = 0
-configure:2906: result: yes
-configure:2911: checking whether cc accepts -g
-configure:2941: cc -c -g conftest.c >&5
-configure:2947: $? = 0
-configure:3046: result: yes
-configure:3063: checking for cc option to accept ISO C89
-configure:3137: cc -c -g -O2 conftest.c >&5
-configure:3143: $? = 0
-configure:3166: result: none needed
-configure:3186: checking dependency style of cc
-configure:3276: result: gcc3
-configure:3299: checking how to run the C preprocessor
-configure:3339: cc -E conftest.c
-configure:3345: $? = 0
-configure:3376: cc -E conftest.c
-conftest.c:10:10: fatal error: 'ac_nonexistent.h' file not found
-#include <ac_nonexistent.h>
- ^
-1 error generated.
-configure:3382: $? = 1
-configure: failed program was:
-| /* confdefs.h. */
-| #define PACKAGE_NAME "wdfs"
-| #define PACKAGE_TARNAME "wdfs"
-| #define PACKAGE_VERSION "1.4.2"
-| #define PACKAGE_STRING "wdfs 1.4.2"
-| #define PACKAGE_BUGREPORT "[email protected]"
-| #define PACKAGE "wdfs"
-| #define VERSION "1.4.2"
-| /* end confdefs.h. */
-| #include <ac_nonexistent.h>
-configure:3415: result: cc -E
-configure:3444: cc -E conftest.c
-configure:3450: $? = 0
-configure:3481: cc -E conftest.c
-conftest.c:10:10: fatal error: 'ac_nonexistent.h' file not found
-#include <ac_nonexistent.h>
- ^
-1 error generated.
-configure:3487: $? = 1
-configure: failed program was:
-| /* confdefs.h. */
-| #define PACKAGE_NAME "wdfs"
-| #define PACKAGE_TARNAME "wdfs"
-| #define PACKAGE_VERSION "1.4.2"
-| #define PACKAGE_STRING "wdfs 1.4.2"
-| #define PACKAGE_BUGREPORT "[email protected]"
-| #define PACKAGE "wdfs"
-| #define VERSION "1.4.2"
-| /* end confdefs.h. */
-| #include <ac_nonexistent.h>
-configure:3525: checking for grep that handles long lines and -e
-configure:3599: result: /usr/bin/grep
-configure:3604: checking for egrep
-configure:3682: result: /usr/bin/grep -E
-configure:3687: checking for ANSI C header files
-configure:3717: cc -c -g -O2 conftest.c >&5
-configure:3723: $? = 0
-configure:3822: cc -o conftest -g -O2 conftest.c >&5
-configure:3825: $? = 0
-configure:3831: ./conftest
-configure:3834: $? = 0
-configure:3851: result: yes
-configure:3875: checking for sys/types.h
-configure:3896: cc -c -g -O2 conftest.c >&5
-configure:3902: $? = 0
-configure:3918: result: yes
-configure:3875: checking for sys/stat.h
-configure:3896: cc -c -g -O2 conftest.c >&5
-configure:3902: $? = 0
-configure:3918: result: yes
-configure:3875: checking for stdlib.h
-configure:3896: cc -c -g -O2 conftest.c >&5
-configure:3902: $? = 0
-configure:3918: result: yes
-configure:3875: checking for string.h
-configure:3896: cc -c -g -O2 conftest.c >&5
-configure:3902: $? = 0
-configure:3918: result: yes
-configure:3875: checking for memory.h
-configure:3896: cc -c -g -O2 conftest.c >&5
-configure:3902: $? = 0
-configure:3918: result: yes
-configure:3875: checking for strings.h
-configure:3896: cc -c -g -O2 conftest.c >&5
-configure:3902: $? = 0
-configure:3918: result: yes
-configure:3875: checking for inttypes.h
-configure:3896: cc -c -g -O2 conftest.c >&5
-configure:3902: $? = 0
-configure:3918: result: yes
-configure:3875: checking for stdint.h
-configure:3896: cc -c -g -O2 conftest.c >&5
-configure:3902: $? = 0
-configure:3918: result: yes
-configure:3875: checking for unistd.h
-configure:3896: cc -c -g -O2 conftest.c >&5
-configure:3902: $? = 0
-configure:3918: result: yes
-configure:3945: checking pthread.h usability
-configure:3962: cc -c -g -O2 conftest.c >&5
-configure:3968: $? = 0
-configure:3982: result: yes
-configure:3986: checking pthread.h presence
-configure:4001: cc -E conftest.c
-configure:4007: $? = 0
-configure:4021: result: yes
-configure:4054: checking for pthread.h
-configure:4062: result: yes
-configure:4080: checking for strndup
-configure:4136: cc -o conftest -g -O2 conftest.c >&5
-conftest.c:44:6: warning: incompatible redeclaration of library function 'strndup' [-Wincompatible-library-redeclaration]
-char strndup ();
- ^
-conftest.c:44:6: note: 'strndup' is a builtin with type 'char *(const char *, unsigned long)'
-1 warning generated.
-configure:4142: $? = 0
-configure:4160: result: yes
-configure:4484: checking for C compiler version
-configure:4491: cc --version >&5
-FreeBSD clang version 3.7.0 (tags/RELEASE_370/final 246257) 20150906
-Target: x86_64-unknown-freebsd11.0
-Thread model: posix
-configure:4494: $? = 0
-configure:4501: cc -v >&5
-FreeBSD clang version 3.7.0 (tags/RELEASE_370/final 246257) 20150906
-Target: x86_64-unknown-freebsd11.0
-Thread model: posix
-configure:4504: $? = 0
-configure:4511: cc -V >&5
-cc: error: argument to '-V' is missing (expected 1 value)
-cc: error: no input files
-configure:4514: $? = 1
-configure:4517: checking whether we are using the GNU C compiler
-configure:4569: result: yes
-configure:4574: checking whether cc accepts -g
-configure:4709: result: yes
-configure:4726: checking for cc option to accept ISO C89
-configure:4829: result: none needed
-configure:4849: checking dependency style of cc
-configure:4939: result: gcc3
-configure:5006: checking for pkg-config
-configure:5024: found /usr/local/bin/pkg-config
-configure:5036: result: /usr/local/bin/pkg-config
-configure:5065: checking pkg-config is at least version 0.9.0
-configure:5068: result: yes
-configure:5079: checking for WDFS
-configure:5087: $PKG_CONFIG --exists --print-errors "fuse >= 2.5.0 neon >= 0.24.7 glib-2.0"
-configure:5090: $? = 0
-configure:5105: $PKG_CONFIG --exists --print-errors "fuse >= 2.5.0 neon >= 0.24.7 glib-2.0"
-configure:5108: $? = 0
-configure:5184: result: yes
-configure:5315: creating ./config.status
-
-## ---------------------- ##
-## Running config.status. ##
-## ---------------------- ##
-
-This file was extended by wdfs config.status 1.4.2, which was
-generated by GNU Autoconf 2.61. Invocation command line was
-
- CONFIG_FILES =
- CONFIG_HEADERS =
- CONFIG_LINKS =
- CONFIG_COMMANDS =
- $ ./config.status
-
-on afia.waitman.net
-
-config.status:637: creating Makefile
-config.status:637: creating src/Makefile
-config.status:637: creating src/config.h
-config.status:905: executing depfiles commands
-
-## ---------------- ##
-## Cache variables. ##
-## ---------------- ##
-
-ac_cv_c_compiler_gnu=yes
-ac_cv_env_CC_set=''
-ac_cv_env_CC_value=''
-ac_cv_env_CFLAGS_set=''
-ac_cv_env_CFLAGS_value=''
-ac_cv_env_CPPFLAGS_set=''
-ac_cv_env_CPPFLAGS_value=''
-ac_cv_env_CPP_set=''
-ac_cv_env_CPP_value=''
-ac_cv_env_LDFLAGS_set=''
-ac_cv_env_LDFLAGS_value=''
-ac_cv_env_LIBS_set=''
-ac_cv_env_LIBS_value=''
-ac_cv_env_PKG_CONFIG_set=''
-ac_cv_env_PKG_CONFIG_value=''
-ac_cv_env_WDFS_CFLAGS_set=''
-ac_cv_env_WDFS_CFLAGS_value=''
-ac_cv_env_WDFS_LIBS_set=''
-ac_cv_env_WDFS_LIBS_value=''
-ac_cv_env_build_alias_set=''
-ac_cv_env_build_alias_value=''
-ac_cv_env_host_alias_set=''
-ac_cv_env_host_alias_value=''
-ac_cv_env_target_alias_set=''
-ac_cv_env_target_alias_value=''
-ac_cv_func_strndup=yes
-ac_cv_header_inttypes_h=yes
-ac_cv_header_memory_h=yes
-ac_cv_header_pthread_h=yes
-ac_cv_header_stdc=yes
-ac_cv_header_stdint_h=yes
-ac_cv_header_stdlib_h=yes
-ac_cv_header_string_h=yes
-ac_cv_header_strings_h=yes
-ac_cv_header_sys_stat_h=yes
-ac_cv_header_sys_types_h=yes
-ac_cv_header_unistd_h=yes
-ac_cv_objext=o
-ac_cv_path_EGREP='/usr/bin/grep -E'
-ac_cv_path_GREP=/usr/bin/grep
-ac_cv_path_ac_pt_PKG_CONFIG=/usr/local/bin/pkg-config
-ac_cv_path_install='/usr/bin/install -c'
-ac_cv_prog_AWK=nawk
-ac_cv_prog_CC=cc
-ac_cv_prog_CPP='cc -E'
-ac_cv_prog_cc_c89=''
-ac_cv_prog_cc_g=yes
-ac_cv_prog_make_make_set=yes
-am_cv_CC_dependencies_compiler_type=gcc3
-pkg_cv_WDFS_CFLAGS='-I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include '
-pkg_cv_WDFS_LIBS='-L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl '
-
-## ----------------- ##
-## Output variables. ##
-## ----------------- ##
-
-ACLOCAL='${SHELL} /xj/waitman/wdfs/missing --run aclocal-1.9'
-AMDEPBACKSLASH='\'
-AMDEP_FALSE='#'
-AMDEP_TRUE=''
-AMTAR='${SHELL} /xj/waitman/wdfs/missing --run tar'
-AUTOCONF='${SHELL} /xj/waitman/wdfs/missing --run autoconf'
-AUTOHEADER='${SHELL} /xj/waitman/wdfs/missing --run autoheader'
-AUTOMAKE='${SHELL} /xj/waitman/wdfs/missing --run automake-1.9'
-AWK='nawk'
-CC='cc'
-CCDEPMODE='depmode=gcc3'
-CFLAGS='-g -O2 -I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include -Wall -D_GNU_SOURCE -D_REENTRANT'
-CPP='cc -E'
-CPPFLAGS=''
-CYGPATH_W='echo'
-DEFS='-DHAVE_CONFIG_H'
-DEPDIR='.deps'
-ECHO_C=''
-ECHO_N='-n'
-ECHO_T=''
-EGREP='/usr/bin/grep -E'
-EXEEXT=''
-GREP='/usr/bin/grep'
-INSTALL_DATA='${INSTALL} -m 644'
-INSTALL_PROGRAM='${INSTALL}'
-INSTALL_SCRIPT='${INSTALL}'
-INSTALL_STRIP_PROGRAM='${SHELL} $(install_sh) -c -s'
-LDFLAGS=''
-LIBOBJS=''
-LIBS='-L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl '
-LTLIBOBJS=''
-MAKEINFO='${SHELL} /xj/waitman/wdfs/missing --run makeinfo'
-OBJEXT='o'
-PACKAGE='wdfs'
-PACKAGE_BUGREPORT='[email protected]'
-PACKAGE_NAME='wdfs'
-PACKAGE_STRING='wdfs 1.4.2'
-PACKAGE_TARNAME='wdfs'
-PACKAGE_VERSION='1.4.2'
-PATH_SEPARATOR=':'
-PKG_CONFIG='/usr/local/bin/pkg-config'
-SET_MAKE=''
-SHELL='/bin/sh'
-STRIP=''
-VERSION='1.4.2'
-WDFS_CFLAGS='-I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include '
-WDFS_LIBS='-L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl '
-ac_ct_CC=''
-am__fastdepCC_FALSE='#'
-am__fastdepCC_TRUE=''
-am__include='include'
-am__leading_dot='.'
-am__quote=''
-am__tar='${AMTAR} chof - "$$tardir"'
-am__untar='${AMTAR} xf -'
-bindir='${exec_prefix}/bin'
-build_alias=''
-datadir='${datarootdir}'
-datarootdir='${prefix}/share'
-docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
-dvidir='${docdir}'
-exec_prefix='${prefix}'
-host_alias=''
-htmldir='${docdir}'
-includedir='${prefix}/include'
-infodir='${datarootdir}/info'
-install_sh='/xj/waitman/wdfs/install-sh'
-libdir='${exec_prefix}/lib'
-libexecdir='${exec_prefix}/libexec'
-localedir='${datarootdir}/locale'
-localstatedir='${prefix}/var'
-mandir='${datarootdir}/man'
-mkdir_p='$(install_sh) -d'
-oldincludedir='/usr/include'
-pdfdir='${docdir}'
-prefix='/usr/local'
-program_transform_name='s,x,x,'
-psdir='${docdir}'
-sbindir='${exec_prefix}/sbin'
-sharedstatedir='${prefix}/com'
-sysconfdir='${prefix}/etc'
-target_alias=''
-
-## ----------- ##
-## confdefs.h. ##
-## ----------- ##
-
-#define PACKAGE_NAME "wdfs"
-#define PACKAGE_TARNAME "wdfs"
-#define PACKAGE_VERSION "1.4.2"
-#define PACKAGE_STRING "wdfs 1.4.2"
-#define PACKAGE_BUGREPORT "[email protected]"
-#define PACKAGE "wdfs"
-#define VERSION "1.4.2"
-#define STDC_HEADERS 1
-#define HAVE_SYS_TYPES_H 1
-#define HAVE_SYS_STAT_H 1
-#define HAVE_STDLIB_H 1
-#define HAVE_STRING_H 1
-#define HAVE_MEMORY_H 1
-#define HAVE_STRINGS_H 1
-#define HAVE_INTTYPES_H 1
-#define HAVE_STDINT_H 1
-#define HAVE_UNISTD_H 1
-#define HAVE_PTHREAD_H 1
-#define HAVE_STRNDUP 1
-
-configure: exit 0
diff --git a/config.status b/config.status
deleted file mode 100755
index 4174aae..0000000
--- a/config.status
+++ /dev/null
@@ -1,1040 +0,0 @@
-#! /bin/sh
-# Generated by configure.
-# Run this file to recreate the current configuration.
-# Compiler output produced by configure, useful for debugging
-# configure, is in config.log if it exists.
-
-debug=false
-ac_cs_recheck=false
-ac_cs_silent=false
-SHELL=${CONFIG_SHELL-/bin/sh}
-## --------------------- ##
-## M4sh Initialization. ##
-## --------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
- emulate sh
- NULLCMD=:
- # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
- # is contrary to our usage. Disable this feature.
- alias -g '${1+"$@"}'='"$@"'
- setopt NO_GLOB_SUBST
-else
- case `(set -o) 2>/dev/null` in
- *posix*) set -o posix ;;
-esac
-
-fi
-
-
-
-
-# PATH needs CR
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
- echo "#! /bin/sh" >conf$$.sh
- echo "exit 0" >>conf$$.sh
- chmod +x conf$$.sh
- if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
- PATH_SEPARATOR=';'
- else
- PATH_SEPARATOR=:
- fi
- rm -f conf$$.sh
-fi
-
-# Support unset when possible.
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
- as_unset=unset
-else
- as_unset=false
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order. Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-as_nl='
-'
-IFS=" "" $as_nl"
-
-# Find who we are. Look in the path if we contain no directory separator.
-case $0 in
- *[\\/]* ) as_myself=$0 ;;
- *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-done
-IFS=$as_save_IFS
-
- ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
- as_myself=$0
-fi
-if test ! -f "$as_myself"; then
- echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
- { (exit 1); exit 1; }
-fi
-
-# Work around bugs in pre-3.0 UWIN ksh.
-for as_var in ENV MAIL MAILPATH
-do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-for as_var in \
- LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
- LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
- LC_TELEPHONE LC_TIME
-do
- if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
- eval $as_var=C; export $as_var
- else
- ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
- fi
-done
-
-# Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1 &&
- test "X`expr 00001 : '.*\(...\)'`" = X001; then
- as_expr=expr
-else
- as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
- as_basename=basename
-else
- as_basename=false
-fi
-
-
-# Name of the executable.
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
- X"$0" : 'X\(//\)$' \| \
- X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-echo X/"$0" |
- sed '/^.*\/\([^/][^/]*\)\/*$/{
- s//\1/
- q
- }
- /^X\/\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\/\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
-
-# CDPATH.
-$as_unset CDPATH
-
-
-
- as_lineno_1=$LINENO
- as_lineno_2=$LINENO
- test "x$as_lineno_1" != "x$as_lineno_2" &&
- test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
-
- # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
- # uniformly replaced by the line number. The first 'sed' inserts a
- # line-number line after each line using $LINENO; the second 'sed'
- # does the real work. The second script uses 'N' to pair each
- # line-number line with the line containing $LINENO, and appends
- # trailing '-' during substitution so that $LINENO is not a special
- # case at line end.
- # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
- # scripts with optimization help from Paolo Bonzini. Blame Lee
- # E. McMahon (1931-1989) for sed's syntax. :-)
- sed -n '
- p
- /[$]LINENO/=
- ' <$as_myself |
- sed '
- s/[$]LINENO.*/&-/
- t lineno
- b
- :lineno
- N
- :loop
- s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
- t loop
- s/-\n.*//
- ' >$as_me.lineno &&
- chmod +x "$as_me.lineno" ||
- { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
- { (exit 1); exit 1; }; }
-
- # Don't try to exec as it changes $[0], causing all sort of problems
- # (the dirname of $[0] is not the place where we might find the
- # original and so on. Autoconf is especially sensitive to this).
- . "./$as_me.lineno"
- # Exit status is that of the last command.
- exit
-}
-
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
- as_dirname=dirname
-else
- as_dirname=false
-fi
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in
--n*)
- case `echo 'x\c'` in
- *c*) ECHO_T=' ';; # ECHO_T is single tab character.
- *) ECHO_C='\c';;
- esac;;
-*)
- ECHO_N='-n';;
-esac
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
- test "X`expr 00001 : '.*\(...\)'`" = X001; then
- as_expr=expr
-else
- as_expr=false
-fi
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
- rm -f conf$$.dir/conf$$.file
-else
- rm -f conf$$.dir
- mkdir conf$$.dir
-fi
-echo >conf$$.file
-if ln -s conf$$.file conf$$ 2>/dev/null; then
- as_ln_s='ln -s'
- # ... but there are two gotchas:
- # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
- # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
- # In both cases, we have to default to `cp -p'.
- ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
- as_ln_s='cp -p'
-elif ln conf$$.file conf$$ 2>/dev/null; then
- as_ln_s=ln
-else
- as_ln_s='cp -p'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-if mkdir -p . 2>/dev/null; then
- as_mkdir_p=:
-else
- test -d ./-p && rmdir ./-p
- as_mkdir_p=false
-fi
-
-if test -x / >/dev/null 2>&1; then
- as_test_x='test -x'
-else
- if ls -dL / >/dev/null 2>&1; then
- as_ls_L_option=L
- else
- as_ls_L_option=
- fi
- as_test_x='
- eval sh -c '\''
- if test -d "$1"; then
- test -d "$1/.";
- else
- case $1 in
- -*)set "./$1";;
- esac;
- case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
- ???[sx]*):;;*)false;;esac;fi
- '\'' sh
- '
-fi
-as_executable_p=$as_test_x
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-exec 6>&1
-
-# Save the log message, to keep $[0] and so on meaningful, and to
-# report actual input values of CONFIG_FILES etc. instead of their
-# values after options handling.
-ac_log="
-This file was extended by wdfs $as_me 1.4.2, which was
-generated by GNU Autoconf 2.61. Invocation command line was
-
- CONFIG_FILES = $CONFIG_FILES
- CONFIG_HEADERS = $CONFIG_HEADERS
- CONFIG_LINKS = $CONFIG_LINKS
- CONFIG_COMMANDS = $CONFIG_COMMANDS
- $ $0 $@
-
-on `(hostname || uname -n) 2>/dev/null | sed 1q`
-"
-
-# Files that config.status was made for.
-config_files=" Makefile src/Makefile"
-config_headers=" src/config.h"
-config_commands=" depfiles"
-
-ac_cs_usage="\
-\`$as_me' instantiates files from templates according to the
-current configuration.
-
-Usage: $0 [OPTIONS] [FILE]...
-
- -h, --help print this help, then exit
- -V, --version print version number and configuration settings, then exit
- -q, --quiet do not print progress messages
- -d, --debug don't remove temporary files
- --recheck update $as_me by reconfiguring in the same conditions
- --file=FILE[:TEMPLATE]
- instantiate the configuration file FILE
- --header=FILE[:TEMPLATE]
- instantiate the configuration header FILE
-
-Configuration files:
-$config_files
-
-Configuration headers:
-$config_headers
-
-Configuration commands:
-$config_commands
-
-Report bugs to <[email protected]>."
-
-ac_cs_version="\
-wdfs config.status 1.4.2
-configured by ./configure, generated by GNU Autoconf 2.61,
- with options \"\"
-
-Copyright (C) 2006 Free Software Foundation, Inc.
-This config.status script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it."
-
-ac_pwd='/xj/waitman/wdfs'
-srcdir='.'
-INSTALL='/usr/bin/install -c'
-# If no file are specified by the user, then we need to provide default
-# value. By we need to know if files were specified by the user.
-ac_need_defaults=:
-while test $# != 0
-do
- case $1 in
- --*=*)
- ac_option=`expr "X$1" : 'X\([^=]*\)='`
- ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
- ac_shift=:
- ;;
- *)
- ac_option=$1
- ac_optarg=$2
- ac_shift=shift
- ;;
- esac
-
- case $ac_option in
- # Handling of the options.
- -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
- ac_cs_recheck=: ;;
- --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
- echo "$ac_cs_version"; exit ;;
- --debug | --debu | --deb | --de | --d | -d )
- debug=: ;;
- --file | --fil | --fi | --f )
- $ac_shift
- CONFIG_FILES="$CONFIG_FILES $ac_optarg"
- ac_need_defaults=false;;
- --header | --heade | --head | --hea )
- $ac_shift
- CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg"
- ac_need_defaults=false;;
- --he | --h)
- # Conflict between --help and --header
- { echo "$as_me: error: ambiguous option: $1
-Try \`$0 --help' for more information." >&2
- { (exit 1); exit 1; }; };;
- --help | --hel | -h )
- echo "$ac_cs_usage"; exit ;;
- -q | -quiet | --quiet | --quie | --qui | --qu | --q \
- | -silent | --silent | --silen | --sile | --sil | --si | --s)
- ac_cs_silent=: ;;
-
- # This is an error.
- -*) { echo "$as_me: error: unrecognized option: $1
-Try \`$0 --help' for more information." >&2
- { (exit 1); exit 1; }; } ;;
-
- *) ac_config_targets="$ac_config_targets $1"
- ac_need_defaults=false ;;
-
- esac
- shift
-done
-
-ac_configure_extra_args=
-
-if $ac_cs_silent; then
- exec 6>/dev/null
- ac_configure_extra_args="$ac_configure_extra_args --silent"
-fi
-
-if $ac_cs_recheck; then
- echo "running CONFIG_SHELL=/bin/sh /bin/sh ./configure " $ac_configure_extra_args " --no-create --no-recursion" >&6
- CONFIG_SHELL=/bin/sh
- export CONFIG_SHELL
- exec /bin/sh "./configure" $ac_configure_extra_args --no-create --no-recursion
-fi
-
-exec 5>>config.log
-{
- echo
- sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
-## Running $as_me. ##
-_ASBOX
- echo "$ac_log"
-} >&5
-
-#
-# INIT-COMMANDS
-#
-AMDEP_TRUE="" ac_aux_dir="."
-
-
-# Handling of arguments.
-for ac_config_target in $ac_config_targets
-do
- case $ac_config_target in
- "src/config.h") CONFIG_HEADERS="$CONFIG_HEADERS src/config.h" ;;
- "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;;
- "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
- "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;;
-
- *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
-echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
- { (exit 1); exit 1; }; };;
- esac
-done
-
-
-# If the user did not use the arguments to specify the items to instantiate,
-# then the envvar interface is used. Set only those that are not.
-# We use the long form for the default assignment because of an extremely
-# bizarre bug on SunOS 4.1.3.
-if $ac_need_defaults; then
- test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
- test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
- test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands
-fi
-
-# Have a temporary directory for convenience. Make it in the build tree
-# simply because there is no reason against having it here, and in addition,
-# creating and moving files from /tmp can sometimes cause problems.
-# Hook for its removal unless debugging.
-# Note that there is a small window in which the directory will not be cleaned:
-# after its creation but before its name has been assigned to `$tmp'.
-$debug ||
-{
- tmp=
- trap 'exit_status=$?
- { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
-' 0
- trap '{ (exit 1); exit 1; }' 1 2 13 15
-}
-# Create a (secure) tmp directory for tmp files.
-
-{
- tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
- test -n "$tmp" && test -d "$tmp"
-} ||
-{
- tmp=./conf$$-$RANDOM
- (umask 077 && mkdir "$tmp")
-} ||
-{
- echo "$me: cannot create a temporary directory in ." >&2
- { (exit 1); exit 1; }
-}
-
-#
-# Set up the sed scripts for CONFIG_FILES section.
-#
-
-# No need to generate the scripts if there are no CONFIG_FILES.
-# This happens for instance when ./config.status config.h
-if test -n "$CONFIG_FILES"; then
-
-cat >"$tmp/subs-1.sed" <<\CEOF
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end
-s,@SHELL@,|#_!!_#|/bin/sh,g
-s,@PATH_SEPARATOR@,|#_!!_#|:,g
-s,@PACKAGE_NAME@,|#_!!_#|wdfs,g
-s,@PACKAGE_TARNAME@,|#_!!_#|wdfs,g
-s,@PACKAGE_VERSION@,|#_!!_#|1.4.2,g
-s,@PACKAGE_STRING@,|#_!!_#|wdfs 1.4.2,g
-s,@PACKAGE_BUGREPORT@,|#_!!_#|noedler@|#_!!_#|web.de,g
-s,@exec_prefix@,|#_!!_#|${prefix},g
-s,@prefix@,|#_!!_#|/usr/local,g
-s,@program_transform_name@,|#_!!_#|s\,x\,x\,,g
-s,@bindir@,|#_!!_#|${exec_prefix}/bin,g
-s,@sbindir@,|#_!!_#|${exec_prefix}/sbin,g
-s,@libexecdir@,|#_!!_#|${exec_prefix}/libexec,g
-s,@datarootdir@,|#_!!_#|${prefix}/share,g
-s,@datadir@,|#_!!_#|${datarootdir},g
-s,@sysconfdir@,|#_!!_#|${prefix}/etc,g
-s,@sharedstatedir@,|#_!!_#|${prefix}/com,g
-s,@localstatedir@,|#_!!_#|${prefix}/var,g
-s,@includedir@,|#_!!_#|${prefix}/include,g
-s,@oldincludedir@,|#_!!_#|/usr/include,g
-s,@docdir@,|#_!!_#|${datarootdir}/doc/${PACKAGE_TARNAME},g
-s,@infodir@,|#_!!_#|${datarootdir}/info,g
-s,@htmldir@,|#_!!_#|${docdir},g
-s,@dvidir@,|#_!!_#|${docdir},g
-s,@pdfdir@,|#_!!_#|${docdir},g
-s,@psdir@,|#_!!_#|${docdir},g
-s,@libdir@,|#_!!_#|${exec_prefix}/lib,g
-s,@localedir@,|#_!!_#|${datarootdir}/locale,g
-s,@mandir@,|#_!!_#|${datarootdir}/man,g
-s,@DEFS@,|#_!!_#|-DHAVE_CONFIG_H,g
-s,@ECHO_C@,|#_!!_#|,g
-s,@ECHO_N@,|#_!!_#|-n,g
-s,@ECHO_T@,|#_!!_#|,g
-s,@LIBS@,|#_!!_#|-L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl ,g
-s,@build_alias@,|#_!!_#|,g
-s,@host_alias@,|#_!!_#|,g
-s,@target_alias@,|#_!!_#|,g
-s,@INSTALL_PROGRAM@,|#_!!_#|${INSTALL},g
-s,@INSTALL_SCRIPT@,|#_!!_#|${INSTALL},g
-s,@INSTALL_DATA@,|#_!!_#|${INSTALL} -m 644,g
-s,@CYGPATH_W@,|#_!!_#|echo,g
-s,@PACKAGE@,|#_!!_#|wdfs,g
-s,@VERSION@,|#_!!_#|1.4.2,g
-s,@ACLOCAL@,|#_!!_#|${SHELL} /xj/waitman/wdfs/missing --run aclocal-1.9,g
-s,@AUTOCONF@,|#_!!_#|${SHELL} /xj/waitman/wdfs/missing --run autoconf,g
-s,@AUTOMAKE@,|#_!!_#|${SHELL} /xj/waitman/wdfs/missing --run automake-1.9,g
-s,@AUTOHEADER@,|#_!!_#|${SHELL} /xj/waitman/wdfs/missing --run autoheader,g
-s,@MAKEINFO@,|#_!!_#|${SHELL} /xj/waitman/wdfs/missing --run makeinfo,g
-s,@install_sh@,|#_!!_#|/xj/waitman/wdfs/install-sh,g
-s,@STRIP@,|#_!!_#|,g
-s,@INSTALL_STRIP_PROGRAM@,|#_!!_#|${SHELL} $(install_sh) -c -s,g
-s,@mkdir_p@,|#_!!_#|$(install_sh) -d,g
-s,@AWK@,|#_!!_#|nawk,g
-s,@SET_MAKE@,|#_!!_#|,g
-s,@am__leading_dot@,|#_!!_#|.,g
-s,@AMTAR@,|#_!!_#|${SHELL} /xj/waitman/wdfs/missing --run tar,g
-s,@am__tar@,|#_!!_#|${AMTAR} chof - "$$tardir",g
-s,@am__untar@,|#_!!_#|${AMTAR} xf -,g
-s,@CC@,|#_!!_#|cc,g
-s,@CFLAGS@,|#_!!_#|-g -O2 -I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include -Wall -D_GNU_SOURCE -D_REENTRANT,g
-s,@LDFLAGS@,|#_!!_#|,g
-s,@CPPFLAGS@,|#_!!_#|,g
-s,@ac_ct_CC@,|#_!!_#|,g
-s,@EXEEXT@,|#_!!_#|,g
-s,@OBJEXT@,|#_!!_#|o,g
-s,@DEPDIR@,|#_!!_#|.deps,g
-s,@am__include@,|#_!!_#|include,g
-s,@am__quote@,|#_!!_#|,g
-s,@AMDEP_TRUE@,|#_!!_#|,g
-s,@AMDEP_FALSE@,|#_!!_#|#,g
-s,@AMDEPBACKSLASH@,|#_!!_#|\\,g
-s,@CCDEPMODE@,|#_!!_#|depmode=gcc3,g
-s,@am__fastdepCC_TRUE@,|#_!!_#|,g
-s,@am__fastdepCC_FALSE@,|#_!!_#|#,g
-s,@CPP@,|#_!!_#|cc -E,g
-s,@GREP@,|#_!!_#|/usr/bin/grep,g
-s,@EGREP@,|#_!!_#|/usr/bin/grep -E,g
-s,@PKG_CONFIG@,|#_!!_#|/usr/local/bin/pkg-config,g
-s,@WDFS_CFLAGS@,|#_!!_#|-I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include ,g
-s,@WDFS_LIBS@,|#_!!_#|-L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl ,g
-s,@LIBOBJS@,|#_!!_#|,g
-s,@LTLIBOBJS@,|#_!!_#|,g
-:end
-s/|#_!!_#|//g
-CEOF
-fi # test -n "$CONFIG_FILES"
-
-
-for ac_tag in :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS
-do
- case $ac_tag in
- :[FHLC]) ac_mode=$ac_tag; continue;;
- esac
- case $ac_mode$ac_tag in
- :[FHL]*:*);;
- :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5
-echo "$as_me: error: Invalid tag $ac_tag." >&2;}
- { (exit 1); exit 1; }; };;
- :[FH]-) ac_tag=-:-;;
- :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
- esac
- ac_save_IFS=$IFS
- IFS=:
- set x $ac_tag
- IFS=$ac_save_IFS
- shift
- ac_file=$1
- shift
-
- case $ac_mode in
- :L) ac_source=$1;;
- :[FH])
- ac_file_inputs=
- for ac_f
- do
- case $ac_f in
- -) ac_f="$tmp/stdin";;
- *) # Look for the file first in the build tree, then in the source tree
- # (if the path is not absolute). The absolute path cannot be DOS-style,
- # because $ac_f cannot contain `:'.
- test -f "$ac_f" ||
- case $ac_f in
- [\\/$]*) false;;
- *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
- esac ||
- { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5
-echo "$as_me: error: cannot find input file: $ac_f" >&2;}
- { (exit 1); exit 1; }; };;
- esac
- ac_file_inputs="$ac_file_inputs $ac_f"
- done
-
- # Let's still pretend it is `configure' which instantiates (i.e., don't
- # use $as_me), people would be surprised to read:
- # /* config.h. Generated by config.status. */
- configure_input="Generated from "`IFS=:
- echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure."
- if test x"$ac_file" != x-; then
- configure_input="$ac_file. $configure_input"
- { echo "$as_me:$LINENO: creating $ac_file" >&5
-echo "$as_me: creating $ac_file" >&6;}
- fi
-
- case $ac_tag in
- *:-:* | *:-) cat >"$tmp/stdin";;
- esac
- ;;
- esac
-
- ac_dir=`$as_dirname -- "$ac_file" ||
-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$ac_file" : 'X\(//\)[^/]' \| \
- X"$ac_file" : 'X\(//\)$' \| \
- X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
-echo X"$ac_file" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- { as_dir="$ac_dir"
- case $as_dir in #(
- -*) as_dir=./$as_dir;;
- esac
- test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
- as_dirs=
- while :; do
- case $as_dir in #(
- *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
- *) as_qdir=$as_dir;;
- esac
- as_dirs="'$as_qdir' $as_dirs"
- as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$as_dir" : 'X\(//\)[^/]' \| \
- X"$as_dir" : 'X\(//\)$' \| \
- X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-echo X"$as_dir" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- test -d "$as_dir" && break
- done
- test -z "$as_dirs" || eval "mkdir $as_dirs"
- } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
-echo "$as_me: error: cannot create directory $as_dir" >&2;}
- { (exit 1); exit 1; }; }; }
- ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
- ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
- # A ".." for each directory in $ac_dir_suffix.
- ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
- case $ac_top_builddir_sub in
- "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
- *) ac_top_build_prefix=$ac_top_builddir_sub/ ;;
- esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
- .) # We are building in place.
- ac_srcdir=.
- ac_top_srcdir=$ac_top_builddir_sub
- ac_abs_top_srcdir=$ac_pwd ;;
- [\\/]* | ?:[\\/]* ) # Absolute name.
- ac_srcdir=$srcdir$ac_dir_suffix;
- ac_top_srcdir=$srcdir
- ac_abs_top_srcdir=$srcdir ;;
- *) # Relative name.
- ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
- ac_top_srcdir=$ac_top_build_prefix$srcdir
- ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
-
- case $ac_mode in
- :F)
- #
- # CONFIG_FILE
- #
-
- case $INSTALL in
- [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;;
- *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;;
- esac
-# If the template does not know about datarootdir, expand it.
-# FIXME: This hack should be removed a few years after 2.60.
-ac_datarootdir_hack=; ac_datarootdir_seen=
-
-case `sed -n '/datarootdir/ {
- p
- q
-}
-/@datadir@/p
-/@docdir@/p
-/@infodir@/p
-/@localedir@/p
-/@mandir@/p
-' $ac_file_inputs` in
-*datarootdir*) ac_datarootdir_seen=yes;;
-*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
- { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
-echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
- ac_datarootdir_hack='
- s&@datadir@&${datarootdir}&g
- s&@docdir@&${datarootdir}/doc/${PACKAGE_TARNAME}&g
- s&@infodir@&${datarootdir}/info&g
- s&@localedir@&${datarootdir}/locale&g
- s&@mandir@&${datarootdir}/man&g
- s&\${datarootdir}&${prefix}/share&g' ;;
-esac
- sed "/^[ ]*VPATH[ ]*=/{
-s/:*\$(srcdir):*/:/
-s/:*\${srcdir}:*/:/
-s/:*@srcdir@:*/:/
-s/^\([^=]*=[ ]*\):*/\1/
-s/:*$//
-s/^[^=]*=[ ]*$//
-}
-
-:t
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s&@configure_input@&$configure_input&;t t
-s&@top_builddir@&$ac_top_builddir_sub&;t t
-s&@srcdir@&$ac_srcdir&;t t
-s&@abs_srcdir@&$ac_abs_srcdir&;t t
-s&@top_srcdir@&$ac_top_srcdir&;t t
-s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
-s&@builddir@&$ac_builddir&;t t
-s&@abs_builddir@&$ac_abs_builddir&;t t
-s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
-s&@INSTALL@&$ac_INSTALL&;t t
-$ac_datarootdir_hack
-" $ac_file_inputs | sed -f "$tmp/subs-1.sed" >$tmp/out
-
-test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
- { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
- { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
- { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined. Please make sure it is defined." >&5
-echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined. Please make sure it is defined." >&2;}
-
- rm -f "$tmp/stdin"
- case $ac_file in
- -) cat "$tmp/out"; rm -f "$tmp/out";;
- *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;;
- esac
- ;;
- :H)
- #
- # CONFIG_HEADER
- #
- # First, check the format of the line:
- cat >"$tmp/defines.sed" <<\CEOF
-/^[ ]*#[ ]*undef[ ][ ]*[_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ][_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*[ ]*$/b def
-/^[ ]*#[ ]*define[ ][ ]*[_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ][_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*[( ]/b def
-b
-:def
-s/$/ /
-s,^\([ #]*\)[^ ]*\([ ]*PACKAGE_NAME\)[ (].*,\1define\2 "wdfs" ,
-s,^\([ #]*\)[^ ]*\([ ]*PACKAGE_TARNAME\)[ (].*,\1define\2 "wdfs" ,
-s,^\([ #]*\)[^ ]*\([ ]*PACKAGE_VERSION\)[ (].*,\1define\2 "1.4.2" ,
-s,^\([ #]*\)[^ ]*\([ ]*PACKAGE_STRING\)[ (].*,\1define\2 "wdfs 1.4.2" ,
-s,^\([ #]*\)[^ ]*\([ ]*PACKAGE_BUGREPORT\)[ (].*,\1define\2 "[email protected]" ,
-s,^\([ #]*\)[^ ]*\([ ]*PACKAGE\)[ (].*,\1define\2 "wdfs" ,
-s,^\([ #]*\)[^ ]*\([ ]*VERSION\)[ (].*,\1define\2 "1.4.2" ,
-s,^\([ #]*\)[^ ]*\([ ]*STDC_HEADERS\)[ (].*,\1define\2 1 ,
-s,^\([ #]*\)[^ ]*\([ ]*HAVE_SYS_TYPES_H\)[ (].*,\1define\2 1 ,
-s,^\([ #]*\)[^ ]*\([ ]*HAVE_SYS_STAT_H\)[ (].*,\1define\2 1 ,
-s,^\([ #]*\)[^ ]*\([ ]*HAVE_STDLIB_H\)[ (].*,\1define\2 1 ,
-s,^\([ #]*\)[^ ]*\([ ]*HAVE_STRING_H\)[ (].*,\1define\2 1 ,
-s,^\([ #]*\)[^ ]*\([ ]*HAVE_MEMORY_H\)[ (].*,\1define\2 1 ,
-s,^\([ #]*\)[^ ]*\([ ]*HAVE_STRINGS_H\)[ (].*,\1define\2 1 ,
-s,^\([ #]*\)[^ ]*\([ ]*HAVE_INTTYPES_H\)[ (].*,\1define\2 1 ,
-s,^\([ #]*\)[^ ]*\([ ]*HAVE_STDINT_H\)[ (].*,\1define\2 1 ,
-s,^\([ #]*\)[^ ]*\([ ]*HAVE_UNISTD_H\)[ (].*,\1define\2 1 ,
-s,^\([ #]*\)[^ ]*\([ ]*HAVE_PTHREAD_H\)[ (].*,\1define\2 1 ,
-s,^\([ #]*\)[^ ]*\([ ]*HAVE_STRNDUP\)[ (].*,\1define\2 1 ,
-s/ $//
-s,^[ #]*u.*,/* & */,
-CEOF
- sed -f "$tmp/defines.sed" $ac_file_inputs >"$tmp/out1"
-ac_result="$tmp/out1"
- if test x"$ac_file" != x-; then
- echo "/* $configure_input */" >"$tmp/config.h"
- cat "$ac_result" >>"$tmp/config.h"
- if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then
- { echo "$as_me:$LINENO: $ac_file is unchanged" >&5
-echo "$as_me: $ac_file is unchanged" >&6;}
- else
- rm -f $ac_file
- mv "$tmp/config.h" $ac_file
- fi
- else
- echo "/* $configure_input */"
- cat "$ac_result"
- fi
- rm -f "$tmp/out12"
-# Compute $ac_file's index in $config_headers.
-_am_stamp_count=1
-for _am_header in $config_headers :; do
- case $_am_header in
- $ac_file | $ac_file:* )
- break ;;
- * )
- _am_stamp_count=`expr $_am_stamp_count + 1` ;;
- esac
-done
-echo "timestamp for $ac_file" >`$as_dirname -- $ac_file ||
-$as_expr X$ac_file : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X$ac_file : 'X\(//\)[^/]' \| \
- X$ac_file : 'X\(//\)$' \| \
- X$ac_file : 'X\(/\)' \| . 2>/dev/null ||
-echo X$ac_file |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`/stamp-h$_am_stamp_count
- ;;
-
- :C) { echo "$as_me:$LINENO: executing $ac_file commands" >&5
-echo "$as_me: executing $ac_file commands" >&6;}
- ;;
- esac
-
-
- case $ac_file$ac_mode in
- "depfiles":C) test x"$AMDEP_TRUE" != x"" || for mf in $CONFIG_FILES; do
- # Strip MF so we end up with the name of the file.
- mf=`echo "$mf" | sed -e 's/:.*$//'`
- # Check whether this is an Automake generated Makefile or not.
- # We used to match only the files named `Makefile.in', but
- # some people rename them; so instead we look at the file content.
- # Grep'ing the first line is not enough: some people post-process
- # each Makefile.in and add a new line on top of each file to say so.
- # So let's grep whole file.
- if grep '^#.*generated by automake' $mf > /dev/null 2>&1; then
- dirpart=`$as_dirname -- "$mf" ||
-$as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$mf" : 'X\(//\)[^/]' \| \
- X"$mf" : 'X\(//\)$' \| \
- X"$mf" : 'X\(/\)' \| . 2>/dev/null ||
-echo X"$mf" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- else
- continue
- fi
- # Extract the definition of DEPDIR, am__include, and am__quote
- # from the Makefile without running `make'.
- DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"`
- test -z "$DEPDIR" && continue
- am__include=`sed -n 's/^am__include = //p' < "$mf"`
- test -z "am__include" && continue
- am__quote=`sed -n 's/^am__quote = //p' < "$mf"`
- # When using ansi2knr, U may be empty or an underscore; expand it
- U=`sed -n 's/^U = //p' < "$mf"`
- # Find all dependency output files, they are included files with
- # $(DEPDIR) in their names. We invoke sed twice because it is the
- # simplest approach to changing $(DEPDIR) to its actual value in the
- # expansion.
- for file in `sed -n "
- s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \
- sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do
- # Make sure the directory exists.
- test -f "$dirpart/$file" && continue
- fdir=`$as_dirname -- "$file" ||
-$as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$file" : 'X\(//\)[^/]' \| \
- X"$file" : 'X\(//\)$' \| \
- X"$file" : 'X\(/\)' \| . 2>/dev/null ||
-echo X"$file" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- { as_dir=$dirpart/$fdir
- case $as_dir in #(
- -*) as_dir=./$as_dir;;
- esac
- test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
- as_dirs=
- while :; do
- case $as_dir in #(
- *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
- *) as_qdir=$as_dir;;
- esac
- as_dirs="'$as_qdir' $as_dirs"
- as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$as_dir" : 'X\(//\)[^/]' \| \
- X"$as_dir" : 'X\(//\)$' \| \
- X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-echo X"$as_dir" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- test -d "$as_dir" && break
- done
- test -z "$as_dirs" || eval "mkdir $as_dirs"
- } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
-echo "$as_me: error: cannot create directory $as_dir" >&2;}
- { (exit 1); exit 1; }; }; }
- # echo "creating $dirpart/$file"
- echo '# dummy' > "$dirpart/$file"
- done
-done
- ;;
-
- esac
-done # for ac_tag
-
-
-{ (exit 0); exit 0; }
diff --git a/src/.deps/cache.Po b/src/.deps/cache.Po
deleted file mode 100644
index 82b1710..0000000
--- a/src/.deps/cache.Po
+++ /dev/null
@@ -1,409 +0,0 @@
-cache.o: cache.c /usr/include/stdio.h /usr/include/sys/cdefs.h \
- /usr/include/sys/_null.h /usr/include/sys/_types.h \
- /usr/include/machine/_types.h /usr/include/x86/_types.h \
- /usr/include/stdlib.h /usr/include/string.h /usr/include/strings.h \
- /usr/include/xlocale/_strings.h /usr/include/xlocale/_string.h \
- /usr/include/assert.h /usr/local/include/glib-2.0/glib.h \
- /usr/local/include/glib-2.0/glib/galloca.h \
- /usr/local/include/glib-2.0/glib/gtypes.h \
- /usr/local/lib/glib-2.0/include/glibconfig.h \
- /usr/local/include/glib-2.0/glib/gmacros.h /usr/include/stddef.h \
- /usr/include/limits.h /usr/include/sys/limits.h \
- /usr/include/machine/_limits.h /usr/include/x86/_limits.h \
- /usr/include/sys/syslimits.h /usr/include/float.h \
- /usr/include/x86/float.h \
- /usr/local/include/glib-2.0/glib/gversionmacros.h /usr/include/time.h \
- /usr/include/sys/timespec.h /usr/include/sys/_timespec.h \
- /usr/include/xlocale/_time.h /usr/local/include/glib-2.0/glib/garray.h \
- /usr/local/include/glib-2.0/glib/gasyncqueue.h \
- /usr/local/include/glib-2.0/glib/gthread.h \
- /usr/local/include/glib-2.0/glib/gatomic.h \
- /usr/local/include/glib-2.0/glib/gerror.h /usr/include/stdarg.h \
- /usr/include/x86/stdarg.h /usr/local/include/glib-2.0/glib/gquark.h \
- /usr/local/include/glib-2.0/glib/gutils.h \
- /usr/local/include/glib-2.0/glib/gbacktrace.h /usr/include/signal.h \
- /usr/include/sys/signal.h /usr/include/sys/_sigset.h \
- /usr/include/machine/signal.h /usr/include/x86/signal.h \
- /usr/include/machine/trap.h /usr/include/x86/trap.h \
- /usr/local/include/glib-2.0/glib/gbase64.h \
- /usr/local/include/glib-2.0/glib/gbitlock.h \
- /usr/local/include/glib-2.0/glib/gbookmarkfile.h \
- /usr/local/include/glib-2.0/glib/gbytes.h \
- /usr/local/include/glib-2.0/glib/gcharset.h \
- /usr/local/include/glib-2.0/glib/gchecksum.h \
- /usr/local/include/glib-2.0/glib/gconvert.h \
- /usr/local/include/glib-2.0/glib/gdataset.h \
- /usr/local/include/glib-2.0/glib/gdate.h \
- /usr/local/include/glib-2.0/glib/gdatetime.h \
- /usr/local/include/glib-2.0/glib/gtimezone.h \
- /usr/local/include/glib-2.0/glib/gdir.h /usr/include/dirent.h \
- /usr/include/sys/dirent.h /usr/local/include/glib-2.0/glib/genviron.h \
- /usr/local/include/glib-2.0/glib/gfileutils.h \
- /usr/local/include/glib-2.0/glib/ggettext.h \
- /usr/local/include/glib-2.0/glib/ghash.h \
- /usr/local/include/glib-2.0/glib/glist.h \
- /usr/local/include/glib-2.0/glib/gmem.h \
- /usr/local/include/glib-2.0/glib/gnode.h \
- /usr/local/include/glib-2.0/glib/ghmac.h \
- /usr/local/include/glib-2.0/glib/ghook.h \
- /usr/local/include/glib-2.0/glib/ghostutils.h \
- /usr/local/include/glib-2.0/glib/giochannel.h \
- /usr/local/include/glib-2.0/glib/gmain.h \
- /usr/local/include/glib-2.0/glib/gpoll.h \
- /usr/local/include/glib-2.0/glib/gslist.h \
- /usr/local/include/glib-2.0/glib/gstring.h \
- /usr/local/include/glib-2.0/glib/gunicode.h \
- /usr/local/include/glib-2.0/glib/gkeyfile.h \
- /usr/local/include/glib-2.0/glib/gmappedfile.h \
- /usr/local/include/glib-2.0/glib/gmarkup.h \
- /usr/local/include/glib-2.0/glib/gmessages.h \
- /usr/local/include/glib-2.0/glib/goption.h \
- /usr/local/include/glib-2.0/glib/gpattern.h \
- /usr/local/include/glib-2.0/glib/gprimes.h \
- /usr/local/include/glib-2.0/glib/gqsort.h \
- /usr/local/include/glib-2.0/glib/gqueue.h \
- /usr/local/include/glib-2.0/glib/grand.h \
- /usr/local/include/glib-2.0/glib/gregex.h \
- /usr/local/include/glib-2.0/glib/gscanner.h \
- /usr/local/include/glib-2.0/glib/gsequence.h \
- /usr/local/include/glib-2.0/glib/gshell.h \
- /usr/local/include/glib-2.0/glib/gslice.h \
- /usr/local/include/glib-2.0/glib/gspawn.h \
- /usr/local/include/glib-2.0/glib/gstrfuncs.h \
- /usr/local/include/glib-2.0/glib/gstringchunk.h \
- /usr/local/include/glib-2.0/glib/gtestutils.h \
- /usr/local/include/glib-2.0/glib/gthreadpool.h \
- /usr/local/include/glib-2.0/glib/gtimer.h \
- /usr/local/include/glib-2.0/glib/gtrashstack.h \
- /usr/local/include/glib-2.0/glib/gtree.h \
- /usr/local/include/glib-2.0/glib/gurifuncs.h \
- /usr/local/include/glib-2.0/glib/gvarianttype.h \
- /usr/local/include/glib-2.0/glib/gvariant.h \
- /usr/local/include/glib-2.0/glib/gversion.h \
- /usr/local/include/glib-2.0/glib/deprecated/gallocator.h \
- /usr/local/include/glib-2.0/glib/deprecated/gcache.h \
- /usr/local/include/glib-2.0/glib/deprecated/gcompletion.h \
- /usr/local/include/glib-2.0/glib/deprecated/gmain.h \
- /usr/local/include/glib-2.0/glib/deprecated/grel.h \
- /usr/local/include/glib-2.0/glib/deprecated/gthread.h \
- /usr/include/sys/types.h /usr/include/machine/endian.h \
- /usr/include/x86/endian.h /usr/include/sys/_pthreadtypes.h \
- /usr/include/sys/_stdint.h /usr/include/sys/select.h \
- /usr/include/sys/_timeval.h /usr/include/pthread.h \
- /usr/include/sched.h \
- /usr/local/include/glib-2.0/glib/glib-autocleanups.h \
- /usr/include/unistd.h /usr/include/sys/unistd.h wdfs-main.h config.h \
- /usr/local/include/fuse/fuse.h /usr/local/include/fuse/fuse_common.h \
- /usr/local/include/fuse/fuse_opt.h /usr/include/stdint.h \
- /usr/include/machine/_stdint.h /usr/include/x86/_stdint.h \
- /usr/local/include/fuse/fuse_common_compat.h /usr/include/fcntl.h \
- /usr/include/utime.h /usr/include/sys/stat.h /usr/include/sys/time.h \
- /usr/include/sys/statvfs.h /usr/include/sys/uio.h \
- /usr/include/sys/_iovec.h /usr/local/include/fuse/fuse_compat.h \
- /usr/local/include/neon/ne_basic.h \
- /usr/local/include/neon/ne_request.h \
- /usr/local/include/neon/ne_utils.h /usr/local/include/neon/ne_defs.h \
- /usr/local/include/neon/ne_string.h /usr/local/include/neon/ne_alloc.h \
- /usr/local/include/neon/ne_session.h /usr/local/include/neon/ne_ssl.h \
- /usr/local/include/neon/ne_uri.h /usr/local/include/neon/ne_socket.h \
- cache.h
-
-/usr/include/stdio.h:
-
-/usr/include/sys/cdefs.h:
-
-/usr/include/sys/_null.h:
-
-/usr/include/sys/_types.h:
-
-/usr/include/machine/_types.h:
-
-/usr/include/x86/_types.h:
-
-/usr/include/stdlib.h:
-
-/usr/include/string.h:
-
-/usr/include/strings.h:
-
-/usr/include/xlocale/_strings.h:
-
-/usr/include/xlocale/_string.h:
-
-/usr/include/assert.h:
-
-/usr/local/include/glib-2.0/glib.h:
-
-/usr/local/include/glib-2.0/glib/galloca.h:
-
-/usr/local/include/glib-2.0/glib/gtypes.h:
-
-/usr/local/lib/glib-2.0/include/glibconfig.h:
-
-/usr/local/include/glib-2.0/glib/gmacros.h:
-
-/usr/include/stddef.h:
-
-/usr/include/limits.h:
-
-/usr/include/sys/limits.h:
-
-/usr/include/machine/_limits.h:
-
-/usr/include/x86/_limits.h:
-
-/usr/include/sys/syslimits.h:
-
-/usr/include/float.h:
-
-/usr/include/x86/float.h:
-
-/usr/local/include/glib-2.0/glib/gversionmacros.h:
-
-/usr/include/time.h:
-
-/usr/include/sys/timespec.h:
-
-/usr/include/sys/_timespec.h:
-
-/usr/include/xlocale/_time.h:
-
-/usr/local/include/glib-2.0/glib/garray.h:
-
-/usr/local/include/glib-2.0/glib/gasyncqueue.h:
-
-/usr/local/include/glib-2.0/glib/gthread.h:
-
-/usr/local/include/glib-2.0/glib/gatomic.h:
-
-/usr/local/include/glib-2.0/glib/gerror.h:
-
-/usr/include/stdarg.h:
-
-/usr/include/x86/stdarg.h:
-
-/usr/local/include/glib-2.0/glib/gquark.h:
-
-/usr/local/include/glib-2.0/glib/gutils.h:
-
-/usr/local/include/glib-2.0/glib/gbacktrace.h:
-
-/usr/include/signal.h:
-
-/usr/include/sys/signal.h:
-
-/usr/include/sys/_sigset.h:
-
-/usr/include/machine/signal.h:
-
-/usr/include/x86/signal.h:
-
-/usr/include/machine/trap.h:
-
-/usr/include/x86/trap.h:
-
-/usr/local/include/glib-2.0/glib/gbase64.h:
-
-/usr/local/include/glib-2.0/glib/gbitlock.h:
-
-/usr/local/include/glib-2.0/glib/gbookmarkfile.h:
-
-/usr/local/include/glib-2.0/glib/gbytes.h:
-
-/usr/local/include/glib-2.0/glib/gcharset.h:
-
-/usr/local/include/glib-2.0/glib/gchecksum.h:
-
-/usr/local/include/glib-2.0/glib/gconvert.h:
-
-/usr/local/include/glib-2.0/glib/gdataset.h:
-
-/usr/local/include/glib-2.0/glib/gdate.h:
-
-/usr/local/include/glib-2.0/glib/gdatetime.h:
-
-/usr/local/include/glib-2.0/glib/gtimezone.h:
-
-/usr/local/include/glib-2.0/glib/gdir.h:
-
-/usr/include/dirent.h:
-
-/usr/include/sys/dirent.h:
-
-/usr/local/include/glib-2.0/glib/genviron.h:
-
-/usr/local/include/glib-2.0/glib/gfileutils.h:
-
-/usr/local/include/glib-2.0/glib/ggettext.h:
-
-/usr/local/include/glib-2.0/glib/ghash.h:
-
-/usr/local/include/glib-2.0/glib/glist.h:
-
-/usr/local/include/glib-2.0/glib/gmem.h:
-
-/usr/local/include/glib-2.0/glib/gnode.h:
-
-/usr/local/include/glib-2.0/glib/ghmac.h:
-
-/usr/local/include/glib-2.0/glib/ghook.h:
-
-/usr/local/include/glib-2.0/glib/ghostutils.h:
-
-/usr/local/include/glib-2.0/glib/giochannel.h:
-
-/usr/local/include/glib-2.0/glib/gmain.h:
-
-/usr/local/include/glib-2.0/glib/gpoll.h:
-
-/usr/local/include/glib-2.0/glib/gslist.h:
-
-/usr/local/include/glib-2.0/glib/gstring.h:
-
-/usr/local/include/glib-2.0/glib/gunicode.h:
-
-/usr/local/include/glib-2.0/glib/gkeyfile.h:
-
-/usr/local/include/glib-2.0/glib/gmappedfile.h:
-
-/usr/local/include/glib-2.0/glib/gmarkup.h:
-
-/usr/local/include/glib-2.0/glib/gmessages.h:
-
-/usr/local/include/glib-2.0/glib/goption.h:
-
-/usr/local/include/glib-2.0/glib/gpattern.h:
-
-/usr/local/include/glib-2.0/glib/gprimes.h:
-
-/usr/local/include/glib-2.0/glib/gqsort.h:
-
-/usr/local/include/glib-2.0/glib/gqueue.h:
-
-/usr/local/include/glib-2.0/glib/grand.h:
-
-/usr/local/include/glib-2.0/glib/gregex.h:
-
-/usr/local/include/glib-2.0/glib/gscanner.h:
-
-/usr/local/include/glib-2.0/glib/gsequence.h:
-
-/usr/local/include/glib-2.0/glib/gshell.h:
-
-/usr/local/include/glib-2.0/glib/gslice.h:
-
-/usr/local/include/glib-2.0/glib/gspawn.h:
-
-/usr/local/include/glib-2.0/glib/gstrfuncs.h:
-
-/usr/local/include/glib-2.0/glib/gstringchunk.h:
-
-/usr/local/include/glib-2.0/glib/gtestutils.h:
-
-/usr/local/include/glib-2.0/glib/gthreadpool.h:
-
-/usr/local/include/glib-2.0/glib/gtimer.h:
-
-/usr/local/include/glib-2.0/glib/gtrashstack.h:
-
-/usr/local/include/glib-2.0/glib/gtree.h:
-
-/usr/local/include/glib-2.0/glib/gurifuncs.h:
-
-/usr/local/include/glib-2.0/glib/gvarianttype.h:
-
-/usr/local/include/glib-2.0/glib/gvariant.h:
-
-/usr/local/include/glib-2.0/glib/gversion.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gallocator.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gcache.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gcompletion.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gmain.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/grel.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gthread.h:
-
-/usr/include/sys/types.h:
-
-/usr/include/machine/endian.h:
-
-/usr/include/x86/endian.h:
-
-/usr/include/sys/_pthreadtypes.h:
-
-/usr/include/sys/_stdint.h:
-
-/usr/include/sys/select.h:
-
-/usr/include/sys/_timeval.h:
-
-/usr/include/pthread.h:
-
-/usr/include/sched.h:
-
-/usr/local/include/glib-2.0/glib/glib-autocleanups.h:
-
-/usr/include/unistd.h:
-
-/usr/include/sys/unistd.h:
-
-wdfs-main.h:
-
-config.h:
-
-/usr/local/include/fuse/fuse.h:
-
-/usr/local/include/fuse/fuse_common.h:
-
-/usr/local/include/fuse/fuse_opt.h:
-
-/usr/include/stdint.h:
-
-/usr/include/machine/_stdint.h:
-
-/usr/include/x86/_stdint.h:
-
-/usr/local/include/fuse/fuse_common_compat.h:
-
-/usr/include/fcntl.h:
-
-/usr/include/utime.h:
-
-/usr/include/sys/stat.h:
-
-/usr/include/sys/time.h:
-
-/usr/include/sys/statvfs.h:
-
-/usr/include/sys/uio.h:
-
-/usr/include/sys/_iovec.h:
-
-/usr/local/include/fuse/fuse_compat.h:
-
-/usr/local/include/neon/ne_basic.h:
-
-/usr/local/include/neon/ne_request.h:
-
-/usr/local/include/neon/ne_utils.h:
-
-/usr/local/include/neon/ne_defs.h:
-
-/usr/local/include/neon/ne_string.h:
-
-/usr/local/include/neon/ne_alloc.h:
-
-/usr/local/include/neon/ne_session.h:
-
-/usr/local/include/neon/ne_ssl.h:
-
-/usr/local/include/neon/ne_uri.h:
-
-/usr/local/include/neon/ne_socket.h:
-
-cache.h:
diff --git a/src/.deps/svn.Po b/src/.deps/svn.Po
deleted file mode 100644
index 2f3c12c..0000000
--- a/src/.deps/svn.Po
+++ /dev/null
@@ -1,418 +0,0 @@
-svn.o: svn.c /usr/include/stdio.h /usr/include/sys/cdefs.h \
- /usr/include/sys/_null.h /usr/include/sys/_types.h \
- /usr/include/machine/_types.h /usr/include/x86/_types.h \
- /usr/include/stdlib.h /usr/include/string.h /usr/include/strings.h \
- /usr/include/xlocale/_strings.h /usr/include/xlocale/_string.h \
- /usr/include/assert.h /usr/include/unistd.h /usr/include/sys/types.h \
- /usr/include/machine/endian.h /usr/include/x86/endian.h \
- /usr/include/sys/_pthreadtypes.h /usr/include/sys/_stdint.h \
- /usr/include/sys/select.h /usr/include/sys/_sigset.h \
- /usr/include/sys/_timeval.h /usr/include/sys/timespec.h \
- /usr/include/sys/_timespec.h /usr/include/sys/unistd.h \
- /usr/local/include/glib-2.0/glib.h \
- /usr/local/include/glib-2.0/glib/galloca.h \
- /usr/local/include/glib-2.0/glib/gtypes.h \
- /usr/local/lib/glib-2.0/include/glibconfig.h \
- /usr/local/include/glib-2.0/glib/gmacros.h /usr/include/stddef.h \
- /usr/include/limits.h /usr/include/sys/limits.h \
- /usr/include/machine/_limits.h /usr/include/x86/_limits.h \
- /usr/include/sys/syslimits.h /usr/include/float.h \
- /usr/include/x86/float.h \
- /usr/local/include/glib-2.0/glib/gversionmacros.h /usr/include/time.h \
- /usr/include/xlocale/_time.h /usr/local/include/glib-2.0/glib/garray.h \
- /usr/local/include/glib-2.0/glib/gasyncqueue.h \
- /usr/local/include/glib-2.0/glib/gthread.h \
- /usr/local/include/glib-2.0/glib/gatomic.h \
- /usr/local/include/glib-2.0/glib/gerror.h /usr/include/stdarg.h \
- /usr/include/x86/stdarg.h /usr/local/include/glib-2.0/glib/gquark.h \
- /usr/local/include/glib-2.0/glib/gutils.h \
- /usr/local/include/glib-2.0/glib/gbacktrace.h /usr/include/signal.h \
- /usr/include/sys/signal.h /usr/include/machine/signal.h \
- /usr/include/x86/signal.h /usr/include/machine/trap.h \
- /usr/include/x86/trap.h /usr/local/include/glib-2.0/glib/gbase64.h \
- /usr/local/include/glib-2.0/glib/gbitlock.h \
- /usr/local/include/glib-2.0/glib/gbookmarkfile.h \
- /usr/local/include/glib-2.0/glib/gbytes.h \
- /usr/local/include/glib-2.0/glib/gcharset.h \
- /usr/local/include/glib-2.0/glib/gchecksum.h \
- /usr/local/include/glib-2.0/glib/gconvert.h \
- /usr/local/include/glib-2.0/glib/gdataset.h \
- /usr/local/include/glib-2.0/glib/gdate.h \
- /usr/local/include/glib-2.0/glib/gdatetime.h \
- /usr/local/include/glib-2.0/glib/gtimezone.h \
- /usr/local/include/glib-2.0/glib/gdir.h /usr/include/dirent.h \
- /usr/include/sys/dirent.h /usr/local/include/glib-2.0/glib/genviron.h \
- /usr/local/include/glib-2.0/glib/gfileutils.h \
- /usr/local/include/glib-2.0/glib/ggettext.h \
- /usr/local/include/glib-2.0/glib/ghash.h \
- /usr/local/include/glib-2.0/glib/glist.h \
- /usr/local/include/glib-2.0/glib/gmem.h \
- /usr/local/include/glib-2.0/glib/gnode.h \
- /usr/local/include/glib-2.0/glib/ghmac.h \
- /usr/local/include/glib-2.0/glib/ghook.h \
- /usr/local/include/glib-2.0/glib/ghostutils.h \
- /usr/local/include/glib-2.0/glib/giochannel.h \
- /usr/local/include/glib-2.0/glib/gmain.h \
- /usr/local/include/glib-2.0/glib/gpoll.h \
- /usr/local/include/glib-2.0/glib/gslist.h \
- /usr/local/include/glib-2.0/glib/gstring.h \
- /usr/local/include/glib-2.0/glib/gunicode.h \
- /usr/local/include/glib-2.0/glib/gkeyfile.h \
- /usr/local/include/glib-2.0/glib/gmappedfile.h \
- /usr/local/include/glib-2.0/glib/gmarkup.h \
- /usr/local/include/glib-2.0/glib/gmessages.h \
- /usr/local/include/glib-2.0/glib/goption.h \
- /usr/local/include/glib-2.0/glib/gpattern.h \
- /usr/local/include/glib-2.0/glib/gprimes.h \
- /usr/local/include/glib-2.0/glib/gqsort.h \
- /usr/local/include/glib-2.0/glib/gqueue.h \
- /usr/local/include/glib-2.0/glib/grand.h \
- /usr/local/include/glib-2.0/glib/gregex.h \
- /usr/local/include/glib-2.0/glib/gscanner.h \
- /usr/local/include/glib-2.0/glib/gsequence.h \
- /usr/local/include/glib-2.0/glib/gshell.h \
- /usr/local/include/glib-2.0/glib/gslice.h \
- /usr/local/include/glib-2.0/glib/gspawn.h \
- /usr/local/include/glib-2.0/glib/gstrfuncs.h \
- /usr/local/include/glib-2.0/glib/gstringchunk.h \
- /usr/local/include/glib-2.0/glib/gtestutils.h \
- /usr/local/include/glib-2.0/glib/gthreadpool.h \
- /usr/local/include/glib-2.0/glib/gtimer.h \
- /usr/local/include/glib-2.0/glib/gtrashstack.h \
- /usr/local/include/glib-2.0/glib/gtree.h \
- /usr/local/include/glib-2.0/glib/gurifuncs.h \
- /usr/local/include/glib-2.0/glib/gvarianttype.h \
- /usr/local/include/glib-2.0/glib/gvariant.h \
- /usr/local/include/glib-2.0/glib/gversion.h \
- /usr/local/include/glib-2.0/glib/deprecated/gallocator.h \
- /usr/local/include/glib-2.0/glib/deprecated/gcache.h \
- /usr/local/include/glib-2.0/glib/deprecated/gcompletion.h \
- /usr/local/include/glib-2.0/glib/deprecated/gmain.h \
- /usr/local/include/glib-2.0/glib/deprecated/grel.h \
- /usr/local/include/glib-2.0/glib/deprecated/gthread.h \
- /usr/include/pthread.h /usr/include/sched.h \
- /usr/local/include/glib-2.0/glib/glib-autocleanups.h \
- /usr/local/include/neon/ne_props.h \
- /usr/local/include/neon/ne_request.h \
- /usr/local/include/neon/ne_utils.h /usr/local/include/neon/ne_defs.h \
- /usr/local/include/neon/ne_string.h /usr/local/include/neon/ne_alloc.h \
- /usr/local/include/neon/ne_session.h /usr/local/include/neon/ne_ssl.h \
- /usr/local/include/neon/ne_uri.h /usr/local/include/neon/ne_socket.h \
- /usr/local/include/neon/ne_207.h /usr/local/include/neon/ne_xml.h \
- wdfs-main.h config.h /usr/local/include/fuse/fuse.h \
- /usr/local/include/fuse/fuse_common.h \
- /usr/local/include/fuse/fuse_opt.h /usr/include/stdint.h \
- /usr/include/machine/_stdint.h /usr/include/x86/_stdint.h \
- /usr/local/include/fuse/fuse_common_compat.h /usr/include/fcntl.h \
- /usr/include/utime.h /usr/include/sys/stat.h /usr/include/sys/time.h \
- /usr/include/sys/statvfs.h /usr/include/sys/uio.h \
- /usr/include/sys/_iovec.h /usr/local/include/fuse/fuse_compat.h \
- /usr/local/include/neon/ne_basic.h webdav.h svn.h
-
-/usr/include/stdio.h:
-
-/usr/include/sys/cdefs.h:
-
-/usr/include/sys/_null.h:
-
-/usr/include/sys/_types.h:
-
-/usr/include/machine/_types.h:
-
-/usr/include/x86/_types.h:
-
-/usr/include/stdlib.h:
-
-/usr/include/string.h:
-
-/usr/include/strings.h:
-
-/usr/include/xlocale/_strings.h:
-
-/usr/include/xlocale/_string.h:
-
-/usr/include/assert.h:
-
-/usr/include/unistd.h:
-
-/usr/include/sys/types.h:
-
-/usr/include/machine/endian.h:
-
-/usr/include/x86/endian.h:
-
-/usr/include/sys/_pthreadtypes.h:
-
-/usr/include/sys/_stdint.h:
-
-/usr/include/sys/select.h:
-
-/usr/include/sys/_sigset.h:
-
-/usr/include/sys/_timeval.h:
-
-/usr/include/sys/timespec.h:
-
-/usr/include/sys/_timespec.h:
-
-/usr/include/sys/unistd.h:
-
-/usr/local/include/glib-2.0/glib.h:
-
-/usr/local/include/glib-2.0/glib/galloca.h:
-
-/usr/local/include/glib-2.0/glib/gtypes.h:
-
-/usr/local/lib/glib-2.0/include/glibconfig.h:
-
-/usr/local/include/glib-2.0/glib/gmacros.h:
-
-/usr/include/stddef.h:
-
-/usr/include/limits.h:
-
-/usr/include/sys/limits.h:
-
-/usr/include/machine/_limits.h:
-
-/usr/include/x86/_limits.h:
-
-/usr/include/sys/syslimits.h:
-
-/usr/include/float.h:
-
-/usr/include/x86/float.h:
-
-/usr/local/include/glib-2.0/glib/gversionmacros.h:
-
-/usr/include/time.h:
-
-/usr/include/xlocale/_time.h:
-
-/usr/local/include/glib-2.0/glib/garray.h:
-
-/usr/local/include/glib-2.0/glib/gasyncqueue.h:
-
-/usr/local/include/glib-2.0/glib/gthread.h:
-
-/usr/local/include/glib-2.0/glib/gatomic.h:
-
-/usr/local/include/glib-2.0/glib/gerror.h:
-
-/usr/include/stdarg.h:
-
-/usr/include/x86/stdarg.h:
-
-/usr/local/include/glib-2.0/glib/gquark.h:
-
-/usr/local/include/glib-2.0/glib/gutils.h:
-
-/usr/local/include/glib-2.0/glib/gbacktrace.h:
-
-/usr/include/signal.h:
-
-/usr/include/sys/signal.h:
-
-/usr/include/machine/signal.h:
-
-/usr/include/x86/signal.h:
-
-/usr/include/machine/trap.h:
-
-/usr/include/x86/trap.h:
-
-/usr/local/include/glib-2.0/glib/gbase64.h:
-
-/usr/local/include/glib-2.0/glib/gbitlock.h:
-
-/usr/local/include/glib-2.0/glib/gbookmarkfile.h:
-
-/usr/local/include/glib-2.0/glib/gbytes.h:
-
-/usr/local/include/glib-2.0/glib/gcharset.h:
-
-/usr/local/include/glib-2.0/glib/gchecksum.h:
-
-/usr/local/include/glib-2.0/glib/gconvert.h:
-
-/usr/local/include/glib-2.0/glib/gdataset.h:
-
-/usr/local/include/glib-2.0/glib/gdate.h:
-
-/usr/local/include/glib-2.0/glib/gdatetime.h:
-
-/usr/local/include/glib-2.0/glib/gtimezone.h:
-
-/usr/local/include/glib-2.0/glib/gdir.h:
-
-/usr/include/dirent.h:
-
-/usr/include/sys/dirent.h:
-
-/usr/local/include/glib-2.0/glib/genviron.h:
-
-/usr/local/include/glib-2.0/glib/gfileutils.h:
-
-/usr/local/include/glib-2.0/glib/ggettext.h:
-
-/usr/local/include/glib-2.0/glib/ghash.h:
-
-/usr/local/include/glib-2.0/glib/glist.h:
-
-/usr/local/include/glib-2.0/glib/gmem.h:
-
-/usr/local/include/glib-2.0/glib/gnode.h:
-
-/usr/local/include/glib-2.0/glib/ghmac.h:
-
-/usr/local/include/glib-2.0/glib/ghook.h:
-
-/usr/local/include/glib-2.0/glib/ghostutils.h:
-
-/usr/local/include/glib-2.0/glib/giochannel.h:
-
-/usr/local/include/glib-2.0/glib/gmain.h:
-
-/usr/local/include/glib-2.0/glib/gpoll.h:
-
-/usr/local/include/glib-2.0/glib/gslist.h:
-
-/usr/local/include/glib-2.0/glib/gstring.h:
-
-/usr/local/include/glib-2.0/glib/gunicode.h:
-
-/usr/local/include/glib-2.0/glib/gkeyfile.h:
-
-/usr/local/include/glib-2.0/glib/gmappedfile.h:
-
-/usr/local/include/glib-2.0/glib/gmarkup.h:
-
-/usr/local/include/glib-2.0/glib/gmessages.h:
-
-/usr/local/include/glib-2.0/glib/goption.h:
-
-/usr/local/include/glib-2.0/glib/gpattern.h:
-
-/usr/local/include/glib-2.0/glib/gprimes.h:
-
-/usr/local/include/glib-2.0/glib/gqsort.h:
-
-/usr/local/include/glib-2.0/glib/gqueue.h:
-
-/usr/local/include/glib-2.0/glib/grand.h:
-
-/usr/local/include/glib-2.0/glib/gregex.h:
-
-/usr/local/include/glib-2.0/glib/gscanner.h:
-
-/usr/local/include/glib-2.0/glib/gsequence.h:
-
-/usr/local/include/glib-2.0/glib/gshell.h:
-
-/usr/local/include/glib-2.0/glib/gslice.h:
-
-/usr/local/include/glib-2.0/glib/gspawn.h:
-
-/usr/local/include/glib-2.0/glib/gstrfuncs.h:
-
-/usr/local/include/glib-2.0/glib/gstringchunk.h:
-
-/usr/local/include/glib-2.0/glib/gtestutils.h:
-
-/usr/local/include/glib-2.0/glib/gthreadpool.h:
-
-/usr/local/include/glib-2.0/glib/gtimer.h:
-
-/usr/local/include/glib-2.0/glib/gtrashstack.h:
-
-/usr/local/include/glib-2.0/glib/gtree.h:
-
-/usr/local/include/glib-2.0/glib/gurifuncs.h:
-
-/usr/local/include/glib-2.0/glib/gvarianttype.h:
-
-/usr/local/include/glib-2.0/glib/gvariant.h:
-
-/usr/local/include/glib-2.0/glib/gversion.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gallocator.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gcache.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gcompletion.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gmain.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/grel.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gthread.h:
-
-/usr/include/pthread.h:
-
-/usr/include/sched.h:
-
-/usr/local/include/glib-2.0/glib/glib-autocleanups.h:
-
-/usr/local/include/neon/ne_props.h:
-
-/usr/local/include/neon/ne_request.h:
-
-/usr/local/include/neon/ne_utils.h:
-
-/usr/local/include/neon/ne_defs.h:
-
-/usr/local/include/neon/ne_string.h:
-
-/usr/local/include/neon/ne_alloc.h:
-
-/usr/local/include/neon/ne_session.h:
-
-/usr/local/include/neon/ne_ssl.h:
-
-/usr/local/include/neon/ne_uri.h:
-
-/usr/local/include/neon/ne_socket.h:
-
-/usr/local/include/neon/ne_207.h:
-
-/usr/local/include/neon/ne_xml.h:
-
-wdfs-main.h:
-
-config.h:
-
-/usr/local/include/fuse/fuse.h:
-
-/usr/local/include/fuse/fuse_common.h:
-
-/usr/local/include/fuse/fuse_opt.h:
-
-/usr/include/stdint.h:
-
-/usr/include/machine/_stdint.h:
-
-/usr/include/x86/_stdint.h:
-
-/usr/local/include/fuse/fuse_common_compat.h:
-
-/usr/include/fcntl.h:
-
-/usr/include/utime.h:
-
-/usr/include/sys/stat.h:
-
-/usr/include/sys/time.h:
-
-/usr/include/sys/statvfs.h:
-
-/usr/include/sys/uio.h:
-
-/usr/include/sys/_iovec.h:
-
-/usr/local/include/fuse/fuse_compat.h:
-
-/usr/local/include/neon/ne_basic.h:
-
-webdav.h:
-
-svn.h:
diff --git a/src/.deps/wdfs-main.Po b/src/.deps/wdfs-main.Po
deleted file mode 100644
index 08dd8c7..0000000
--- a/src/.deps/wdfs-main.Po
+++ /dev/null
@@ -1,428 +0,0 @@
-wdfs-main.o: wdfs-main.c /usr/include/stdio.h /usr/include/sys/cdefs.h \
- /usr/include/sys/_null.h /usr/include/sys/_types.h \
- /usr/include/machine/_types.h /usr/include/x86/_types.h \
- /usr/include/stdlib.h /usr/include/string.h /usr/include/strings.h \
- /usr/include/xlocale/_strings.h /usr/include/xlocale/_string.h \
- /usr/include/errno.h /usr/include/fcntl.h /usr/include/assert.h \
- /usr/include/unistd.h /usr/include/sys/types.h \
- /usr/include/machine/endian.h /usr/include/x86/endian.h \
- /usr/include/sys/_pthreadtypes.h /usr/include/sys/_stdint.h \
- /usr/include/sys/select.h /usr/include/sys/_sigset.h \
- /usr/include/sys/_timeval.h /usr/include/sys/timespec.h \
- /usr/include/sys/_timespec.h /usr/include/sys/unistd.h \
- /usr/local/include/glib-2.0/glib.h \
- /usr/local/include/glib-2.0/glib/galloca.h \
- /usr/local/include/glib-2.0/glib/gtypes.h \
- /usr/local/lib/glib-2.0/include/glibconfig.h \
- /usr/local/include/glib-2.0/glib/gmacros.h /usr/include/stddef.h \
- /usr/include/limits.h /usr/include/sys/limits.h \
- /usr/include/machine/_limits.h /usr/include/x86/_limits.h \
- /usr/include/sys/syslimits.h /usr/include/float.h \
- /usr/include/x86/float.h \
- /usr/local/include/glib-2.0/glib/gversionmacros.h /usr/include/time.h \
- /usr/include/xlocale/_time.h /usr/local/include/glib-2.0/glib/garray.h \
- /usr/local/include/glib-2.0/glib/gasyncqueue.h \
- /usr/local/include/glib-2.0/glib/gthread.h \
- /usr/local/include/glib-2.0/glib/gatomic.h \
- /usr/local/include/glib-2.0/glib/gerror.h /usr/include/stdarg.h \
- /usr/include/x86/stdarg.h /usr/local/include/glib-2.0/glib/gquark.h \
- /usr/local/include/glib-2.0/glib/gutils.h \
- /usr/local/include/glib-2.0/glib/gbacktrace.h /usr/include/signal.h \
- /usr/include/sys/signal.h /usr/include/machine/signal.h \
- /usr/include/x86/signal.h /usr/include/machine/trap.h \
- /usr/include/x86/trap.h /usr/local/include/glib-2.0/glib/gbase64.h \
- /usr/local/include/glib-2.0/glib/gbitlock.h \
- /usr/local/include/glib-2.0/glib/gbookmarkfile.h \
- /usr/local/include/glib-2.0/glib/gbytes.h \
- /usr/local/include/glib-2.0/glib/gcharset.h \
- /usr/local/include/glib-2.0/glib/gchecksum.h \
- /usr/local/include/glib-2.0/glib/gconvert.h \
- /usr/local/include/glib-2.0/glib/gdataset.h \
- /usr/local/include/glib-2.0/glib/gdate.h \
- /usr/local/include/glib-2.0/glib/gdatetime.h \
- /usr/local/include/glib-2.0/glib/gtimezone.h \
- /usr/local/include/glib-2.0/glib/gdir.h /usr/include/dirent.h \
- /usr/include/sys/dirent.h /usr/local/include/glib-2.0/glib/genviron.h \
- /usr/local/include/glib-2.0/glib/gfileutils.h \
- /usr/local/include/glib-2.0/glib/ggettext.h \
- /usr/local/include/glib-2.0/glib/ghash.h \
- /usr/local/include/glib-2.0/glib/glist.h \
- /usr/local/include/glib-2.0/glib/gmem.h \
- /usr/local/include/glib-2.0/glib/gnode.h \
- /usr/local/include/glib-2.0/glib/ghmac.h \
- /usr/local/include/glib-2.0/glib/ghook.h \
- /usr/local/include/glib-2.0/glib/ghostutils.h \
- /usr/local/include/glib-2.0/glib/giochannel.h \
- /usr/local/include/glib-2.0/glib/gmain.h \
- /usr/local/include/glib-2.0/glib/gpoll.h \
- /usr/local/include/glib-2.0/glib/gslist.h \
- /usr/local/include/glib-2.0/glib/gstring.h \
- /usr/local/include/glib-2.0/glib/gunicode.h \
- /usr/local/include/glib-2.0/glib/gkeyfile.h \
- /usr/local/include/glib-2.0/glib/gmappedfile.h \
- /usr/local/include/glib-2.0/glib/gmarkup.h \
- /usr/local/include/glib-2.0/glib/gmessages.h \
- /usr/local/include/glib-2.0/glib/goption.h \
- /usr/local/include/glib-2.0/glib/gpattern.h \
- /usr/local/include/glib-2.0/glib/gprimes.h \
- /usr/local/include/glib-2.0/glib/gqsort.h \
- /usr/local/include/glib-2.0/glib/gqueue.h \
- /usr/local/include/glib-2.0/glib/grand.h \
- /usr/local/include/glib-2.0/glib/gregex.h \
- /usr/local/include/glib-2.0/glib/gscanner.h \
- /usr/local/include/glib-2.0/glib/gsequence.h \
- /usr/local/include/glib-2.0/glib/gshell.h \
- /usr/local/include/glib-2.0/glib/gslice.h \
- /usr/local/include/glib-2.0/glib/gspawn.h \
- /usr/local/include/glib-2.0/glib/gstrfuncs.h \
- /usr/local/include/glib-2.0/glib/gstringchunk.h \
- /usr/local/include/glib-2.0/glib/gtestutils.h \
- /usr/local/include/glib-2.0/glib/gthreadpool.h \
- /usr/local/include/glib-2.0/glib/gtimer.h \
- /usr/local/include/glib-2.0/glib/gtrashstack.h \
- /usr/local/include/glib-2.0/glib/gtree.h \
- /usr/local/include/glib-2.0/glib/gurifuncs.h \
- /usr/local/include/glib-2.0/glib/gvarianttype.h \
- /usr/local/include/glib-2.0/glib/gvariant.h \
- /usr/local/include/glib-2.0/glib/gversion.h \
- /usr/local/include/glib-2.0/glib/deprecated/gallocator.h \
- /usr/local/include/glib-2.0/glib/deprecated/gcache.h \
- /usr/local/include/glib-2.0/glib/deprecated/gcompletion.h \
- /usr/local/include/glib-2.0/glib/deprecated/gmain.h \
- /usr/local/include/glib-2.0/glib/deprecated/grel.h \
- /usr/local/include/glib-2.0/glib/deprecated/gthread.h \
- /usr/include/pthread.h /usr/include/sched.h \
- /usr/local/include/glib-2.0/glib/glib-autocleanups.h \
- /usr/local/include/fuse/fuse_opt.h /usr/local/include/neon/ne_props.h \
- /usr/local/include/neon/ne_request.h \
- /usr/local/include/neon/ne_utils.h /usr/local/include/neon/ne_defs.h \
- /usr/local/include/neon/ne_string.h /usr/local/include/neon/ne_alloc.h \
- /usr/local/include/neon/ne_session.h /usr/local/include/neon/ne_ssl.h \
- /usr/local/include/neon/ne_uri.h /usr/local/include/neon/ne_socket.h \
- /usr/local/include/neon/ne_207.h /usr/local/include/neon/ne_xml.h \
- /usr/local/include/neon/ne_dates.h \
- /usr/local/include/neon/ne_redirect.h wdfs-main.h config.h \
- /usr/local/include/fuse/fuse.h /usr/local/include/fuse/fuse_common.h \
- /usr/include/stdint.h /usr/include/machine/_stdint.h \
- /usr/include/x86/_stdint.h \
- /usr/local/include/fuse/fuse_common_compat.h /usr/include/utime.h \
- /usr/include/sys/stat.h /usr/include/sys/time.h \
- /usr/include/sys/statvfs.h /usr/include/sys/uio.h \
- /usr/include/sys/_iovec.h /usr/local/include/fuse/fuse_compat.h \
- /usr/local/include/neon/ne_basic.h webdav.h cache.h svn.h
-
-/usr/include/stdio.h:
-
-/usr/include/sys/cdefs.h:
-
-/usr/include/sys/_null.h:
-
-/usr/include/sys/_types.h:
-
-/usr/include/machine/_types.h:
-
-/usr/include/x86/_types.h:
-
-/usr/include/stdlib.h:
-
-/usr/include/string.h:
-
-/usr/include/strings.h:
-
-/usr/include/xlocale/_strings.h:
-
-/usr/include/xlocale/_string.h:
-
-/usr/include/errno.h:
-
-/usr/include/fcntl.h:
-
-/usr/include/assert.h:
-
-/usr/include/unistd.h:
-
-/usr/include/sys/types.h:
-
-/usr/include/machine/endian.h:
-
-/usr/include/x86/endian.h:
-
-/usr/include/sys/_pthreadtypes.h:
-
-/usr/include/sys/_stdint.h:
-
-/usr/include/sys/select.h:
-
-/usr/include/sys/_sigset.h:
-
-/usr/include/sys/_timeval.h:
-
-/usr/include/sys/timespec.h:
-
-/usr/include/sys/_timespec.h:
-
-/usr/include/sys/unistd.h:
-
-/usr/local/include/glib-2.0/glib.h:
-
-/usr/local/include/glib-2.0/glib/galloca.h:
-
-/usr/local/include/glib-2.0/glib/gtypes.h:
-
-/usr/local/lib/glib-2.0/include/glibconfig.h:
-
-/usr/local/include/glib-2.0/glib/gmacros.h:
-
-/usr/include/stddef.h:
-
-/usr/include/limits.h:
-
-/usr/include/sys/limits.h:
-
-/usr/include/machine/_limits.h:
-
-/usr/include/x86/_limits.h:
-
-/usr/include/sys/syslimits.h:
-
-/usr/include/float.h:
-
-/usr/include/x86/float.h:
-
-/usr/local/include/glib-2.0/glib/gversionmacros.h:
-
-/usr/include/time.h:
-
-/usr/include/xlocale/_time.h:
-
-/usr/local/include/glib-2.0/glib/garray.h:
-
-/usr/local/include/glib-2.0/glib/gasyncqueue.h:
-
-/usr/local/include/glib-2.0/glib/gthread.h:
-
-/usr/local/include/glib-2.0/glib/gatomic.h:
-
-/usr/local/include/glib-2.0/glib/gerror.h:
-
-/usr/include/stdarg.h:
-
-/usr/include/x86/stdarg.h:
-
-/usr/local/include/glib-2.0/glib/gquark.h:
-
-/usr/local/include/glib-2.0/glib/gutils.h:
-
-/usr/local/include/glib-2.0/glib/gbacktrace.h:
-
-/usr/include/signal.h:
-
-/usr/include/sys/signal.h:
-
-/usr/include/machine/signal.h:
-
-/usr/include/x86/signal.h:
-
-/usr/include/machine/trap.h:
-
-/usr/include/x86/trap.h:
-
-/usr/local/include/glib-2.0/glib/gbase64.h:
-
-/usr/local/include/glib-2.0/glib/gbitlock.h:
-
-/usr/local/include/glib-2.0/glib/gbookmarkfile.h:
-
-/usr/local/include/glib-2.0/glib/gbytes.h:
-
-/usr/local/include/glib-2.0/glib/gcharset.h:
-
-/usr/local/include/glib-2.0/glib/gchecksum.h:
-
-/usr/local/include/glib-2.0/glib/gconvert.h:
-
-/usr/local/include/glib-2.0/glib/gdataset.h:
-
-/usr/local/include/glib-2.0/glib/gdate.h:
-
-/usr/local/include/glib-2.0/glib/gdatetime.h:
-
-/usr/local/include/glib-2.0/glib/gtimezone.h:
-
-/usr/local/include/glib-2.0/glib/gdir.h:
-
-/usr/include/dirent.h:
-
-/usr/include/sys/dirent.h:
-
-/usr/local/include/glib-2.0/glib/genviron.h:
-
-/usr/local/include/glib-2.0/glib/gfileutils.h:
-
-/usr/local/include/glib-2.0/glib/ggettext.h:
-
-/usr/local/include/glib-2.0/glib/ghash.h:
-
-/usr/local/include/glib-2.0/glib/glist.h:
-
-/usr/local/include/glib-2.0/glib/gmem.h:
-
-/usr/local/include/glib-2.0/glib/gnode.h:
-
-/usr/local/include/glib-2.0/glib/ghmac.h:
-
-/usr/local/include/glib-2.0/glib/ghook.h:
-
-/usr/local/include/glib-2.0/glib/ghostutils.h:
-
-/usr/local/include/glib-2.0/glib/giochannel.h:
-
-/usr/local/include/glib-2.0/glib/gmain.h:
-
-/usr/local/include/glib-2.0/glib/gpoll.h:
-
-/usr/local/include/glib-2.0/glib/gslist.h:
-
-/usr/local/include/glib-2.0/glib/gstring.h:
-
-/usr/local/include/glib-2.0/glib/gunicode.h:
-
-/usr/local/include/glib-2.0/glib/gkeyfile.h:
-
-/usr/local/include/glib-2.0/glib/gmappedfile.h:
-
-/usr/local/include/glib-2.0/glib/gmarkup.h:
-
-/usr/local/include/glib-2.0/glib/gmessages.h:
-
-/usr/local/include/glib-2.0/glib/goption.h:
-
-/usr/local/include/glib-2.0/glib/gpattern.h:
-
-/usr/local/include/glib-2.0/glib/gprimes.h:
-
-/usr/local/include/glib-2.0/glib/gqsort.h:
-
-/usr/local/include/glib-2.0/glib/gqueue.h:
-
-/usr/local/include/glib-2.0/glib/grand.h:
-
-/usr/local/include/glib-2.0/glib/gregex.h:
-
-/usr/local/include/glib-2.0/glib/gscanner.h:
-
-/usr/local/include/glib-2.0/glib/gsequence.h:
-
-/usr/local/include/glib-2.0/glib/gshell.h:
-
-/usr/local/include/glib-2.0/glib/gslice.h:
-
-/usr/local/include/glib-2.0/glib/gspawn.h:
-
-/usr/local/include/glib-2.0/glib/gstrfuncs.h:
-
-/usr/local/include/glib-2.0/glib/gstringchunk.h:
-
-/usr/local/include/glib-2.0/glib/gtestutils.h:
-
-/usr/local/include/glib-2.0/glib/gthreadpool.h:
-
-/usr/local/include/glib-2.0/glib/gtimer.h:
-
-/usr/local/include/glib-2.0/glib/gtrashstack.h:
-
-/usr/local/include/glib-2.0/glib/gtree.h:
-
-/usr/local/include/glib-2.0/glib/gurifuncs.h:
-
-/usr/local/include/glib-2.0/glib/gvarianttype.h:
-
-/usr/local/include/glib-2.0/glib/gvariant.h:
-
-/usr/local/include/glib-2.0/glib/gversion.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gallocator.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gcache.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gcompletion.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gmain.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/grel.h:
-
-/usr/local/include/glib-2.0/glib/deprecated/gthread.h:
-
-/usr/include/pthread.h:
-
-/usr/include/sched.h:
-
-/usr/local/include/glib-2.0/glib/glib-autocleanups.h:
-
-/usr/local/include/fuse/fuse_opt.h:
-
-/usr/local/include/neon/ne_props.h:
-
-/usr/local/include/neon/ne_request.h:
-
-/usr/local/include/neon/ne_utils.h:
-
-/usr/local/include/neon/ne_defs.h:
-
-/usr/local/include/neon/ne_string.h:
-
-/usr/local/include/neon/ne_alloc.h:
-
-/usr/local/include/neon/ne_session.h:
-
-/usr/local/include/neon/ne_ssl.h:
-
-/usr/local/include/neon/ne_uri.h:
-
-/usr/local/include/neon/ne_socket.h:
-
-/usr/local/include/neon/ne_207.h:
-
-/usr/local/include/neon/ne_xml.h:
-
-/usr/local/include/neon/ne_dates.h:
-
-/usr/local/include/neon/ne_redirect.h:
-
-wdfs-main.h:
-
-config.h:
-
-/usr/local/include/fuse/fuse.h:
-
-/usr/local/include/fuse/fuse_common.h:
-
-/usr/include/stdint.h:
-
-/usr/include/machine/_stdint.h:
-
-/usr/include/x86/_stdint.h:
-
-/usr/local/include/fuse/fuse_common_compat.h:
-
-/usr/include/utime.h:
-
-/usr/include/sys/stat.h:
-
-/usr/include/sys/time.h:
-
-/usr/include/sys/statvfs.h:
-
-/usr/include/sys/uio.h:
-
-/usr/include/sys/_iovec.h:
-
-/usr/local/include/fuse/fuse_compat.h:
-
-/usr/local/include/neon/ne_basic.h:
-
-webdav.h:
-
-cache.h:
-
-svn.h:
diff --git a/src/.deps/webdav.Po b/src/.deps/webdav.Po
deleted file mode 100644
index 4734e67..0000000
--- a/src/.deps/webdav.Po
+++ /dev/null
@@ -1,160 +0,0 @@
-webdav.o: webdav.c /usr/include/stdio.h /usr/include/sys/cdefs.h \
- /usr/include/sys/_null.h /usr/include/sys/_types.h \
- /usr/include/machine/_types.h /usr/include/x86/_types.h \
- /usr/include/string.h /usr/include/strings.h \
- /usr/include/xlocale/_strings.h /usr/include/xlocale/_string.h \
- /usr/include/stdlib.h /usr/include/unistd.h /usr/include/sys/types.h \
- /usr/include/machine/endian.h /usr/include/x86/endian.h \
- /usr/include/sys/_pthreadtypes.h /usr/include/sys/_stdint.h \
- /usr/include/sys/select.h /usr/include/sys/_sigset.h \
- /usr/include/sys/_timeval.h /usr/include/sys/timespec.h \
- /usr/include/sys/_timespec.h /usr/include/sys/unistd.h \
- /usr/include/assert.h /usr/include/termios.h \
- /usr/include/sys/_termios.h /usr/include/sys/ttycom.h \
- /usr/include/sys/ioccom.h /usr/include/sys/ttydefaults.h \
- /usr/local/include/neon/ne_basic.h \
- /usr/local/include/neon/ne_request.h \
- /usr/local/include/neon/ne_utils.h /usr/include/stdarg.h \
- /usr/include/x86/stdarg.h /usr/local/include/neon/ne_defs.h \
- /usr/local/include/neon/ne_string.h /usr/local/include/neon/ne_alloc.h \
- /usr/local/include/neon/ne_session.h /usr/local/include/neon/ne_ssl.h \
- /usr/local/include/neon/ne_uri.h /usr/local/include/neon/ne_socket.h \
- /usr/local/include/neon/ne_auth.h /usr/local/include/neon/ne_locks.h \
- /usr/local/include/neon/ne_redirect.h wdfs-main.h config.h \
- /usr/local/include/fuse/fuse.h /usr/local/include/fuse/fuse_common.h \
- /usr/local/include/fuse/fuse_opt.h /usr/include/stdint.h \
- /usr/include/machine/_stdint.h /usr/include/x86/_stdint.h \
- /usr/local/include/fuse/fuse_common_compat.h /usr/include/fcntl.h \
- /usr/include/time.h /usr/include/xlocale/_time.h /usr/include/utime.h \
- /usr/include/sys/stat.h /usr/include/sys/time.h \
- /usr/include/sys/statvfs.h /usr/include/sys/uio.h \
- /usr/include/sys/_iovec.h /usr/local/include/fuse/fuse_compat.h \
- webdav.h
-
-/usr/include/stdio.h:
-
-/usr/include/sys/cdefs.h:
-
-/usr/include/sys/_null.h:
-
-/usr/include/sys/_types.h:
-
-/usr/include/machine/_types.h:
-
-/usr/include/x86/_types.h:
-
-/usr/include/string.h:
-
-/usr/include/strings.h:
-
-/usr/include/xlocale/_strings.h:
-
-/usr/include/xlocale/_string.h:
-
-/usr/include/stdlib.h:
-
-/usr/include/unistd.h:
-
-/usr/include/sys/types.h:
-
-/usr/include/machine/endian.h:
-
-/usr/include/x86/endian.h:
-
-/usr/include/sys/_pthreadtypes.h:
-
-/usr/include/sys/_stdint.h:
-
-/usr/include/sys/select.h:
-
-/usr/include/sys/_sigset.h:
-
-/usr/include/sys/_timeval.h:
-
-/usr/include/sys/timespec.h:
-
-/usr/include/sys/_timespec.h:
-
-/usr/include/sys/unistd.h:
-
-/usr/include/assert.h:
-
-/usr/include/termios.h:
-
-/usr/include/sys/_termios.h:
-
-/usr/include/sys/ttycom.h:
-
-/usr/include/sys/ioccom.h:
-
-/usr/include/sys/ttydefaults.h:
-
-/usr/local/include/neon/ne_basic.h:
-
-/usr/local/include/neon/ne_request.h:
-
-/usr/local/include/neon/ne_utils.h:
-
-/usr/include/stdarg.h:
-
-/usr/include/x86/stdarg.h:
-
-/usr/local/include/neon/ne_defs.h:
-
-/usr/local/include/neon/ne_string.h:
-
-/usr/local/include/neon/ne_alloc.h:
-
-/usr/local/include/neon/ne_session.h:
-
-/usr/local/include/neon/ne_ssl.h:
-
-/usr/local/include/neon/ne_uri.h:
-
-/usr/local/include/neon/ne_socket.h:
-
-/usr/local/include/neon/ne_auth.h:
-
-/usr/local/include/neon/ne_locks.h:
-
-/usr/local/include/neon/ne_redirect.h:
-
-wdfs-main.h:
-
-config.h:
-
-/usr/local/include/fuse/fuse.h:
-
-/usr/local/include/fuse/fuse_common.h:
-
-/usr/local/include/fuse/fuse_opt.h:
-
-/usr/include/stdint.h:
-
-/usr/include/machine/_stdint.h:
-
-/usr/include/x86/_stdint.h:
-
-/usr/local/include/fuse/fuse_common_compat.h:
-
-/usr/include/fcntl.h:
-
-/usr/include/time.h:
-
-/usr/include/xlocale/_time.h:
-
-/usr/include/utime.h:
-
-/usr/include/sys/stat.h:
-
-/usr/include/sys/time.h:
-
-/usr/include/sys/statvfs.h:
-
-/usr/include/sys/uio.h:
-
-/usr/include/sys/_iovec.h:
-
-/usr/local/include/fuse/fuse_compat.h:
-
-webdav.h:
diff --git a/src/config.h b/src/config.h
deleted file mode 100644
index bf10206..0000000
--- a/src/config.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/* src/config.h. Generated from config.h.in by configure. */
-/* src/config.h.in. Generated from configure.ac by autoheader. */
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <pthread.h> header file. */
-#define HAVE_PTHREAD_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strndup' function. */
-#define HAVE_STRNDUP 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Name of package */
-#define PACKAGE "wdfs"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "[email protected]"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "wdfs"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "wdfs 1.4.2"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "wdfs"
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "1.4.2"
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Version number of package */
-#define VERSION "1.4.2"
diff --git a/src/stamp-h1 b/src/stamp-h1
deleted file mode 100644
index 57ea58e..0000000
--- a/src/stamp-h1
+++ /dev/null
@@ -1 +0,0 @@
-timestamp for src/config.h
|
codyps/wdfs
|
21fbb1d5b559fccfdcb6933a40783e33c1a1cffe
|
implement fuse.create()
|
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..7992ffd
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,562 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# Makefile. Generated from Makefile.in by configure.
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+
+srcdir = .
+top_srcdir = .
+
+pkgdatadir = $(datadir)/wdfs
+pkglibdir = $(libdir)/wdfs
+pkgincludedir = $(includedir)/wdfs
+top_builddir = .
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = /usr/bin/install -c
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+subdir = .
+DIST_COMMON = README $(am__configure_deps) $(srcdir)/Makefile.am \
+ $(srcdir)/Makefile.in $(top_srcdir)/configure AUTHORS COPYING \
+ ChangeLog INSTALL NEWS TODO depcomp install-sh missing
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \
+ configure.lineno configure.status.lineno
+mkinstalldirs = $(install_sh) -d
+CONFIG_HEADER = $(top_builddir)/src/config.h
+CONFIG_CLEAN_FILES =
+SOURCES =
+DIST_SOURCES =
+RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
+ html-recursive info-recursive install-data-recursive \
+ install-exec-recursive install-info-recursive \
+ install-recursive installcheck-recursive installdirs-recursive \
+ pdf-recursive ps-recursive uninstall-info-recursive \
+ uninstall-recursive
+ETAGS = etags
+CTAGS = ctags
+DIST_SUBDIRS = $(SUBDIRS)
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+distdir = $(PACKAGE)-$(VERSION)
+top_distdir = $(distdir)
+am__remove_distdir = \
+ { test ! -d $(distdir) \
+ || { find $(distdir) -type d ! -perm -200 -exec chmod u+w {} ';' \
+ && rm -fr $(distdir); }; }
+DIST_ARCHIVES = $(distdir).tar.gz
+GZIP_ENV = --best
+distuninstallcheck_listfiles = find . -type f -print
+distcleancheck_listfiles = find . -type f -print
+ACLOCAL = ${SHELL} /xj/waitman/wdfs/missing --run aclocal-1.9
+AMDEP_FALSE = #
+AMDEP_TRUE =
+AMTAR = ${SHELL} /xj/waitman/wdfs/missing --run tar
+AUTOCONF = ${SHELL} /xj/waitman/wdfs/missing --run autoconf
+AUTOHEADER = ${SHELL} /xj/waitman/wdfs/missing --run autoheader
+AUTOMAKE = ${SHELL} /xj/waitman/wdfs/missing --run automake-1.9
+AWK = nawk
+CC = cc
+CCDEPMODE = depmode=gcc3
+CFLAGS = -g -O2 -I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include -Wall -D_GNU_SOURCE -D_REENTRANT
+CPP = cc -E
+CPPFLAGS =
+CYGPATH_W = echo
+DEFS = -DHAVE_CONFIG_H
+DEPDIR = .deps
+ECHO_C =
+ECHO_N = -n
+ECHO_T =
+EGREP = /usr/bin/grep -E
+EXEEXT =
+GREP = /usr/bin/grep
+INSTALL_DATA = ${INSTALL} -m 644
+INSTALL_PROGRAM = ${INSTALL}
+INSTALL_SCRIPT = ${INSTALL}
+INSTALL_STRIP_PROGRAM = ${SHELL} $(install_sh) -c -s
+LDFLAGS =
+LIBOBJS =
+LIBS = -L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl
+LTLIBOBJS =
+MAKEINFO = ${SHELL} /xj/waitman/wdfs/missing --run makeinfo
+OBJEXT = o
+PACKAGE = wdfs
+PACKAGE_BUGREPORT = [email protected]
+PACKAGE_NAME = wdfs
+PACKAGE_STRING = wdfs 1.4.2
+PACKAGE_TARNAME = wdfs
+PACKAGE_VERSION = 1.4.2
+PATH_SEPARATOR = :
+PKG_CONFIG = /usr/local/bin/pkg-config
+SET_MAKE =
+SHELL = /bin/sh
+STRIP =
+VERSION = 1.4.2
+WDFS_CFLAGS = -I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include
+WDFS_LIBS = -L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl
+ac_ct_CC =
+am__fastdepCC_FALSE = #
+am__fastdepCC_TRUE =
+am__include = include
+am__leading_dot = .
+am__quote =
+am__tar = ${AMTAR} chof - "$$tardir"
+am__untar = ${AMTAR} xf -
+bindir = ${exec_prefix}/bin
+build_alias =
+datadir = ${datarootdir}
+datarootdir = ${prefix}/share
+docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
+dvidir = ${docdir}
+exec_prefix = ${prefix}
+host_alias =
+htmldir = ${docdir}
+includedir = ${prefix}/include
+infodir = ${datarootdir}/info
+install_sh = /xj/waitman/wdfs/install-sh
+libdir = ${exec_prefix}/lib
+libexecdir = ${exec_prefix}/libexec
+localedir = ${datarootdir}/locale
+localstatedir = ${prefix}/var
+mandir = ${datarootdir}/man
+mkdir_p = $(install_sh) -d
+oldincludedir = /usr/include
+pdfdir = ${docdir}
+prefix = /usr/local
+program_transform_name = s,x,x,
+psdir = ${docdir}
+sbindir = ${exec_prefix}/sbin
+sharedstatedir = ${prefix}/com
+sysconfdir = ${prefix}/etc
+target_alias =
+SUBDIRS = src
+all: all-recursive
+
+.SUFFIXES:
+am--refresh:
+ @:
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ echo ' cd $(srcdir) && $(AUTOMAKE) --gnu '; \
+ cd $(srcdir) && $(AUTOMAKE) --gnu \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --gnu Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ echo ' $(SHELL) ./config.status'; \
+ $(SHELL) ./config.status;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ $(SHELL) ./config.status --recheck
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(srcdir) && $(AUTOCONF)
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS)
+uninstall-info-am:
+
+# This directory's subdirectories are mostly independent; you can cd
+# into them and run `make' without going through this Makefile.
+# To change the values of `make' variables: instead of editing Makefiles,
+# (1) if the variable is set in `config.status', edit `config.status'
+# (which will cause the Makefiles to be regenerated when you run `make');
+# (2) otherwise, pass the desired values on the `make' command line.
+$(RECURSIVE_TARGETS):
+ @failcom='exit 1'; \
+ for f in x $$MAKEFLAGS; do \
+ case $$f in \
+ *=* | --[!k]*);; \
+ *k*) failcom='fail=yes';; \
+ esac; \
+ done; \
+ dot_seen=no; \
+ target=`echo $@ | sed s/-recursive//`; \
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ echo "Making $$target in $$subdir"; \
+ if test "$$subdir" = "."; then \
+ dot_seen=yes; \
+ local_target="$$target-am"; \
+ else \
+ local_target="$$target"; \
+ fi; \
+ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+ || eval $$failcom; \
+ done; \
+ if test "$$dot_seen" = "no"; then \
+ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
+ fi; test -z "$$fail"
+
+mostlyclean-recursive clean-recursive distclean-recursive \
+maintainer-clean-recursive:
+ @failcom='exit 1'; \
+ for f in x $$MAKEFLAGS; do \
+ case $$f in \
+ *=* | --[!k]*);; \
+ *k*) failcom='fail=yes';; \
+ esac; \
+ done; \
+ dot_seen=no; \
+ case "$@" in \
+ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
+ *) list='$(SUBDIRS)' ;; \
+ esac; \
+ rev=''; for subdir in $$list; do \
+ if test "$$subdir" = "."; then :; else \
+ rev="$$subdir $$rev"; \
+ fi; \
+ done; \
+ rev="$$rev ."; \
+ target=`echo $@ | sed s/-recursive//`; \
+ for subdir in $$rev; do \
+ echo "Making $$target in $$subdir"; \
+ if test "$$subdir" = "."; then \
+ local_target="$$target-am"; \
+ else \
+ local_target="$$target"; \
+ fi; \
+ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+ || eval $$failcom; \
+ done && test -z "$$fail"
+tags-recursive:
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \
+ done
+ctags-recursive:
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \
+ done
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
+ include_option=--etags-include; \
+ empty_fix=.; \
+ else \
+ include_option=--include; \
+ empty_fix=; \
+ fi; \
+ list='$(SUBDIRS)'; for subdir in $$list; do \
+ if test "$$subdir" = .; then :; else \
+ test ! -f $$subdir/TAGS || \
+ tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \
+ fi; \
+ done; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ $(am__remove_distdir)
+ mkdir $(distdir)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+ list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
+ if test "$$subdir" = .; then :; else \
+ test -d "$(distdir)/$$subdir" \
+ || $(mkdir_p) "$(distdir)/$$subdir" \
+ || exit 1; \
+ distdir=`$(am__cd) $(distdir) && pwd`; \
+ top_distdir=`$(am__cd) $(top_distdir) && pwd`; \
+ (cd $$subdir && \
+ $(MAKE) $(AM_MAKEFLAGS) \
+ top_distdir="$$top_distdir" \
+ distdir="$$distdir/$$subdir" \
+ distdir) \
+ || exit 1; \
+ fi; \
+ done
+ -find $(distdir) -type d ! -perm -777 -exec chmod a+rwx {} \; -o \
+ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \
+ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \
+ ! -type d ! -perm -444 -exec $(SHELL) $(install_sh) -c -m a+r {} {} \; \
+ || chmod -R a+r $(distdir)
+dist-gzip: distdir
+ tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
+ $(am__remove_distdir)
+
+dist-bzip2: distdir
+ tardir=$(distdir) && $(am__tar) | bzip2 -9 -c >$(distdir).tar.bz2
+ $(am__remove_distdir)
+
+dist-tarZ: distdir
+ tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z
+ $(am__remove_distdir)
+
+dist-shar: distdir
+ shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz
+ $(am__remove_distdir)
+
+dist-zip: distdir
+ -rm -f $(distdir).zip
+ zip -rq $(distdir).zip $(distdir)
+ $(am__remove_distdir)
+
+dist dist-all: distdir
+ tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
+ $(am__remove_distdir)
+
+# This target untars the dist file and tries a VPATH configuration. Then
+# it guarantees that the distribution is self-contained by making another
+# tarfile.
+distcheck: dist
+ case '$(DIST_ARCHIVES)' in \
+ *.tar.gz*) \
+ GZIP=$(GZIP_ENV) gunzip -c $(distdir).tar.gz | $(am__untar) ;;\
+ *.tar.bz2*) \
+ bunzip2 -c $(distdir).tar.bz2 | $(am__untar) ;;\
+ *.tar.Z*) \
+ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\
+ *.shar.gz*) \
+ GZIP=$(GZIP_ENV) gunzip -c $(distdir).shar.gz | unshar ;;\
+ *.zip*) \
+ unzip $(distdir).zip ;;\
+ esac
+ chmod -R a-w $(distdir); chmod a+w $(distdir)
+ mkdir $(distdir)/_build
+ mkdir $(distdir)/_inst
+ chmod a-w $(distdir)
+ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \
+ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \
+ && cd $(distdir)/_build \
+ && ../configure --srcdir=.. --prefix="$$dc_install_base" \
+ $(DISTCHECK_CONFIGURE_FLAGS) \
+ && $(MAKE) $(AM_MAKEFLAGS) \
+ && $(MAKE) $(AM_MAKEFLAGS) dvi \
+ && $(MAKE) $(AM_MAKEFLAGS) check \
+ && $(MAKE) $(AM_MAKEFLAGS) install \
+ && $(MAKE) $(AM_MAKEFLAGS) installcheck \
+ && $(MAKE) $(AM_MAKEFLAGS) uninstall \
+ && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \
+ distuninstallcheck \
+ && chmod -R a-w "$$dc_install_base" \
+ && ({ \
+ (cd ../.. && umask 077 && mkdir "$$dc_destdir") \
+ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \
+ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \
+ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \
+ distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \
+ } || { rm -rf "$$dc_destdir"; exit 1; }) \
+ && rm -rf "$$dc_destdir" \
+ && $(MAKE) $(AM_MAKEFLAGS) dist \
+ && rm -rf $(DIST_ARCHIVES) \
+ && $(MAKE) $(AM_MAKEFLAGS) distcleancheck
+ $(am__remove_distdir)
+ @(echo "$(distdir) archives ready for distribution: "; \
+ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \
+ sed -e '1{h;s/./=/g;p;x;}' -e '$${p;x;}'
+distuninstallcheck:
+ @cd $(distuninstallcheck_dir) \
+ && test `$(distuninstallcheck_listfiles) | wc -l` -le 1 \
+ || { echo "ERROR: files left after uninstall:" ; \
+ if test -n "$(DESTDIR)"; then \
+ echo " (check DESTDIR support)"; \
+ fi ; \
+ $(distuninstallcheck_listfiles) ; \
+ exit 1; } >&2
+distcleancheck: distclean
+ @if test '$(srcdir)' = . ; then \
+ echo "ERROR: distcleancheck can only run from a VPATH build" ; \
+ exit 1 ; \
+ fi
+ @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \
+ || { echo "ERROR: files left in build directory after distclean:" ; \
+ $(distcleancheck_listfiles) ; \
+ exit 1; } >&2
+check-am: all-am
+check: check-recursive
+all-am: Makefile
+installdirs: installdirs-recursive
+installdirs-am:
+install: install-recursive
+install-exec: install-exec-recursive
+install-data: install-data-recursive
+uninstall: uninstall-recursive
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-recursive
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-recursive
+
+clean-am: clean-generic mostlyclean-am
+
+distclean: distclean-recursive
+ -rm -f $(am__CONFIG_DISTCLEAN_FILES)
+ -rm -f Makefile
+distclean-am: clean-am distclean-generic distclean-tags
+
+dvi: dvi-recursive
+
+dvi-am:
+
+html: html-recursive
+
+info: info-recursive
+
+info-am:
+
+install-data-am:
+
+install-exec-am:
+
+install-info: install-info-recursive
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-recursive
+ -rm -f $(am__CONFIG_DISTCLEAN_FILES)
+ -rm -rf $(top_srcdir)/autom4te.cache
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-recursive
+
+mostlyclean-am: mostlyclean-generic
+
+pdf: pdf-recursive
+
+pdf-am:
+
+ps: ps-recursive
+
+ps-am:
+
+uninstall-am: uninstall-info-am
+
+uninstall-info: uninstall-info-recursive
+
+.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am am--refresh check \
+ check-am clean clean-generic clean-recursive ctags \
+ ctags-recursive dist dist-all dist-bzip2 dist-gzip dist-shar \
+ dist-tarZ dist-zip distcheck distclean distclean-generic \
+ distclean-recursive distclean-tags distcleancheck distdir \
+ distuninstallcheck dvi dvi-am html html-am info info-am \
+ install install-am install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-strip installcheck installcheck-am installdirs \
+ installdirs-am maintainer-clean maintainer-clean-generic \
+ maintainer-clean-recursive mostlyclean mostlyclean-generic \
+ mostlyclean-recursive pdf pdf-am ps ps-am tags tags-recursive \
+ uninstall uninstall-am uninstall-info-am
+
+
+# eof
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/config.log b/config.log
new file mode 100644
index 0000000..886eae9
--- /dev/null
+++ b/config.log
@@ -0,0 +1,440 @@
+This file contains any messages produced by compilers while
+running configure, to aid debugging if configure makes a mistake.
+
+It was created by wdfs configure 1.4.2, which was
+generated by GNU Autoconf 2.61. Invocation command line was
+
+ $ ./configure
+
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = afia.waitman.net
+uname -m = amd64
+uname -r = 11.0-CURRENT
+uname -s = FreeBSD
+uname -v = FreeBSD 11.0-CURRENT #0 r290480M: Fri Nov 6 20:43:01 PST 2015 [email protected]:/usr/obj/usr/src/sys/AFIA
+
+/usr/bin/uname -p = amd64
+/bin/uname -X = unknown
+
+/bin/arch = unknown
+/usr/bin/arch -k = unknown
+/usr/convex/getsysinfo = unknown
+/usr/bin/hostinfo = unknown
+/bin/machine = unknown
+/usr/bin/oslevel = unknown
+/bin/universe = unknown
+
+PATH: /sbin
+PATH: /bin
+PATH: /usr/sbin
+PATH: /usr/bin
+PATH: /usr/local/sbin
+PATH: /usr/local/bin
+PATH: /root/bin
+
+
+## ----------- ##
+## Core tests. ##
+## ----------- ##
+
+configure:1779: checking for a BSD-compatible install
+configure:1835: result: /usr/bin/install -c
+configure:1846: checking whether build environment is sane
+configure:1889: result: yes
+configure:1954: checking for gawk
+configure:1984: result: no
+configure:1954: checking for mawk
+configure:1984: result: no
+configure:1954: checking for nawk
+configure:1970: found /usr/bin/nawk
+configure:1981: result: nawk
+configure:1992: checking whether make sets $(MAKE)
+configure:2013: result: yes
+configure:2212: checking for style of include used by make
+configure:2240: result: GNU
+configure:2313: checking for gcc
+configure:2343: result: no
+configure:2410: checking for cc
+configure:2431: found /usr/bin/cc
+configure:2454: result: cc
+configure:2578: checking for C compiler version
+configure:2585: cc --version >&5
+FreeBSD clang version 3.7.0 (tags/RELEASE_370/final 246257) 20150906
+Target: x86_64-unknown-freebsd11.0
+Thread model: posix
+configure:2588: $? = 0
+configure:2595: cc -v >&5
+FreeBSD clang version 3.7.0 (tags/RELEASE_370/final 246257) 20150906
+Target: x86_64-unknown-freebsd11.0
+Thread model: posix
+configure:2598: $? = 0
+configure:2605: cc -V >&5
+cc: error: argument to '-V' is missing (expected 1 value)
+cc: error: no input files
+configure:2608: $? = 1
+configure:2631: checking for C compiler default output file name
+configure:2658: cc conftest.c >&5
+configure:2661: $? = 0
+configure:2699: result: a.out
+configure:2716: checking whether the C compiler works
+configure:2726: ./a.out
+configure:2729: $? = 0
+configure:2746: result: yes
+configure:2753: checking whether we are cross compiling
+configure:2755: result: no
+configure:2758: checking for suffix of executables
+configure:2765: cc -o conftest conftest.c >&5
+configure:2768: $? = 0
+configure:2792: result:
+configure:2798: checking for suffix of object files
+configure:2824: cc -c conftest.c >&5
+configure:2827: $? = 0
+configure:2850: result: o
+configure:2854: checking whether we are using the GNU C compiler
+configure:2883: cc -c conftest.c >&5
+configure:2889: $? = 0
+configure:2906: result: yes
+configure:2911: checking whether cc accepts -g
+configure:2941: cc -c -g conftest.c >&5
+configure:2947: $? = 0
+configure:3046: result: yes
+configure:3063: checking for cc option to accept ISO C89
+configure:3137: cc -c -g -O2 conftest.c >&5
+configure:3143: $? = 0
+configure:3166: result: none needed
+configure:3186: checking dependency style of cc
+configure:3276: result: gcc3
+configure:3299: checking how to run the C preprocessor
+configure:3339: cc -E conftest.c
+configure:3345: $? = 0
+configure:3376: cc -E conftest.c
+conftest.c:10:10: fatal error: 'ac_nonexistent.h' file not found
+#include <ac_nonexistent.h>
+ ^
+1 error generated.
+configure:3382: $? = 1
+configure: failed program was:
+| /* confdefs.h. */
+| #define PACKAGE_NAME "wdfs"
+| #define PACKAGE_TARNAME "wdfs"
+| #define PACKAGE_VERSION "1.4.2"
+| #define PACKAGE_STRING "wdfs 1.4.2"
+| #define PACKAGE_BUGREPORT "[email protected]"
+| #define PACKAGE "wdfs"
+| #define VERSION "1.4.2"
+| /* end confdefs.h. */
+| #include <ac_nonexistent.h>
+configure:3415: result: cc -E
+configure:3444: cc -E conftest.c
+configure:3450: $? = 0
+configure:3481: cc -E conftest.c
+conftest.c:10:10: fatal error: 'ac_nonexistent.h' file not found
+#include <ac_nonexistent.h>
+ ^
+1 error generated.
+configure:3487: $? = 1
+configure: failed program was:
+| /* confdefs.h. */
+| #define PACKAGE_NAME "wdfs"
+| #define PACKAGE_TARNAME "wdfs"
+| #define PACKAGE_VERSION "1.4.2"
+| #define PACKAGE_STRING "wdfs 1.4.2"
+| #define PACKAGE_BUGREPORT "[email protected]"
+| #define PACKAGE "wdfs"
+| #define VERSION "1.4.2"
+| /* end confdefs.h. */
+| #include <ac_nonexistent.h>
+configure:3525: checking for grep that handles long lines and -e
+configure:3599: result: /usr/bin/grep
+configure:3604: checking for egrep
+configure:3682: result: /usr/bin/grep -E
+configure:3687: checking for ANSI C header files
+configure:3717: cc -c -g -O2 conftest.c >&5
+configure:3723: $? = 0
+configure:3822: cc -o conftest -g -O2 conftest.c >&5
+configure:3825: $? = 0
+configure:3831: ./conftest
+configure:3834: $? = 0
+configure:3851: result: yes
+configure:3875: checking for sys/types.h
+configure:3896: cc -c -g -O2 conftest.c >&5
+configure:3902: $? = 0
+configure:3918: result: yes
+configure:3875: checking for sys/stat.h
+configure:3896: cc -c -g -O2 conftest.c >&5
+configure:3902: $? = 0
+configure:3918: result: yes
+configure:3875: checking for stdlib.h
+configure:3896: cc -c -g -O2 conftest.c >&5
+configure:3902: $? = 0
+configure:3918: result: yes
+configure:3875: checking for string.h
+configure:3896: cc -c -g -O2 conftest.c >&5
+configure:3902: $? = 0
+configure:3918: result: yes
+configure:3875: checking for memory.h
+configure:3896: cc -c -g -O2 conftest.c >&5
+configure:3902: $? = 0
+configure:3918: result: yes
+configure:3875: checking for strings.h
+configure:3896: cc -c -g -O2 conftest.c >&5
+configure:3902: $? = 0
+configure:3918: result: yes
+configure:3875: checking for inttypes.h
+configure:3896: cc -c -g -O2 conftest.c >&5
+configure:3902: $? = 0
+configure:3918: result: yes
+configure:3875: checking for stdint.h
+configure:3896: cc -c -g -O2 conftest.c >&5
+configure:3902: $? = 0
+configure:3918: result: yes
+configure:3875: checking for unistd.h
+configure:3896: cc -c -g -O2 conftest.c >&5
+configure:3902: $? = 0
+configure:3918: result: yes
+configure:3945: checking pthread.h usability
+configure:3962: cc -c -g -O2 conftest.c >&5
+configure:3968: $? = 0
+configure:3982: result: yes
+configure:3986: checking pthread.h presence
+configure:4001: cc -E conftest.c
+configure:4007: $? = 0
+configure:4021: result: yes
+configure:4054: checking for pthread.h
+configure:4062: result: yes
+configure:4080: checking for strndup
+configure:4136: cc -o conftest -g -O2 conftest.c >&5
+conftest.c:44:6: warning: incompatible redeclaration of library function 'strndup' [-Wincompatible-library-redeclaration]
+char strndup ();
+ ^
+conftest.c:44:6: note: 'strndup' is a builtin with type 'char *(const char *, unsigned long)'
+1 warning generated.
+configure:4142: $? = 0
+configure:4160: result: yes
+configure:4484: checking for C compiler version
+configure:4491: cc --version >&5
+FreeBSD clang version 3.7.0 (tags/RELEASE_370/final 246257) 20150906
+Target: x86_64-unknown-freebsd11.0
+Thread model: posix
+configure:4494: $? = 0
+configure:4501: cc -v >&5
+FreeBSD clang version 3.7.0 (tags/RELEASE_370/final 246257) 20150906
+Target: x86_64-unknown-freebsd11.0
+Thread model: posix
+configure:4504: $? = 0
+configure:4511: cc -V >&5
+cc: error: argument to '-V' is missing (expected 1 value)
+cc: error: no input files
+configure:4514: $? = 1
+configure:4517: checking whether we are using the GNU C compiler
+configure:4569: result: yes
+configure:4574: checking whether cc accepts -g
+configure:4709: result: yes
+configure:4726: checking for cc option to accept ISO C89
+configure:4829: result: none needed
+configure:4849: checking dependency style of cc
+configure:4939: result: gcc3
+configure:5006: checking for pkg-config
+configure:5024: found /usr/local/bin/pkg-config
+configure:5036: result: /usr/local/bin/pkg-config
+configure:5065: checking pkg-config is at least version 0.9.0
+configure:5068: result: yes
+configure:5079: checking for WDFS
+configure:5087: $PKG_CONFIG --exists --print-errors "fuse >= 2.5.0 neon >= 0.24.7 glib-2.0"
+configure:5090: $? = 0
+configure:5105: $PKG_CONFIG --exists --print-errors "fuse >= 2.5.0 neon >= 0.24.7 glib-2.0"
+configure:5108: $? = 0
+configure:5184: result: yes
+configure:5315: creating ./config.status
+
+## ---------------------- ##
+## Running config.status. ##
+## ---------------------- ##
+
+This file was extended by wdfs config.status 1.4.2, which was
+generated by GNU Autoconf 2.61. Invocation command line was
+
+ CONFIG_FILES =
+ CONFIG_HEADERS =
+ CONFIG_LINKS =
+ CONFIG_COMMANDS =
+ $ ./config.status
+
+on afia.waitman.net
+
+config.status:637: creating Makefile
+config.status:637: creating src/Makefile
+config.status:637: creating src/config.h
+config.status:905: executing depfiles commands
+
+## ---------------- ##
+## Cache variables. ##
+## ---------------- ##
+
+ac_cv_c_compiler_gnu=yes
+ac_cv_env_CC_set=''
+ac_cv_env_CC_value=''
+ac_cv_env_CFLAGS_set=''
+ac_cv_env_CFLAGS_value=''
+ac_cv_env_CPPFLAGS_set=''
+ac_cv_env_CPPFLAGS_value=''
+ac_cv_env_CPP_set=''
+ac_cv_env_CPP_value=''
+ac_cv_env_LDFLAGS_set=''
+ac_cv_env_LDFLAGS_value=''
+ac_cv_env_LIBS_set=''
+ac_cv_env_LIBS_value=''
+ac_cv_env_PKG_CONFIG_set=''
+ac_cv_env_PKG_CONFIG_value=''
+ac_cv_env_WDFS_CFLAGS_set=''
+ac_cv_env_WDFS_CFLAGS_value=''
+ac_cv_env_WDFS_LIBS_set=''
+ac_cv_env_WDFS_LIBS_value=''
+ac_cv_env_build_alias_set=''
+ac_cv_env_build_alias_value=''
+ac_cv_env_host_alias_set=''
+ac_cv_env_host_alias_value=''
+ac_cv_env_target_alias_set=''
+ac_cv_env_target_alias_value=''
+ac_cv_func_strndup=yes
+ac_cv_header_inttypes_h=yes
+ac_cv_header_memory_h=yes
+ac_cv_header_pthread_h=yes
+ac_cv_header_stdc=yes
+ac_cv_header_stdint_h=yes
+ac_cv_header_stdlib_h=yes
+ac_cv_header_string_h=yes
+ac_cv_header_strings_h=yes
+ac_cv_header_sys_stat_h=yes
+ac_cv_header_sys_types_h=yes
+ac_cv_header_unistd_h=yes
+ac_cv_objext=o
+ac_cv_path_EGREP='/usr/bin/grep -E'
+ac_cv_path_GREP=/usr/bin/grep
+ac_cv_path_ac_pt_PKG_CONFIG=/usr/local/bin/pkg-config
+ac_cv_path_install='/usr/bin/install -c'
+ac_cv_prog_AWK=nawk
+ac_cv_prog_CC=cc
+ac_cv_prog_CPP='cc -E'
+ac_cv_prog_cc_c89=''
+ac_cv_prog_cc_g=yes
+ac_cv_prog_make_make_set=yes
+am_cv_CC_dependencies_compiler_type=gcc3
+pkg_cv_WDFS_CFLAGS='-I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include '
+pkg_cv_WDFS_LIBS='-L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl '
+
+## ----------------- ##
+## Output variables. ##
+## ----------------- ##
+
+ACLOCAL='${SHELL} /xj/waitman/wdfs/missing --run aclocal-1.9'
+AMDEPBACKSLASH='\'
+AMDEP_FALSE='#'
+AMDEP_TRUE=''
+AMTAR='${SHELL} /xj/waitman/wdfs/missing --run tar'
+AUTOCONF='${SHELL} /xj/waitman/wdfs/missing --run autoconf'
+AUTOHEADER='${SHELL} /xj/waitman/wdfs/missing --run autoheader'
+AUTOMAKE='${SHELL} /xj/waitman/wdfs/missing --run automake-1.9'
+AWK='nawk'
+CC='cc'
+CCDEPMODE='depmode=gcc3'
+CFLAGS='-g -O2 -I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include -Wall -D_GNU_SOURCE -D_REENTRANT'
+CPP='cc -E'
+CPPFLAGS=''
+CYGPATH_W='echo'
+DEFS='-DHAVE_CONFIG_H'
+DEPDIR='.deps'
+ECHO_C=''
+ECHO_N='-n'
+ECHO_T=''
+EGREP='/usr/bin/grep -E'
+EXEEXT=''
+GREP='/usr/bin/grep'
+INSTALL_DATA='${INSTALL} -m 644'
+INSTALL_PROGRAM='${INSTALL}'
+INSTALL_SCRIPT='${INSTALL}'
+INSTALL_STRIP_PROGRAM='${SHELL} $(install_sh) -c -s'
+LDFLAGS=''
+LIBOBJS=''
+LIBS='-L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl '
+LTLIBOBJS=''
+MAKEINFO='${SHELL} /xj/waitman/wdfs/missing --run makeinfo'
+OBJEXT='o'
+PACKAGE='wdfs'
+PACKAGE_BUGREPORT='[email protected]'
+PACKAGE_NAME='wdfs'
+PACKAGE_STRING='wdfs 1.4.2'
+PACKAGE_TARNAME='wdfs'
+PACKAGE_VERSION='1.4.2'
+PATH_SEPARATOR=':'
+PKG_CONFIG='/usr/local/bin/pkg-config'
+SET_MAKE=''
+SHELL='/bin/sh'
+STRIP=''
+VERSION='1.4.2'
+WDFS_CFLAGS='-I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include '
+WDFS_LIBS='-L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl '
+ac_ct_CC=''
+am__fastdepCC_FALSE='#'
+am__fastdepCC_TRUE=''
+am__include='include'
+am__leading_dot='.'
+am__quote=''
+am__tar='${AMTAR} chof - "$$tardir"'
+am__untar='${AMTAR} xf -'
+bindir='${exec_prefix}/bin'
+build_alias=''
+datadir='${datarootdir}'
+datarootdir='${prefix}/share'
+docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
+dvidir='${docdir}'
+exec_prefix='${prefix}'
+host_alias=''
+htmldir='${docdir}'
+includedir='${prefix}/include'
+infodir='${datarootdir}/info'
+install_sh='/xj/waitman/wdfs/install-sh'
+libdir='${exec_prefix}/lib'
+libexecdir='${exec_prefix}/libexec'
+localedir='${datarootdir}/locale'
+localstatedir='${prefix}/var'
+mandir='${datarootdir}/man'
+mkdir_p='$(install_sh) -d'
+oldincludedir='/usr/include'
+pdfdir='${docdir}'
+prefix='/usr/local'
+program_transform_name='s,x,x,'
+psdir='${docdir}'
+sbindir='${exec_prefix}/sbin'
+sharedstatedir='${prefix}/com'
+sysconfdir='${prefix}/etc'
+target_alias=''
+
+## ----------- ##
+## confdefs.h. ##
+## ----------- ##
+
+#define PACKAGE_NAME "wdfs"
+#define PACKAGE_TARNAME "wdfs"
+#define PACKAGE_VERSION "1.4.2"
+#define PACKAGE_STRING "wdfs 1.4.2"
+#define PACKAGE_BUGREPORT "[email protected]"
+#define PACKAGE "wdfs"
+#define VERSION "1.4.2"
+#define STDC_HEADERS 1
+#define HAVE_SYS_TYPES_H 1
+#define HAVE_SYS_STAT_H 1
+#define HAVE_STDLIB_H 1
+#define HAVE_STRING_H 1
+#define HAVE_MEMORY_H 1
+#define HAVE_STRINGS_H 1
+#define HAVE_INTTYPES_H 1
+#define HAVE_STDINT_H 1
+#define HAVE_UNISTD_H 1
+#define HAVE_PTHREAD_H 1
+#define HAVE_STRNDUP 1
+
+configure: exit 0
diff --git a/config.status b/config.status
new file mode 100755
index 0000000..4174aae
--- /dev/null
+++ b/config.status
@@ -0,0 +1,1040 @@
+#! /bin/sh
+# Generated by configure.
+# Run this file to recreate the current configuration.
+# Compiler output produced by configure, useful for debugging
+# configure, is in config.log if it exists.
+
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+SHELL=${CONFIG_SHELL-/bin/sh}
+## --------------------- ##
+## M4sh Initialization. ##
+## --------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+ emulate sh
+ NULLCMD=:
+ # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+ # is contrary to our usage. Disable this feature.
+ alias -g '${1+"$@"}'='"$@"'
+ setopt NO_GLOB_SUBST
+else
+ case `(set -o) 2>/dev/null` in
+ *posix*) set -o posix ;;
+esac
+
+fi
+
+
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+ echo "#! /bin/sh" >conf$$.sh
+ echo "exit 0" >>conf$$.sh
+ chmod +x conf$$.sh
+ if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+ PATH_SEPARATOR=';'
+ else
+ PATH_SEPARATOR=:
+ fi
+ rm -f conf$$.sh
+fi
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+ as_unset=unset
+else
+ as_unset=false
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order. Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" "" $as_nl"
+
+# Find who we are. Look in the path if we contain no directory separator.
+case $0 in
+ *[\\/]* ) as_myself=$0 ;;
+ *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+ IFS=$as_save_IFS
+ test -z "$as_dir" && as_dir=.
+ test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+ ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+ as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+ echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+ { (exit 1); exit 1; }
+fi
+
+# Work around bugs in pre-3.0 UWIN ksh.
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+ LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+ LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+ LC_TELEPHONE LC_TIME
+do
+ if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+ eval $as_var=C; export $as_var
+ else
+ ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+ fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+ test "X`expr 00001 : '.*\(...\)'`" = X001; then
+ as_expr=expr
+else
+ as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+ as_basename=basename
+else
+ as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+ X"$0" : 'X\(//\)$' \| \
+ X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X/"$0" |
+ sed '/^.*\/\([^/][^/]*\)\/*$/{
+ s//\1/
+ q
+ }
+ /^X\/\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\/\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`
+
+# CDPATH.
+$as_unset CDPATH
+
+
+
+ as_lineno_1=$LINENO
+ as_lineno_2=$LINENO
+ test "x$as_lineno_1" != "x$as_lineno_2" &&
+ test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+
+ # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+ # uniformly replaced by the line number. The first 'sed' inserts a
+ # line-number line after each line using $LINENO; the second 'sed'
+ # does the real work. The second script uses 'N' to pair each
+ # line-number line with the line containing $LINENO, and appends
+ # trailing '-' during substitution so that $LINENO is not a special
+ # case at line end.
+ # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+ # scripts with optimization help from Paolo Bonzini. Blame Lee
+ # E. McMahon (1931-1989) for sed's syntax. :-)
+ sed -n '
+ p
+ /[$]LINENO/=
+ ' <$as_myself |
+ sed '
+ s/[$]LINENO.*/&-/
+ t lineno
+ b
+ :lineno
+ N
+ :loop
+ s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+ t loop
+ s/-\n.*//
+ ' >$as_me.lineno &&
+ chmod +x "$as_me.lineno" ||
+ { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+ { (exit 1); exit 1; }; }
+
+ # Don't try to exec as it changes $[0], causing all sort of problems
+ # (the dirname of $[0] is not the place where we might find the
+ # original and so on. Autoconf is especially sensitive to this).
+ . "./$as_me.lineno"
+ # Exit status is that of the last command.
+ exit
+}
+
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+ as_dirname=dirname
+else
+ as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+ case `echo 'x\c'` in
+ *c*) ECHO_T=' ';; # ECHO_T is single tab character.
+ *) ECHO_C='\c';;
+ esac;;
+*)
+ ECHO_N='-n';;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+ test "X`expr 00001 : '.*\(...\)'`" = X001; then
+ as_expr=expr
+else
+ as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+ rm -f conf$$.dir/conf$$.file
+else
+ rm -f conf$$.dir
+ mkdir conf$$.dir
+fi
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+ as_ln_s='ln -s'
+ # ... but there are two gotchas:
+ # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+ # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+ # In both cases, we have to default to `cp -p'.
+ ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+ as_ln_s='cp -p'
+elif ln conf$$.file conf$$ 2>/dev/null; then
+ as_ln_s=ln
+else
+ as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+ as_mkdir_p=:
+else
+ test -d ./-p && rmdir ./-p
+ as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+ as_test_x='test -x'
+else
+ if ls -dL / >/dev/null 2>&1; then
+ as_ls_L_option=L
+ else
+ as_ls_L_option=
+ fi
+ as_test_x='
+ eval sh -c '\''
+ if test -d "$1"; then
+ test -d "$1/.";
+ else
+ case $1 in
+ -*)set "./$1";;
+ esac;
+ case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+ ???[sx]*):;;*)false;;esac;fi
+ '\'' sh
+ '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 6>&1
+
+# Save the log message, to keep $[0] and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by wdfs $as_me 1.4.2, which was
+generated by GNU Autoconf 2.61. Invocation command line was
+
+ CONFIG_FILES = $CONFIG_FILES
+ CONFIG_HEADERS = $CONFIG_HEADERS
+ CONFIG_LINKS = $CONFIG_LINKS
+ CONFIG_COMMANDS = $CONFIG_COMMANDS
+ $ $0 $@
+
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
+# Files that config.status was made for.
+config_files=" Makefile src/Makefile"
+config_headers=" src/config.h"
+config_commands=" depfiles"
+
+ac_cs_usage="\
+\`$as_me' instantiates files from templates according to the
+current configuration.
+
+Usage: $0 [OPTIONS] [FILE]...
+
+ -h, --help print this help, then exit
+ -V, --version print version number and configuration settings, then exit
+ -q, --quiet do not print progress messages
+ -d, --debug don't remove temporary files
+ --recheck update $as_me by reconfiguring in the same conditions
+ --file=FILE[:TEMPLATE]
+ instantiate the configuration file FILE
+ --header=FILE[:TEMPLATE]
+ instantiate the configuration header FILE
+
+Configuration files:
+$config_files
+
+Configuration headers:
+$config_headers
+
+Configuration commands:
+$config_commands
+
+Report bugs to <[email protected]>."
+
+ac_cs_version="\
+wdfs config.status 1.4.2
+configured by ./configure, generated by GNU Autoconf 2.61,
+ with options \"\"
+
+Copyright (C) 2006 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+
+ac_pwd='/xj/waitman/wdfs'
+srcdir='.'
+INSTALL='/usr/bin/install -c'
+# If no file are specified by the user, then we need to provide default
+# value. By we need to know if files were specified by the user.
+ac_need_defaults=:
+while test $# != 0
+do
+ case $1 in
+ --*=*)
+ ac_option=`expr "X$1" : 'X\([^=]*\)='`
+ ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+ ac_shift=:
+ ;;
+ *)
+ ac_option=$1
+ ac_optarg=$2
+ ac_shift=shift
+ ;;
+ esac
+
+ case $ac_option in
+ # Handling of the options.
+ -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
+ ac_cs_recheck=: ;;
+ --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+ echo "$ac_cs_version"; exit ;;
+ --debug | --debu | --deb | --de | --d | -d )
+ debug=: ;;
+ --file | --fil | --fi | --f )
+ $ac_shift
+ CONFIG_FILES="$CONFIG_FILES $ac_optarg"
+ ac_need_defaults=false;;
+ --header | --heade | --head | --hea )
+ $ac_shift
+ CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg"
+ ac_need_defaults=false;;
+ --he | --h)
+ # Conflict between --help and --header
+ { echo "$as_me: error: ambiguous option: $1
+Try \`$0 --help' for more information." >&2
+ { (exit 1); exit 1; }; };;
+ --help | --hel | -h )
+ echo "$ac_cs_usage"; exit ;;
+ -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+ | -silent | --silent | --silen | --sile | --sil | --si | --s)
+ ac_cs_silent=: ;;
+
+ # This is an error.
+ -*) { echo "$as_me: error: unrecognized option: $1
+Try \`$0 --help' for more information." >&2
+ { (exit 1); exit 1; }; } ;;
+
+ *) ac_config_targets="$ac_config_targets $1"
+ ac_need_defaults=false ;;
+
+ esac
+ shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+ exec 6>/dev/null
+ ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+if $ac_cs_recheck; then
+ echo "running CONFIG_SHELL=/bin/sh /bin/sh ./configure " $ac_configure_extra_args " --no-create --no-recursion" >&6
+ CONFIG_SHELL=/bin/sh
+ export CONFIG_SHELL
+ exec /bin/sh "./configure" $ac_configure_extra_args --no-create --no-recursion
+fi
+
+exec 5>>config.log
+{
+ echo
+ sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+ echo "$ac_log"
+} >&5
+
+#
+# INIT-COMMANDS
+#
+AMDEP_TRUE="" ac_aux_dir="."
+
+
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+ case $ac_config_target in
+ "src/config.h") CONFIG_HEADERS="$CONFIG_HEADERS src/config.h" ;;
+ "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;;
+ "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
+ "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;;
+
+ *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
+echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
+ { (exit 1); exit 1; }; };;
+ esac
+done
+
+
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used. Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+ test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+ test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
+ test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands
+fi
+
+# Have a temporary directory for convenience. Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+ tmp=
+ trap 'exit_status=$?
+ { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
+' 0
+ trap '{ (exit 1); exit 1; }' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
+
+{
+ tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+ test -n "$tmp" && test -d "$tmp"
+} ||
+{
+ tmp=./conf$$-$RANDOM
+ (umask 077 && mkdir "$tmp")
+} ||
+{
+ echo "$me: cannot create a temporary directory in ." >&2
+ { (exit 1); exit 1; }
+}
+
+#
+# Set up the sed scripts for CONFIG_FILES section.
+#
+
+# No need to generate the scripts if there are no CONFIG_FILES.
+# This happens for instance when ./config.status config.h
+if test -n "$CONFIG_FILES"; then
+
+cat >"$tmp/subs-1.sed" <<\CEOF
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end
+s,@SHELL@,|#_!!_#|/bin/sh,g
+s,@PATH_SEPARATOR@,|#_!!_#|:,g
+s,@PACKAGE_NAME@,|#_!!_#|wdfs,g
+s,@PACKAGE_TARNAME@,|#_!!_#|wdfs,g
+s,@PACKAGE_VERSION@,|#_!!_#|1.4.2,g
+s,@PACKAGE_STRING@,|#_!!_#|wdfs 1.4.2,g
+s,@PACKAGE_BUGREPORT@,|#_!!_#|noedler@|#_!!_#|web.de,g
+s,@exec_prefix@,|#_!!_#|${prefix},g
+s,@prefix@,|#_!!_#|/usr/local,g
+s,@program_transform_name@,|#_!!_#|s\,x\,x\,,g
+s,@bindir@,|#_!!_#|${exec_prefix}/bin,g
+s,@sbindir@,|#_!!_#|${exec_prefix}/sbin,g
+s,@libexecdir@,|#_!!_#|${exec_prefix}/libexec,g
+s,@datarootdir@,|#_!!_#|${prefix}/share,g
+s,@datadir@,|#_!!_#|${datarootdir},g
+s,@sysconfdir@,|#_!!_#|${prefix}/etc,g
+s,@sharedstatedir@,|#_!!_#|${prefix}/com,g
+s,@localstatedir@,|#_!!_#|${prefix}/var,g
+s,@includedir@,|#_!!_#|${prefix}/include,g
+s,@oldincludedir@,|#_!!_#|/usr/include,g
+s,@docdir@,|#_!!_#|${datarootdir}/doc/${PACKAGE_TARNAME},g
+s,@infodir@,|#_!!_#|${datarootdir}/info,g
+s,@htmldir@,|#_!!_#|${docdir},g
+s,@dvidir@,|#_!!_#|${docdir},g
+s,@pdfdir@,|#_!!_#|${docdir},g
+s,@psdir@,|#_!!_#|${docdir},g
+s,@libdir@,|#_!!_#|${exec_prefix}/lib,g
+s,@localedir@,|#_!!_#|${datarootdir}/locale,g
+s,@mandir@,|#_!!_#|${datarootdir}/man,g
+s,@DEFS@,|#_!!_#|-DHAVE_CONFIG_H,g
+s,@ECHO_C@,|#_!!_#|,g
+s,@ECHO_N@,|#_!!_#|-n,g
+s,@ECHO_T@,|#_!!_#|,g
+s,@LIBS@,|#_!!_#|-L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl ,g
+s,@build_alias@,|#_!!_#|,g
+s,@host_alias@,|#_!!_#|,g
+s,@target_alias@,|#_!!_#|,g
+s,@INSTALL_PROGRAM@,|#_!!_#|${INSTALL},g
+s,@INSTALL_SCRIPT@,|#_!!_#|${INSTALL},g
+s,@INSTALL_DATA@,|#_!!_#|${INSTALL} -m 644,g
+s,@CYGPATH_W@,|#_!!_#|echo,g
+s,@PACKAGE@,|#_!!_#|wdfs,g
+s,@VERSION@,|#_!!_#|1.4.2,g
+s,@ACLOCAL@,|#_!!_#|${SHELL} /xj/waitman/wdfs/missing --run aclocal-1.9,g
+s,@AUTOCONF@,|#_!!_#|${SHELL} /xj/waitman/wdfs/missing --run autoconf,g
+s,@AUTOMAKE@,|#_!!_#|${SHELL} /xj/waitman/wdfs/missing --run automake-1.9,g
+s,@AUTOHEADER@,|#_!!_#|${SHELL} /xj/waitman/wdfs/missing --run autoheader,g
+s,@MAKEINFO@,|#_!!_#|${SHELL} /xj/waitman/wdfs/missing --run makeinfo,g
+s,@install_sh@,|#_!!_#|/xj/waitman/wdfs/install-sh,g
+s,@STRIP@,|#_!!_#|,g
+s,@INSTALL_STRIP_PROGRAM@,|#_!!_#|${SHELL} $(install_sh) -c -s,g
+s,@mkdir_p@,|#_!!_#|$(install_sh) -d,g
+s,@AWK@,|#_!!_#|nawk,g
+s,@SET_MAKE@,|#_!!_#|,g
+s,@am__leading_dot@,|#_!!_#|.,g
+s,@AMTAR@,|#_!!_#|${SHELL} /xj/waitman/wdfs/missing --run tar,g
+s,@am__tar@,|#_!!_#|${AMTAR} chof - "$$tardir",g
+s,@am__untar@,|#_!!_#|${AMTAR} xf -,g
+s,@CC@,|#_!!_#|cc,g
+s,@CFLAGS@,|#_!!_#|-g -O2 -I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include -Wall -D_GNU_SOURCE -D_REENTRANT,g
+s,@LDFLAGS@,|#_!!_#|,g
+s,@CPPFLAGS@,|#_!!_#|,g
+s,@ac_ct_CC@,|#_!!_#|,g
+s,@EXEEXT@,|#_!!_#|,g
+s,@OBJEXT@,|#_!!_#|o,g
+s,@DEPDIR@,|#_!!_#|.deps,g
+s,@am__include@,|#_!!_#|include,g
+s,@am__quote@,|#_!!_#|,g
+s,@AMDEP_TRUE@,|#_!!_#|,g
+s,@AMDEP_FALSE@,|#_!!_#|#,g
+s,@AMDEPBACKSLASH@,|#_!!_#|\\,g
+s,@CCDEPMODE@,|#_!!_#|depmode=gcc3,g
+s,@am__fastdepCC_TRUE@,|#_!!_#|,g
+s,@am__fastdepCC_FALSE@,|#_!!_#|#,g
+s,@CPP@,|#_!!_#|cc -E,g
+s,@GREP@,|#_!!_#|/usr/bin/grep,g
+s,@EGREP@,|#_!!_#|/usr/bin/grep -E,g
+s,@PKG_CONFIG@,|#_!!_#|/usr/local/bin/pkg-config,g
+s,@WDFS_CFLAGS@,|#_!!_#|-I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include ,g
+s,@WDFS_LIBS@,|#_!!_#|-L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl ,g
+s,@LIBOBJS@,|#_!!_#|,g
+s,@LTLIBOBJS@,|#_!!_#|,g
+:end
+s/|#_!!_#|//g
+CEOF
+fi # test -n "$CONFIG_FILES"
+
+
+for ac_tag in :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS
+do
+ case $ac_tag in
+ :[FHLC]) ac_mode=$ac_tag; continue;;
+ esac
+ case $ac_mode$ac_tag in
+ :[FHL]*:*);;
+ :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5
+echo "$as_me: error: Invalid tag $ac_tag." >&2;}
+ { (exit 1); exit 1; }; };;
+ :[FH]-) ac_tag=-:-;;
+ :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
+ esac
+ ac_save_IFS=$IFS
+ IFS=:
+ set x $ac_tag
+ IFS=$ac_save_IFS
+ shift
+ ac_file=$1
+ shift
+
+ case $ac_mode in
+ :L) ac_source=$1;;
+ :[FH])
+ ac_file_inputs=
+ for ac_f
+ do
+ case $ac_f in
+ -) ac_f="$tmp/stdin";;
+ *) # Look for the file first in the build tree, then in the source tree
+ # (if the path is not absolute). The absolute path cannot be DOS-style,
+ # because $ac_f cannot contain `:'.
+ test -f "$ac_f" ||
+ case $ac_f in
+ [\\/$]*) false;;
+ *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+ esac ||
+ { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5
+echo "$as_me: error: cannot find input file: $ac_f" >&2;}
+ { (exit 1); exit 1; }; };;
+ esac
+ ac_file_inputs="$ac_file_inputs $ac_f"
+ done
+
+ # Let's still pretend it is `configure' which instantiates (i.e., don't
+ # use $as_me), people would be surprised to read:
+ # /* config.h. Generated by config.status. */
+ configure_input="Generated from "`IFS=:
+ echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure."
+ if test x"$ac_file" != x-; then
+ configure_input="$ac_file. $configure_input"
+ { echo "$as_me:$LINENO: creating $ac_file" >&5
+echo "$as_me: creating $ac_file" >&6;}
+ fi
+
+ case $ac_tag in
+ *:-:* | *:-) cat >"$tmp/stdin";;
+ esac
+ ;;
+ esac
+
+ ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$ac_file" : 'X\(//\)[^/]' \| \
+ X"$ac_file" : 'X\(//\)$' \| \
+ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$ac_file" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)[^/].*/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`
+ { as_dir="$ac_dir"
+ case $as_dir in #(
+ -*) as_dir=./$as_dir;;
+ esac
+ test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
+ as_dirs=
+ while :; do
+ case $as_dir in #(
+ *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
+ *) as_qdir=$as_dir;;
+ esac
+ as_dirs="'$as_qdir' $as_dirs"
+ as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$as_dir" : 'X\(//\)[^/]' \| \
+ X"$as_dir" : 'X\(//\)$' \| \
+ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$as_dir" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)[^/].*/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`
+ test -d "$as_dir" && break
+ done
+ test -z "$as_dirs" || eval "mkdir $as_dirs"
+ } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
+echo "$as_me: error: cannot create directory $as_dir" >&2;}
+ { (exit 1); exit 1; }; }; }
+ ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+ ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+ # A ".." for each directory in $ac_dir_suffix.
+ ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+ case $ac_top_builddir_sub in
+ "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+ *) ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+ esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+ .) # We are building in place.
+ ac_srcdir=.
+ ac_top_srcdir=$ac_top_builddir_sub
+ ac_abs_top_srcdir=$ac_pwd ;;
+ [\\/]* | ?:[\\/]* ) # Absolute name.
+ ac_srcdir=$srcdir$ac_dir_suffix;
+ ac_top_srcdir=$srcdir
+ ac_abs_top_srcdir=$srcdir ;;
+ *) # Relative name.
+ ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+ ac_top_srcdir=$ac_top_build_prefix$srcdir
+ ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+ case $ac_mode in
+ :F)
+ #
+ # CONFIG_FILE
+ #
+
+ case $INSTALL in
+ [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;;
+ *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;;
+ esac
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+
+case `sed -n '/datarootdir/ {
+ p
+ q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p
+' $ac_file_inputs` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+ { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+ ac_datarootdir_hack='
+ s&@datadir@&${datarootdir}&g
+ s&@docdir@&${datarootdir}/doc/${PACKAGE_TARNAME}&g
+ s&@infodir@&${datarootdir}/info&g
+ s&@localedir@&${datarootdir}/locale&g
+ s&@mandir@&${datarootdir}/man&g
+ s&\${datarootdir}&${prefix}/share&g' ;;
+esac
+ sed "/^[ ]*VPATH[ ]*=/{
+s/:*\$(srcdir):*/:/
+s/:*\${srcdir}:*/:/
+s/:*@srcdir@:*/:/
+s/^\([^=]*=[ ]*\):*/\1/
+s/:*$//
+s/^[^=]*=[ ]*$//
+}
+
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s&@configure_input@&$configure_input&;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+s&@INSTALL@&$ac_INSTALL&;t t
+$ac_datarootdir_hack
+" $ac_file_inputs | sed -f "$tmp/subs-1.sed" >$tmp/out
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+ { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
+ { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
+ { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined. Please make sure it is defined." >&5
+echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined. Please make sure it is defined." >&2;}
+
+ rm -f "$tmp/stdin"
+ case $ac_file in
+ -) cat "$tmp/out"; rm -f "$tmp/out";;
+ *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;;
+ esac
+ ;;
+ :H)
+ #
+ # CONFIG_HEADER
+ #
+ # First, check the format of the line:
+ cat >"$tmp/defines.sed" <<\CEOF
+/^[ ]*#[ ]*undef[ ][ ]*[_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ][_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*[ ]*$/b def
+/^[ ]*#[ ]*define[ ][ ]*[_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ][_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*[( ]/b def
+b
+:def
+s/$/ /
+s,^\([ #]*\)[^ ]*\([ ]*PACKAGE_NAME\)[ (].*,\1define\2 "wdfs" ,
+s,^\([ #]*\)[^ ]*\([ ]*PACKAGE_TARNAME\)[ (].*,\1define\2 "wdfs" ,
+s,^\([ #]*\)[^ ]*\([ ]*PACKAGE_VERSION\)[ (].*,\1define\2 "1.4.2" ,
+s,^\([ #]*\)[^ ]*\([ ]*PACKAGE_STRING\)[ (].*,\1define\2 "wdfs 1.4.2" ,
+s,^\([ #]*\)[^ ]*\([ ]*PACKAGE_BUGREPORT\)[ (].*,\1define\2 "[email protected]" ,
+s,^\([ #]*\)[^ ]*\([ ]*PACKAGE\)[ (].*,\1define\2 "wdfs" ,
+s,^\([ #]*\)[^ ]*\([ ]*VERSION\)[ (].*,\1define\2 "1.4.2" ,
+s,^\([ #]*\)[^ ]*\([ ]*STDC_HEADERS\)[ (].*,\1define\2 1 ,
+s,^\([ #]*\)[^ ]*\([ ]*HAVE_SYS_TYPES_H\)[ (].*,\1define\2 1 ,
+s,^\([ #]*\)[^ ]*\([ ]*HAVE_SYS_STAT_H\)[ (].*,\1define\2 1 ,
+s,^\([ #]*\)[^ ]*\([ ]*HAVE_STDLIB_H\)[ (].*,\1define\2 1 ,
+s,^\([ #]*\)[^ ]*\([ ]*HAVE_STRING_H\)[ (].*,\1define\2 1 ,
+s,^\([ #]*\)[^ ]*\([ ]*HAVE_MEMORY_H\)[ (].*,\1define\2 1 ,
+s,^\([ #]*\)[^ ]*\([ ]*HAVE_STRINGS_H\)[ (].*,\1define\2 1 ,
+s,^\([ #]*\)[^ ]*\([ ]*HAVE_INTTYPES_H\)[ (].*,\1define\2 1 ,
+s,^\([ #]*\)[^ ]*\([ ]*HAVE_STDINT_H\)[ (].*,\1define\2 1 ,
+s,^\([ #]*\)[^ ]*\([ ]*HAVE_UNISTD_H\)[ (].*,\1define\2 1 ,
+s,^\([ #]*\)[^ ]*\([ ]*HAVE_PTHREAD_H\)[ (].*,\1define\2 1 ,
+s,^\([ #]*\)[^ ]*\([ ]*HAVE_STRNDUP\)[ (].*,\1define\2 1 ,
+s/ $//
+s,^[ #]*u.*,/* & */,
+CEOF
+ sed -f "$tmp/defines.sed" $ac_file_inputs >"$tmp/out1"
+ac_result="$tmp/out1"
+ if test x"$ac_file" != x-; then
+ echo "/* $configure_input */" >"$tmp/config.h"
+ cat "$ac_result" >>"$tmp/config.h"
+ if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then
+ { echo "$as_me:$LINENO: $ac_file is unchanged" >&5
+echo "$as_me: $ac_file is unchanged" >&6;}
+ else
+ rm -f $ac_file
+ mv "$tmp/config.h" $ac_file
+ fi
+ else
+ echo "/* $configure_input */"
+ cat "$ac_result"
+ fi
+ rm -f "$tmp/out12"
+# Compute $ac_file's index in $config_headers.
+_am_stamp_count=1
+for _am_header in $config_headers :; do
+ case $_am_header in
+ $ac_file | $ac_file:* )
+ break ;;
+ * )
+ _am_stamp_count=`expr $_am_stamp_count + 1` ;;
+ esac
+done
+echo "timestamp for $ac_file" >`$as_dirname -- $ac_file ||
+$as_expr X$ac_file : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X$ac_file : 'X\(//\)[^/]' \| \
+ X$ac_file : 'X\(//\)$' \| \
+ X$ac_file : 'X\(/\)' \| . 2>/dev/null ||
+echo X$ac_file |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)[^/].*/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`/stamp-h$_am_stamp_count
+ ;;
+
+ :C) { echo "$as_me:$LINENO: executing $ac_file commands" >&5
+echo "$as_me: executing $ac_file commands" >&6;}
+ ;;
+ esac
+
+
+ case $ac_file$ac_mode in
+ "depfiles":C) test x"$AMDEP_TRUE" != x"" || for mf in $CONFIG_FILES; do
+ # Strip MF so we end up with the name of the file.
+ mf=`echo "$mf" | sed -e 's/:.*$//'`
+ # Check whether this is an Automake generated Makefile or not.
+ # We used to match only the files named `Makefile.in', but
+ # some people rename them; so instead we look at the file content.
+ # Grep'ing the first line is not enough: some people post-process
+ # each Makefile.in and add a new line on top of each file to say so.
+ # So let's grep whole file.
+ if grep '^#.*generated by automake' $mf > /dev/null 2>&1; then
+ dirpart=`$as_dirname -- "$mf" ||
+$as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$mf" : 'X\(//\)[^/]' \| \
+ X"$mf" : 'X\(//\)$' \| \
+ X"$mf" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$mf" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)[^/].*/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`
+ else
+ continue
+ fi
+ # Extract the definition of DEPDIR, am__include, and am__quote
+ # from the Makefile without running `make'.
+ DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"`
+ test -z "$DEPDIR" && continue
+ am__include=`sed -n 's/^am__include = //p' < "$mf"`
+ test -z "am__include" && continue
+ am__quote=`sed -n 's/^am__quote = //p' < "$mf"`
+ # When using ansi2knr, U may be empty or an underscore; expand it
+ U=`sed -n 's/^U = //p' < "$mf"`
+ # Find all dependency output files, they are included files with
+ # $(DEPDIR) in their names. We invoke sed twice because it is the
+ # simplest approach to changing $(DEPDIR) to its actual value in the
+ # expansion.
+ for file in `sed -n "
+ s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \
+ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do
+ # Make sure the directory exists.
+ test -f "$dirpart/$file" && continue
+ fdir=`$as_dirname -- "$file" ||
+$as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$file" : 'X\(//\)[^/]' \| \
+ X"$file" : 'X\(//\)$' \| \
+ X"$file" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$file" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)[^/].*/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`
+ { as_dir=$dirpart/$fdir
+ case $as_dir in #(
+ -*) as_dir=./$as_dir;;
+ esac
+ test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
+ as_dirs=
+ while :; do
+ case $as_dir in #(
+ *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
+ *) as_qdir=$as_dir;;
+ esac
+ as_dirs="'$as_qdir' $as_dirs"
+ as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+ X"$as_dir" : 'X\(//\)[^/]' \| \
+ X"$as_dir" : 'X\(//\)$' \| \
+ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$as_dir" |
+ sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)[^/].*/{
+ s//\1/
+ q
+ }
+ /^X\(\/\/\)$/{
+ s//\1/
+ q
+ }
+ /^X\(\/\).*/{
+ s//\1/
+ q
+ }
+ s/.*/./; q'`
+ test -d "$as_dir" && break
+ done
+ test -z "$as_dirs" || eval "mkdir $as_dirs"
+ } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
+echo "$as_me: error: cannot create directory $as_dir" >&2;}
+ { (exit 1); exit 1; }; }; }
+ # echo "creating $dirpart/$file"
+ echo '# dummy' > "$dirpart/$file"
+ done
+done
+ ;;
+
+ esac
+done # for ac_tag
+
+
+{ (exit 0); exit 0; }
diff --git a/src/.deps/cache.Po b/src/.deps/cache.Po
new file mode 100644
index 0000000..82b1710
--- /dev/null
+++ b/src/.deps/cache.Po
@@ -0,0 +1,409 @@
+cache.o: cache.c /usr/include/stdio.h /usr/include/sys/cdefs.h \
+ /usr/include/sys/_null.h /usr/include/sys/_types.h \
+ /usr/include/machine/_types.h /usr/include/x86/_types.h \
+ /usr/include/stdlib.h /usr/include/string.h /usr/include/strings.h \
+ /usr/include/xlocale/_strings.h /usr/include/xlocale/_string.h \
+ /usr/include/assert.h /usr/local/include/glib-2.0/glib.h \
+ /usr/local/include/glib-2.0/glib/galloca.h \
+ /usr/local/include/glib-2.0/glib/gtypes.h \
+ /usr/local/lib/glib-2.0/include/glibconfig.h \
+ /usr/local/include/glib-2.0/glib/gmacros.h /usr/include/stddef.h \
+ /usr/include/limits.h /usr/include/sys/limits.h \
+ /usr/include/machine/_limits.h /usr/include/x86/_limits.h \
+ /usr/include/sys/syslimits.h /usr/include/float.h \
+ /usr/include/x86/float.h \
+ /usr/local/include/glib-2.0/glib/gversionmacros.h /usr/include/time.h \
+ /usr/include/sys/timespec.h /usr/include/sys/_timespec.h \
+ /usr/include/xlocale/_time.h /usr/local/include/glib-2.0/glib/garray.h \
+ /usr/local/include/glib-2.0/glib/gasyncqueue.h \
+ /usr/local/include/glib-2.0/glib/gthread.h \
+ /usr/local/include/glib-2.0/glib/gatomic.h \
+ /usr/local/include/glib-2.0/glib/gerror.h /usr/include/stdarg.h \
+ /usr/include/x86/stdarg.h /usr/local/include/glib-2.0/glib/gquark.h \
+ /usr/local/include/glib-2.0/glib/gutils.h \
+ /usr/local/include/glib-2.0/glib/gbacktrace.h /usr/include/signal.h \
+ /usr/include/sys/signal.h /usr/include/sys/_sigset.h \
+ /usr/include/machine/signal.h /usr/include/x86/signal.h \
+ /usr/include/machine/trap.h /usr/include/x86/trap.h \
+ /usr/local/include/glib-2.0/glib/gbase64.h \
+ /usr/local/include/glib-2.0/glib/gbitlock.h \
+ /usr/local/include/glib-2.0/glib/gbookmarkfile.h \
+ /usr/local/include/glib-2.0/glib/gbytes.h \
+ /usr/local/include/glib-2.0/glib/gcharset.h \
+ /usr/local/include/glib-2.0/glib/gchecksum.h \
+ /usr/local/include/glib-2.0/glib/gconvert.h \
+ /usr/local/include/glib-2.0/glib/gdataset.h \
+ /usr/local/include/glib-2.0/glib/gdate.h \
+ /usr/local/include/glib-2.0/glib/gdatetime.h \
+ /usr/local/include/glib-2.0/glib/gtimezone.h \
+ /usr/local/include/glib-2.0/glib/gdir.h /usr/include/dirent.h \
+ /usr/include/sys/dirent.h /usr/local/include/glib-2.0/glib/genviron.h \
+ /usr/local/include/glib-2.0/glib/gfileutils.h \
+ /usr/local/include/glib-2.0/glib/ggettext.h \
+ /usr/local/include/glib-2.0/glib/ghash.h \
+ /usr/local/include/glib-2.0/glib/glist.h \
+ /usr/local/include/glib-2.0/glib/gmem.h \
+ /usr/local/include/glib-2.0/glib/gnode.h \
+ /usr/local/include/glib-2.0/glib/ghmac.h \
+ /usr/local/include/glib-2.0/glib/ghook.h \
+ /usr/local/include/glib-2.0/glib/ghostutils.h \
+ /usr/local/include/glib-2.0/glib/giochannel.h \
+ /usr/local/include/glib-2.0/glib/gmain.h \
+ /usr/local/include/glib-2.0/glib/gpoll.h \
+ /usr/local/include/glib-2.0/glib/gslist.h \
+ /usr/local/include/glib-2.0/glib/gstring.h \
+ /usr/local/include/glib-2.0/glib/gunicode.h \
+ /usr/local/include/glib-2.0/glib/gkeyfile.h \
+ /usr/local/include/glib-2.0/glib/gmappedfile.h \
+ /usr/local/include/glib-2.0/glib/gmarkup.h \
+ /usr/local/include/glib-2.0/glib/gmessages.h \
+ /usr/local/include/glib-2.0/glib/goption.h \
+ /usr/local/include/glib-2.0/glib/gpattern.h \
+ /usr/local/include/glib-2.0/glib/gprimes.h \
+ /usr/local/include/glib-2.0/glib/gqsort.h \
+ /usr/local/include/glib-2.0/glib/gqueue.h \
+ /usr/local/include/glib-2.0/glib/grand.h \
+ /usr/local/include/glib-2.0/glib/gregex.h \
+ /usr/local/include/glib-2.0/glib/gscanner.h \
+ /usr/local/include/glib-2.0/glib/gsequence.h \
+ /usr/local/include/glib-2.0/glib/gshell.h \
+ /usr/local/include/glib-2.0/glib/gslice.h \
+ /usr/local/include/glib-2.0/glib/gspawn.h \
+ /usr/local/include/glib-2.0/glib/gstrfuncs.h \
+ /usr/local/include/glib-2.0/glib/gstringchunk.h \
+ /usr/local/include/glib-2.0/glib/gtestutils.h \
+ /usr/local/include/glib-2.0/glib/gthreadpool.h \
+ /usr/local/include/glib-2.0/glib/gtimer.h \
+ /usr/local/include/glib-2.0/glib/gtrashstack.h \
+ /usr/local/include/glib-2.0/glib/gtree.h \
+ /usr/local/include/glib-2.0/glib/gurifuncs.h \
+ /usr/local/include/glib-2.0/glib/gvarianttype.h \
+ /usr/local/include/glib-2.0/glib/gvariant.h \
+ /usr/local/include/glib-2.0/glib/gversion.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gallocator.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gcache.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gcompletion.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gmain.h \
+ /usr/local/include/glib-2.0/glib/deprecated/grel.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gthread.h \
+ /usr/include/sys/types.h /usr/include/machine/endian.h \
+ /usr/include/x86/endian.h /usr/include/sys/_pthreadtypes.h \
+ /usr/include/sys/_stdint.h /usr/include/sys/select.h \
+ /usr/include/sys/_timeval.h /usr/include/pthread.h \
+ /usr/include/sched.h \
+ /usr/local/include/glib-2.0/glib/glib-autocleanups.h \
+ /usr/include/unistd.h /usr/include/sys/unistd.h wdfs-main.h config.h \
+ /usr/local/include/fuse/fuse.h /usr/local/include/fuse/fuse_common.h \
+ /usr/local/include/fuse/fuse_opt.h /usr/include/stdint.h \
+ /usr/include/machine/_stdint.h /usr/include/x86/_stdint.h \
+ /usr/local/include/fuse/fuse_common_compat.h /usr/include/fcntl.h \
+ /usr/include/utime.h /usr/include/sys/stat.h /usr/include/sys/time.h \
+ /usr/include/sys/statvfs.h /usr/include/sys/uio.h \
+ /usr/include/sys/_iovec.h /usr/local/include/fuse/fuse_compat.h \
+ /usr/local/include/neon/ne_basic.h \
+ /usr/local/include/neon/ne_request.h \
+ /usr/local/include/neon/ne_utils.h /usr/local/include/neon/ne_defs.h \
+ /usr/local/include/neon/ne_string.h /usr/local/include/neon/ne_alloc.h \
+ /usr/local/include/neon/ne_session.h /usr/local/include/neon/ne_ssl.h \
+ /usr/local/include/neon/ne_uri.h /usr/local/include/neon/ne_socket.h \
+ cache.h
+
+/usr/include/stdio.h:
+
+/usr/include/sys/cdefs.h:
+
+/usr/include/sys/_null.h:
+
+/usr/include/sys/_types.h:
+
+/usr/include/machine/_types.h:
+
+/usr/include/x86/_types.h:
+
+/usr/include/stdlib.h:
+
+/usr/include/string.h:
+
+/usr/include/strings.h:
+
+/usr/include/xlocale/_strings.h:
+
+/usr/include/xlocale/_string.h:
+
+/usr/include/assert.h:
+
+/usr/local/include/glib-2.0/glib.h:
+
+/usr/local/include/glib-2.0/glib/galloca.h:
+
+/usr/local/include/glib-2.0/glib/gtypes.h:
+
+/usr/local/lib/glib-2.0/include/glibconfig.h:
+
+/usr/local/include/glib-2.0/glib/gmacros.h:
+
+/usr/include/stddef.h:
+
+/usr/include/limits.h:
+
+/usr/include/sys/limits.h:
+
+/usr/include/machine/_limits.h:
+
+/usr/include/x86/_limits.h:
+
+/usr/include/sys/syslimits.h:
+
+/usr/include/float.h:
+
+/usr/include/x86/float.h:
+
+/usr/local/include/glib-2.0/glib/gversionmacros.h:
+
+/usr/include/time.h:
+
+/usr/include/sys/timespec.h:
+
+/usr/include/sys/_timespec.h:
+
+/usr/include/xlocale/_time.h:
+
+/usr/local/include/glib-2.0/glib/garray.h:
+
+/usr/local/include/glib-2.0/glib/gasyncqueue.h:
+
+/usr/local/include/glib-2.0/glib/gthread.h:
+
+/usr/local/include/glib-2.0/glib/gatomic.h:
+
+/usr/local/include/glib-2.0/glib/gerror.h:
+
+/usr/include/stdarg.h:
+
+/usr/include/x86/stdarg.h:
+
+/usr/local/include/glib-2.0/glib/gquark.h:
+
+/usr/local/include/glib-2.0/glib/gutils.h:
+
+/usr/local/include/glib-2.0/glib/gbacktrace.h:
+
+/usr/include/signal.h:
+
+/usr/include/sys/signal.h:
+
+/usr/include/sys/_sigset.h:
+
+/usr/include/machine/signal.h:
+
+/usr/include/x86/signal.h:
+
+/usr/include/machine/trap.h:
+
+/usr/include/x86/trap.h:
+
+/usr/local/include/glib-2.0/glib/gbase64.h:
+
+/usr/local/include/glib-2.0/glib/gbitlock.h:
+
+/usr/local/include/glib-2.0/glib/gbookmarkfile.h:
+
+/usr/local/include/glib-2.0/glib/gbytes.h:
+
+/usr/local/include/glib-2.0/glib/gcharset.h:
+
+/usr/local/include/glib-2.0/glib/gchecksum.h:
+
+/usr/local/include/glib-2.0/glib/gconvert.h:
+
+/usr/local/include/glib-2.0/glib/gdataset.h:
+
+/usr/local/include/glib-2.0/glib/gdate.h:
+
+/usr/local/include/glib-2.0/glib/gdatetime.h:
+
+/usr/local/include/glib-2.0/glib/gtimezone.h:
+
+/usr/local/include/glib-2.0/glib/gdir.h:
+
+/usr/include/dirent.h:
+
+/usr/include/sys/dirent.h:
+
+/usr/local/include/glib-2.0/glib/genviron.h:
+
+/usr/local/include/glib-2.0/glib/gfileutils.h:
+
+/usr/local/include/glib-2.0/glib/ggettext.h:
+
+/usr/local/include/glib-2.0/glib/ghash.h:
+
+/usr/local/include/glib-2.0/glib/glist.h:
+
+/usr/local/include/glib-2.0/glib/gmem.h:
+
+/usr/local/include/glib-2.0/glib/gnode.h:
+
+/usr/local/include/glib-2.0/glib/ghmac.h:
+
+/usr/local/include/glib-2.0/glib/ghook.h:
+
+/usr/local/include/glib-2.0/glib/ghostutils.h:
+
+/usr/local/include/glib-2.0/glib/giochannel.h:
+
+/usr/local/include/glib-2.0/glib/gmain.h:
+
+/usr/local/include/glib-2.0/glib/gpoll.h:
+
+/usr/local/include/glib-2.0/glib/gslist.h:
+
+/usr/local/include/glib-2.0/glib/gstring.h:
+
+/usr/local/include/glib-2.0/glib/gunicode.h:
+
+/usr/local/include/glib-2.0/glib/gkeyfile.h:
+
+/usr/local/include/glib-2.0/glib/gmappedfile.h:
+
+/usr/local/include/glib-2.0/glib/gmarkup.h:
+
+/usr/local/include/glib-2.0/glib/gmessages.h:
+
+/usr/local/include/glib-2.0/glib/goption.h:
+
+/usr/local/include/glib-2.0/glib/gpattern.h:
+
+/usr/local/include/glib-2.0/glib/gprimes.h:
+
+/usr/local/include/glib-2.0/glib/gqsort.h:
+
+/usr/local/include/glib-2.0/glib/gqueue.h:
+
+/usr/local/include/glib-2.0/glib/grand.h:
+
+/usr/local/include/glib-2.0/glib/gregex.h:
+
+/usr/local/include/glib-2.0/glib/gscanner.h:
+
+/usr/local/include/glib-2.0/glib/gsequence.h:
+
+/usr/local/include/glib-2.0/glib/gshell.h:
+
+/usr/local/include/glib-2.0/glib/gslice.h:
+
+/usr/local/include/glib-2.0/glib/gspawn.h:
+
+/usr/local/include/glib-2.0/glib/gstrfuncs.h:
+
+/usr/local/include/glib-2.0/glib/gstringchunk.h:
+
+/usr/local/include/glib-2.0/glib/gtestutils.h:
+
+/usr/local/include/glib-2.0/glib/gthreadpool.h:
+
+/usr/local/include/glib-2.0/glib/gtimer.h:
+
+/usr/local/include/glib-2.0/glib/gtrashstack.h:
+
+/usr/local/include/glib-2.0/glib/gtree.h:
+
+/usr/local/include/glib-2.0/glib/gurifuncs.h:
+
+/usr/local/include/glib-2.0/glib/gvarianttype.h:
+
+/usr/local/include/glib-2.0/glib/gvariant.h:
+
+/usr/local/include/glib-2.0/glib/gversion.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gallocator.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gcache.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gcompletion.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gmain.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/grel.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gthread.h:
+
+/usr/include/sys/types.h:
+
+/usr/include/machine/endian.h:
+
+/usr/include/x86/endian.h:
+
+/usr/include/sys/_pthreadtypes.h:
+
+/usr/include/sys/_stdint.h:
+
+/usr/include/sys/select.h:
+
+/usr/include/sys/_timeval.h:
+
+/usr/include/pthread.h:
+
+/usr/include/sched.h:
+
+/usr/local/include/glib-2.0/glib/glib-autocleanups.h:
+
+/usr/include/unistd.h:
+
+/usr/include/sys/unistd.h:
+
+wdfs-main.h:
+
+config.h:
+
+/usr/local/include/fuse/fuse.h:
+
+/usr/local/include/fuse/fuse_common.h:
+
+/usr/local/include/fuse/fuse_opt.h:
+
+/usr/include/stdint.h:
+
+/usr/include/machine/_stdint.h:
+
+/usr/include/x86/_stdint.h:
+
+/usr/local/include/fuse/fuse_common_compat.h:
+
+/usr/include/fcntl.h:
+
+/usr/include/utime.h:
+
+/usr/include/sys/stat.h:
+
+/usr/include/sys/time.h:
+
+/usr/include/sys/statvfs.h:
+
+/usr/include/sys/uio.h:
+
+/usr/include/sys/_iovec.h:
+
+/usr/local/include/fuse/fuse_compat.h:
+
+/usr/local/include/neon/ne_basic.h:
+
+/usr/local/include/neon/ne_request.h:
+
+/usr/local/include/neon/ne_utils.h:
+
+/usr/local/include/neon/ne_defs.h:
+
+/usr/local/include/neon/ne_string.h:
+
+/usr/local/include/neon/ne_alloc.h:
+
+/usr/local/include/neon/ne_session.h:
+
+/usr/local/include/neon/ne_ssl.h:
+
+/usr/local/include/neon/ne_uri.h:
+
+/usr/local/include/neon/ne_socket.h:
+
+cache.h:
diff --git a/src/.deps/svn.Po b/src/.deps/svn.Po
new file mode 100644
index 0000000..2f3c12c
--- /dev/null
+++ b/src/.deps/svn.Po
@@ -0,0 +1,418 @@
+svn.o: svn.c /usr/include/stdio.h /usr/include/sys/cdefs.h \
+ /usr/include/sys/_null.h /usr/include/sys/_types.h \
+ /usr/include/machine/_types.h /usr/include/x86/_types.h \
+ /usr/include/stdlib.h /usr/include/string.h /usr/include/strings.h \
+ /usr/include/xlocale/_strings.h /usr/include/xlocale/_string.h \
+ /usr/include/assert.h /usr/include/unistd.h /usr/include/sys/types.h \
+ /usr/include/machine/endian.h /usr/include/x86/endian.h \
+ /usr/include/sys/_pthreadtypes.h /usr/include/sys/_stdint.h \
+ /usr/include/sys/select.h /usr/include/sys/_sigset.h \
+ /usr/include/sys/_timeval.h /usr/include/sys/timespec.h \
+ /usr/include/sys/_timespec.h /usr/include/sys/unistd.h \
+ /usr/local/include/glib-2.0/glib.h \
+ /usr/local/include/glib-2.0/glib/galloca.h \
+ /usr/local/include/glib-2.0/glib/gtypes.h \
+ /usr/local/lib/glib-2.0/include/glibconfig.h \
+ /usr/local/include/glib-2.0/glib/gmacros.h /usr/include/stddef.h \
+ /usr/include/limits.h /usr/include/sys/limits.h \
+ /usr/include/machine/_limits.h /usr/include/x86/_limits.h \
+ /usr/include/sys/syslimits.h /usr/include/float.h \
+ /usr/include/x86/float.h \
+ /usr/local/include/glib-2.0/glib/gversionmacros.h /usr/include/time.h \
+ /usr/include/xlocale/_time.h /usr/local/include/glib-2.0/glib/garray.h \
+ /usr/local/include/glib-2.0/glib/gasyncqueue.h \
+ /usr/local/include/glib-2.0/glib/gthread.h \
+ /usr/local/include/glib-2.0/glib/gatomic.h \
+ /usr/local/include/glib-2.0/glib/gerror.h /usr/include/stdarg.h \
+ /usr/include/x86/stdarg.h /usr/local/include/glib-2.0/glib/gquark.h \
+ /usr/local/include/glib-2.0/glib/gutils.h \
+ /usr/local/include/glib-2.0/glib/gbacktrace.h /usr/include/signal.h \
+ /usr/include/sys/signal.h /usr/include/machine/signal.h \
+ /usr/include/x86/signal.h /usr/include/machine/trap.h \
+ /usr/include/x86/trap.h /usr/local/include/glib-2.0/glib/gbase64.h \
+ /usr/local/include/glib-2.0/glib/gbitlock.h \
+ /usr/local/include/glib-2.0/glib/gbookmarkfile.h \
+ /usr/local/include/glib-2.0/glib/gbytes.h \
+ /usr/local/include/glib-2.0/glib/gcharset.h \
+ /usr/local/include/glib-2.0/glib/gchecksum.h \
+ /usr/local/include/glib-2.0/glib/gconvert.h \
+ /usr/local/include/glib-2.0/glib/gdataset.h \
+ /usr/local/include/glib-2.0/glib/gdate.h \
+ /usr/local/include/glib-2.0/glib/gdatetime.h \
+ /usr/local/include/glib-2.0/glib/gtimezone.h \
+ /usr/local/include/glib-2.0/glib/gdir.h /usr/include/dirent.h \
+ /usr/include/sys/dirent.h /usr/local/include/glib-2.0/glib/genviron.h \
+ /usr/local/include/glib-2.0/glib/gfileutils.h \
+ /usr/local/include/glib-2.0/glib/ggettext.h \
+ /usr/local/include/glib-2.0/glib/ghash.h \
+ /usr/local/include/glib-2.0/glib/glist.h \
+ /usr/local/include/glib-2.0/glib/gmem.h \
+ /usr/local/include/glib-2.0/glib/gnode.h \
+ /usr/local/include/glib-2.0/glib/ghmac.h \
+ /usr/local/include/glib-2.0/glib/ghook.h \
+ /usr/local/include/glib-2.0/glib/ghostutils.h \
+ /usr/local/include/glib-2.0/glib/giochannel.h \
+ /usr/local/include/glib-2.0/glib/gmain.h \
+ /usr/local/include/glib-2.0/glib/gpoll.h \
+ /usr/local/include/glib-2.0/glib/gslist.h \
+ /usr/local/include/glib-2.0/glib/gstring.h \
+ /usr/local/include/glib-2.0/glib/gunicode.h \
+ /usr/local/include/glib-2.0/glib/gkeyfile.h \
+ /usr/local/include/glib-2.0/glib/gmappedfile.h \
+ /usr/local/include/glib-2.0/glib/gmarkup.h \
+ /usr/local/include/glib-2.0/glib/gmessages.h \
+ /usr/local/include/glib-2.0/glib/goption.h \
+ /usr/local/include/glib-2.0/glib/gpattern.h \
+ /usr/local/include/glib-2.0/glib/gprimes.h \
+ /usr/local/include/glib-2.0/glib/gqsort.h \
+ /usr/local/include/glib-2.0/glib/gqueue.h \
+ /usr/local/include/glib-2.0/glib/grand.h \
+ /usr/local/include/glib-2.0/glib/gregex.h \
+ /usr/local/include/glib-2.0/glib/gscanner.h \
+ /usr/local/include/glib-2.0/glib/gsequence.h \
+ /usr/local/include/glib-2.0/glib/gshell.h \
+ /usr/local/include/glib-2.0/glib/gslice.h \
+ /usr/local/include/glib-2.0/glib/gspawn.h \
+ /usr/local/include/glib-2.0/glib/gstrfuncs.h \
+ /usr/local/include/glib-2.0/glib/gstringchunk.h \
+ /usr/local/include/glib-2.0/glib/gtestutils.h \
+ /usr/local/include/glib-2.0/glib/gthreadpool.h \
+ /usr/local/include/glib-2.0/glib/gtimer.h \
+ /usr/local/include/glib-2.0/glib/gtrashstack.h \
+ /usr/local/include/glib-2.0/glib/gtree.h \
+ /usr/local/include/glib-2.0/glib/gurifuncs.h \
+ /usr/local/include/glib-2.0/glib/gvarianttype.h \
+ /usr/local/include/glib-2.0/glib/gvariant.h \
+ /usr/local/include/glib-2.0/glib/gversion.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gallocator.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gcache.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gcompletion.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gmain.h \
+ /usr/local/include/glib-2.0/glib/deprecated/grel.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gthread.h \
+ /usr/include/pthread.h /usr/include/sched.h \
+ /usr/local/include/glib-2.0/glib/glib-autocleanups.h \
+ /usr/local/include/neon/ne_props.h \
+ /usr/local/include/neon/ne_request.h \
+ /usr/local/include/neon/ne_utils.h /usr/local/include/neon/ne_defs.h \
+ /usr/local/include/neon/ne_string.h /usr/local/include/neon/ne_alloc.h \
+ /usr/local/include/neon/ne_session.h /usr/local/include/neon/ne_ssl.h \
+ /usr/local/include/neon/ne_uri.h /usr/local/include/neon/ne_socket.h \
+ /usr/local/include/neon/ne_207.h /usr/local/include/neon/ne_xml.h \
+ wdfs-main.h config.h /usr/local/include/fuse/fuse.h \
+ /usr/local/include/fuse/fuse_common.h \
+ /usr/local/include/fuse/fuse_opt.h /usr/include/stdint.h \
+ /usr/include/machine/_stdint.h /usr/include/x86/_stdint.h \
+ /usr/local/include/fuse/fuse_common_compat.h /usr/include/fcntl.h \
+ /usr/include/utime.h /usr/include/sys/stat.h /usr/include/sys/time.h \
+ /usr/include/sys/statvfs.h /usr/include/sys/uio.h \
+ /usr/include/sys/_iovec.h /usr/local/include/fuse/fuse_compat.h \
+ /usr/local/include/neon/ne_basic.h webdav.h svn.h
+
+/usr/include/stdio.h:
+
+/usr/include/sys/cdefs.h:
+
+/usr/include/sys/_null.h:
+
+/usr/include/sys/_types.h:
+
+/usr/include/machine/_types.h:
+
+/usr/include/x86/_types.h:
+
+/usr/include/stdlib.h:
+
+/usr/include/string.h:
+
+/usr/include/strings.h:
+
+/usr/include/xlocale/_strings.h:
+
+/usr/include/xlocale/_string.h:
+
+/usr/include/assert.h:
+
+/usr/include/unistd.h:
+
+/usr/include/sys/types.h:
+
+/usr/include/machine/endian.h:
+
+/usr/include/x86/endian.h:
+
+/usr/include/sys/_pthreadtypes.h:
+
+/usr/include/sys/_stdint.h:
+
+/usr/include/sys/select.h:
+
+/usr/include/sys/_sigset.h:
+
+/usr/include/sys/_timeval.h:
+
+/usr/include/sys/timespec.h:
+
+/usr/include/sys/_timespec.h:
+
+/usr/include/sys/unistd.h:
+
+/usr/local/include/glib-2.0/glib.h:
+
+/usr/local/include/glib-2.0/glib/galloca.h:
+
+/usr/local/include/glib-2.0/glib/gtypes.h:
+
+/usr/local/lib/glib-2.0/include/glibconfig.h:
+
+/usr/local/include/glib-2.0/glib/gmacros.h:
+
+/usr/include/stddef.h:
+
+/usr/include/limits.h:
+
+/usr/include/sys/limits.h:
+
+/usr/include/machine/_limits.h:
+
+/usr/include/x86/_limits.h:
+
+/usr/include/sys/syslimits.h:
+
+/usr/include/float.h:
+
+/usr/include/x86/float.h:
+
+/usr/local/include/glib-2.0/glib/gversionmacros.h:
+
+/usr/include/time.h:
+
+/usr/include/xlocale/_time.h:
+
+/usr/local/include/glib-2.0/glib/garray.h:
+
+/usr/local/include/glib-2.0/glib/gasyncqueue.h:
+
+/usr/local/include/glib-2.0/glib/gthread.h:
+
+/usr/local/include/glib-2.0/glib/gatomic.h:
+
+/usr/local/include/glib-2.0/glib/gerror.h:
+
+/usr/include/stdarg.h:
+
+/usr/include/x86/stdarg.h:
+
+/usr/local/include/glib-2.0/glib/gquark.h:
+
+/usr/local/include/glib-2.0/glib/gutils.h:
+
+/usr/local/include/glib-2.0/glib/gbacktrace.h:
+
+/usr/include/signal.h:
+
+/usr/include/sys/signal.h:
+
+/usr/include/machine/signal.h:
+
+/usr/include/x86/signal.h:
+
+/usr/include/machine/trap.h:
+
+/usr/include/x86/trap.h:
+
+/usr/local/include/glib-2.0/glib/gbase64.h:
+
+/usr/local/include/glib-2.0/glib/gbitlock.h:
+
+/usr/local/include/glib-2.0/glib/gbookmarkfile.h:
+
+/usr/local/include/glib-2.0/glib/gbytes.h:
+
+/usr/local/include/glib-2.0/glib/gcharset.h:
+
+/usr/local/include/glib-2.0/glib/gchecksum.h:
+
+/usr/local/include/glib-2.0/glib/gconvert.h:
+
+/usr/local/include/glib-2.0/glib/gdataset.h:
+
+/usr/local/include/glib-2.0/glib/gdate.h:
+
+/usr/local/include/glib-2.0/glib/gdatetime.h:
+
+/usr/local/include/glib-2.0/glib/gtimezone.h:
+
+/usr/local/include/glib-2.0/glib/gdir.h:
+
+/usr/include/dirent.h:
+
+/usr/include/sys/dirent.h:
+
+/usr/local/include/glib-2.0/glib/genviron.h:
+
+/usr/local/include/glib-2.0/glib/gfileutils.h:
+
+/usr/local/include/glib-2.0/glib/ggettext.h:
+
+/usr/local/include/glib-2.0/glib/ghash.h:
+
+/usr/local/include/glib-2.0/glib/glist.h:
+
+/usr/local/include/glib-2.0/glib/gmem.h:
+
+/usr/local/include/glib-2.0/glib/gnode.h:
+
+/usr/local/include/glib-2.0/glib/ghmac.h:
+
+/usr/local/include/glib-2.0/glib/ghook.h:
+
+/usr/local/include/glib-2.0/glib/ghostutils.h:
+
+/usr/local/include/glib-2.0/glib/giochannel.h:
+
+/usr/local/include/glib-2.0/glib/gmain.h:
+
+/usr/local/include/glib-2.0/glib/gpoll.h:
+
+/usr/local/include/glib-2.0/glib/gslist.h:
+
+/usr/local/include/glib-2.0/glib/gstring.h:
+
+/usr/local/include/glib-2.0/glib/gunicode.h:
+
+/usr/local/include/glib-2.0/glib/gkeyfile.h:
+
+/usr/local/include/glib-2.0/glib/gmappedfile.h:
+
+/usr/local/include/glib-2.0/glib/gmarkup.h:
+
+/usr/local/include/glib-2.0/glib/gmessages.h:
+
+/usr/local/include/glib-2.0/glib/goption.h:
+
+/usr/local/include/glib-2.0/glib/gpattern.h:
+
+/usr/local/include/glib-2.0/glib/gprimes.h:
+
+/usr/local/include/glib-2.0/glib/gqsort.h:
+
+/usr/local/include/glib-2.0/glib/gqueue.h:
+
+/usr/local/include/glib-2.0/glib/grand.h:
+
+/usr/local/include/glib-2.0/glib/gregex.h:
+
+/usr/local/include/glib-2.0/glib/gscanner.h:
+
+/usr/local/include/glib-2.0/glib/gsequence.h:
+
+/usr/local/include/glib-2.0/glib/gshell.h:
+
+/usr/local/include/glib-2.0/glib/gslice.h:
+
+/usr/local/include/glib-2.0/glib/gspawn.h:
+
+/usr/local/include/glib-2.0/glib/gstrfuncs.h:
+
+/usr/local/include/glib-2.0/glib/gstringchunk.h:
+
+/usr/local/include/glib-2.0/glib/gtestutils.h:
+
+/usr/local/include/glib-2.0/glib/gthreadpool.h:
+
+/usr/local/include/glib-2.0/glib/gtimer.h:
+
+/usr/local/include/glib-2.0/glib/gtrashstack.h:
+
+/usr/local/include/glib-2.0/glib/gtree.h:
+
+/usr/local/include/glib-2.0/glib/gurifuncs.h:
+
+/usr/local/include/glib-2.0/glib/gvarianttype.h:
+
+/usr/local/include/glib-2.0/glib/gvariant.h:
+
+/usr/local/include/glib-2.0/glib/gversion.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gallocator.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gcache.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gcompletion.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gmain.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/grel.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gthread.h:
+
+/usr/include/pthread.h:
+
+/usr/include/sched.h:
+
+/usr/local/include/glib-2.0/glib/glib-autocleanups.h:
+
+/usr/local/include/neon/ne_props.h:
+
+/usr/local/include/neon/ne_request.h:
+
+/usr/local/include/neon/ne_utils.h:
+
+/usr/local/include/neon/ne_defs.h:
+
+/usr/local/include/neon/ne_string.h:
+
+/usr/local/include/neon/ne_alloc.h:
+
+/usr/local/include/neon/ne_session.h:
+
+/usr/local/include/neon/ne_ssl.h:
+
+/usr/local/include/neon/ne_uri.h:
+
+/usr/local/include/neon/ne_socket.h:
+
+/usr/local/include/neon/ne_207.h:
+
+/usr/local/include/neon/ne_xml.h:
+
+wdfs-main.h:
+
+config.h:
+
+/usr/local/include/fuse/fuse.h:
+
+/usr/local/include/fuse/fuse_common.h:
+
+/usr/local/include/fuse/fuse_opt.h:
+
+/usr/include/stdint.h:
+
+/usr/include/machine/_stdint.h:
+
+/usr/include/x86/_stdint.h:
+
+/usr/local/include/fuse/fuse_common_compat.h:
+
+/usr/include/fcntl.h:
+
+/usr/include/utime.h:
+
+/usr/include/sys/stat.h:
+
+/usr/include/sys/time.h:
+
+/usr/include/sys/statvfs.h:
+
+/usr/include/sys/uio.h:
+
+/usr/include/sys/_iovec.h:
+
+/usr/local/include/fuse/fuse_compat.h:
+
+/usr/local/include/neon/ne_basic.h:
+
+webdav.h:
+
+svn.h:
diff --git a/src/.deps/wdfs-main.Po b/src/.deps/wdfs-main.Po
new file mode 100644
index 0000000..08dd8c7
--- /dev/null
+++ b/src/.deps/wdfs-main.Po
@@ -0,0 +1,428 @@
+wdfs-main.o: wdfs-main.c /usr/include/stdio.h /usr/include/sys/cdefs.h \
+ /usr/include/sys/_null.h /usr/include/sys/_types.h \
+ /usr/include/machine/_types.h /usr/include/x86/_types.h \
+ /usr/include/stdlib.h /usr/include/string.h /usr/include/strings.h \
+ /usr/include/xlocale/_strings.h /usr/include/xlocale/_string.h \
+ /usr/include/errno.h /usr/include/fcntl.h /usr/include/assert.h \
+ /usr/include/unistd.h /usr/include/sys/types.h \
+ /usr/include/machine/endian.h /usr/include/x86/endian.h \
+ /usr/include/sys/_pthreadtypes.h /usr/include/sys/_stdint.h \
+ /usr/include/sys/select.h /usr/include/sys/_sigset.h \
+ /usr/include/sys/_timeval.h /usr/include/sys/timespec.h \
+ /usr/include/sys/_timespec.h /usr/include/sys/unistd.h \
+ /usr/local/include/glib-2.0/glib.h \
+ /usr/local/include/glib-2.0/glib/galloca.h \
+ /usr/local/include/glib-2.0/glib/gtypes.h \
+ /usr/local/lib/glib-2.0/include/glibconfig.h \
+ /usr/local/include/glib-2.0/glib/gmacros.h /usr/include/stddef.h \
+ /usr/include/limits.h /usr/include/sys/limits.h \
+ /usr/include/machine/_limits.h /usr/include/x86/_limits.h \
+ /usr/include/sys/syslimits.h /usr/include/float.h \
+ /usr/include/x86/float.h \
+ /usr/local/include/glib-2.0/glib/gversionmacros.h /usr/include/time.h \
+ /usr/include/xlocale/_time.h /usr/local/include/glib-2.0/glib/garray.h \
+ /usr/local/include/glib-2.0/glib/gasyncqueue.h \
+ /usr/local/include/glib-2.0/glib/gthread.h \
+ /usr/local/include/glib-2.0/glib/gatomic.h \
+ /usr/local/include/glib-2.0/glib/gerror.h /usr/include/stdarg.h \
+ /usr/include/x86/stdarg.h /usr/local/include/glib-2.0/glib/gquark.h \
+ /usr/local/include/glib-2.0/glib/gutils.h \
+ /usr/local/include/glib-2.0/glib/gbacktrace.h /usr/include/signal.h \
+ /usr/include/sys/signal.h /usr/include/machine/signal.h \
+ /usr/include/x86/signal.h /usr/include/machine/trap.h \
+ /usr/include/x86/trap.h /usr/local/include/glib-2.0/glib/gbase64.h \
+ /usr/local/include/glib-2.0/glib/gbitlock.h \
+ /usr/local/include/glib-2.0/glib/gbookmarkfile.h \
+ /usr/local/include/glib-2.0/glib/gbytes.h \
+ /usr/local/include/glib-2.0/glib/gcharset.h \
+ /usr/local/include/glib-2.0/glib/gchecksum.h \
+ /usr/local/include/glib-2.0/glib/gconvert.h \
+ /usr/local/include/glib-2.0/glib/gdataset.h \
+ /usr/local/include/glib-2.0/glib/gdate.h \
+ /usr/local/include/glib-2.0/glib/gdatetime.h \
+ /usr/local/include/glib-2.0/glib/gtimezone.h \
+ /usr/local/include/glib-2.0/glib/gdir.h /usr/include/dirent.h \
+ /usr/include/sys/dirent.h /usr/local/include/glib-2.0/glib/genviron.h \
+ /usr/local/include/glib-2.0/glib/gfileutils.h \
+ /usr/local/include/glib-2.0/glib/ggettext.h \
+ /usr/local/include/glib-2.0/glib/ghash.h \
+ /usr/local/include/glib-2.0/glib/glist.h \
+ /usr/local/include/glib-2.0/glib/gmem.h \
+ /usr/local/include/glib-2.0/glib/gnode.h \
+ /usr/local/include/glib-2.0/glib/ghmac.h \
+ /usr/local/include/glib-2.0/glib/ghook.h \
+ /usr/local/include/glib-2.0/glib/ghostutils.h \
+ /usr/local/include/glib-2.0/glib/giochannel.h \
+ /usr/local/include/glib-2.0/glib/gmain.h \
+ /usr/local/include/glib-2.0/glib/gpoll.h \
+ /usr/local/include/glib-2.0/glib/gslist.h \
+ /usr/local/include/glib-2.0/glib/gstring.h \
+ /usr/local/include/glib-2.0/glib/gunicode.h \
+ /usr/local/include/glib-2.0/glib/gkeyfile.h \
+ /usr/local/include/glib-2.0/glib/gmappedfile.h \
+ /usr/local/include/glib-2.0/glib/gmarkup.h \
+ /usr/local/include/glib-2.0/glib/gmessages.h \
+ /usr/local/include/glib-2.0/glib/goption.h \
+ /usr/local/include/glib-2.0/glib/gpattern.h \
+ /usr/local/include/glib-2.0/glib/gprimes.h \
+ /usr/local/include/glib-2.0/glib/gqsort.h \
+ /usr/local/include/glib-2.0/glib/gqueue.h \
+ /usr/local/include/glib-2.0/glib/grand.h \
+ /usr/local/include/glib-2.0/glib/gregex.h \
+ /usr/local/include/glib-2.0/glib/gscanner.h \
+ /usr/local/include/glib-2.0/glib/gsequence.h \
+ /usr/local/include/glib-2.0/glib/gshell.h \
+ /usr/local/include/glib-2.0/glib/gslice.h \
+ /usr/local/include/glib-2.0/glib/gspawn.h \
+ /usr/local/include/glib-2.0/glib/gstrfuncs.h \
+ /usr/local/include/glib-2.0/glib/gstringchunk.h \
+ /usr/local/include/glib-2.0/glib/gtestutils.h \
+ /usr/local/include/glib-2.0/glib/gthreadpool.h \
+ /usr/local/include/glib-2.0/glib/gtimer.h \
+ /usr/local/include/glib-2.0/glib/gtrashstack.h \
+ /usr/local/include/glib-2.0/glib/gtree.h \
+ /usr/local/include/glib-2.0/glib/gurifuncs.h \
+ /usr/local/include/glib-2.0/glib/gvarianttype.h \
+ /usr/local/include/glib-2.0/glib/gvariant.h \
+ /usr/local/include/glib-2.0/glib/gversion.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gallocator.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gcache.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gcompletion.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gmain.h \
+ /usr/local/include/glib-2.0/glib/deprecated/grel.h \
+ /usr/local/include/glib-2.0/glib/deprecated/gthread.h \
+ /usr/include/pthread.h /usr/include/sched.h \
+ /usr/local/include/glib-2.0/glib/glib-autocleanups.h \
+ /usr/local/include/fuse/fuse_opt.h /usr/local/include/neon/ne_props.h \
+ /usr/local/include/neon/ne_request.h \
+ /usr/local/include/neon/ne_utils.h /usr/local/include/neon/ne_defs.h \
+ /usr/local/include/neon/ne_string.h /usr/local/include/neon/ne_alloc.h \
+ /usr/local/include/neon/ne_session.h /usr/local/include/neon/ne_ssl.h \
+ /usr/local/include/neon/ne_uri.h /usr/local/include/neon/ne_socket.h \
+ /usr/local/include/neon/ne_207.h /usr/local/include/neon/ne_xml.h \
+ /usr/local/include/neon/ne_dates.h \
+ /usr/local/include/neon/ne_redirect.h wdfs-main.h config.h \
+ /usr/local/include/fuse/fuse.h /usr/local/include/fuse/fuse_common.h \
+ /usr/include/stdint.h /usr/include/machine/_stdint.h \
+ /usr/include/x86/_stdint.h \
+ /usr/local/include/fuse/fuse_common_compat.h /usr/include/utime.h \
+ /usr/include/sys/stat.h /usr/include/sys/time.h \
+ /usr/include/sys/statvfs.h /usr/include/sys/uio.h \
+ /usr/include/sys/_iovec.h /usr/local/include/fuse/fuse_compat.h \
+ /usr/local/include/neon/ne_basic.h webdav.h cache.h svn.h
+
+/usr/include/stdio.h:
+
+/usr/include/sys/cdefs.h:
+
+/usr/include/sys/_null.h:
+
+/usr/include/sys/_types.h:
+
+/usr/include/machine/_types.h:
+
+/usr/include/x86/_types.h:
+
+/usr/include/stdlib.h:
+
+/usr/include/string.h:
+
+/usr/include/strings.h:
+
+/usr/include/xlocale/_strings.h:
+
+/usr/include/xlocale/_string.h:
+
+/usr/include/errno.h:
+
+/usr/include/fcntl.h:
+
+/usr/include/assert.h:
+
+/usr/include/unistd.h:
+
+/usr/include/sys/types.h:
+
+/usr/include/machine/endian.h:
+
+/usr/include/x86/endian.h:
+
+/usr/include/sys/_pthreadtypes.h:
+
+/usr/include/sys/_stdint.h:
+
+/usr/include/sys/select.h:
+
+/usr/include/sys/_sigset.h:
+
+/usr/include/sys/_timeval.h:
+
+/usr/include/sys/timespec.h:
+
+/usr/include/sys/_timespec.h:
+
+/usr/include/sys/unistd.h:
+
+/usr/local/include/glib-2.0/glib.h:
+
+/usr/local/include/glib-2.0/glib/galloca.h:
+
+/usr/local/include/glib-2.0/glib/gtypes.h:
+
+/usr/local/lib/glib-2.0/include/glibconfig.h:
+
+/usr/local/include/glib-2.0/glib/gmacros.h:
+
+/usr/include/stddef.h:
+
+/usr/include/limits.h:
+
+/usr/include/sys/limits.h:
+
+/usr/include/machine/_limits.h:
+
+/usr/include/x86/_limits.h:
+
+/usr/include/sys/syslimits.h:
+
+/usr/include/float.h:
+
+/usr/include/x86/float.h:
+
+/usr/local/include/glib-2.0/glib/gversionmacros.h:
+
+/usr/include/time.h:
+
+/usr/include/xlocale/_time.h:
+
+/usr/local/include/glib-2.0/glib/garray.h:
+
+/usr/local/include/glib-2.0/glib/gasyncqueue.h:
+
+/usr/local/include/glib-2.0/glib/gthread.h:
+
+/usr/local/include/glib-2.0/glib/gatomic.h:
+
+/usr/local/include/glib-2.0/glib/gerror.h:
+
+/usr/include/stdarg.h:
+
+/usr/include/x86/stdarg.h:
+
+/usr/local/include/glib-2.0/glib/gquark.h:
+
+/usr/local/include/glib-2.0/glib/gutils.h:
+
+/usr/local/include/glib-2.0/glib/gbacktrace.h:
+
+/usr/include/signal.h:
+
+/usr/include/sys/signal.h:
+
+/usr/include/machine/signal.h:
+
+/usr/include/x86/signal.h:
+
+/usr/include/machine/trap.h:
+
+/usr/include/x86/trap.h:
+
+/usr/local/include/glib-2.0/glib/gbase64.h:
+
+/usr/local/include/glib-2.0/glib/gbitlock.h:
+
+/usr/local/include/glib-2.0/glib/gbookmarkfile.h:
+
+/usr/local/include/glib-2.0/glib/gbytes.h:
+
+/usr/local/include/glib-2.0/glib/gcharset.h:
+
+/usr/local/include/glib-2.0/glib/gchecksum.h:
+
+/usr/local/include/glib-2.0/glib/gconvert.h:
+
+/usr/local/include/glib-2.0/glib/gdataset.h:
+
+/usr/local/include/glib-2.0/glib/gdate.h:
+
+/usr/local/include/glib-2.0/glib/gdatetime.h:
+
+/usr/local/include/glib-2.0/glib/gtimezone.h:
+
+/usr/local/include/glib-2.0/glib/gdir.h:
+
+/usr/include/dirent.h:
+
+/usr/include/sys/dirent.h:
+
+/usr/local/include/glib-2.0/glib/genviron.h:
+
+/usr/local/include/glib-2.0/glib/gfileutils.h:
+
+/usr/local/include/glib-2.0/glib/ggettext.h:
+
+/usr/local/include/glib-2.0/glib/ghash.h:
+
+/usr/local/include/glib-2.0/glib/glist.h:
+
+/usr/local/include/glib-2.0/glib/gmem.h:
+
+/usr/local/include/glib-2.0/glib/gnode.h:
+
+/usr/local/include/glib-2.0/glib/ghmac.h:
+
+/usr/local/include/glib-2.0/glib/ghook.h:
+
+/usr/local/include/glib-2.0/glib/ghostutils.h:
+
+/usr/local/include/glib-2.0/glib/giochannel.h:
+
+/usr/local/include/glib-2.0/glib/gmain.h:
+
+/usr/local/include/glib-2.0/glib/gpoll.h:
+
+/usr/local/include/glib-2.0/glib/gslist.h:
+
+/usr/local/include/glib-2.0/glib/gstring.h:
+
+/usr/local/include/glib-2.0/glib/gunicode.h:
+
+/usr/local/include/glib-2.0/glib/gkeyfile.h:
+
+/usr/local/include/glib-2.0/glib/gmappedfile.h:
+
+/usr/local/include/glib-2.0/glib/gmarkup.h:
+
+/usr/local/include/glib-2.0/glib/gmessages.h:
+
+/usr/local/include/glib-2.0/glib/goption.h:
+
+/usr/local/include/glib-2.0/glib/gpattern.h:
+
+/usr/local/include/glib-2.0/glib/gprimes.h:
+
+/usr/local/include/glib-2.0/glib/gqsort.h:
+
+/usr/local/include/glib-2.0/glib/gqueue.h:
+
+/usr/local/include/glib-2.0/glib/grand.h:
+
+/usr/local/include/glib-2.0/glib/gregex.h:
+
+/usr/local/include/glib-2.0/glib/gscanner.h:
+
+/usr/local/include/glib-2.0/glib/gsequence.h:
+
+/usr/local/include/glib-2.0/glib/gshell.h:
+
+/usr/local/include/glib-2.0/glib/gslice.h:
+
+/usr/local/include/glib-2.0/glib/gspawn.h:
+
+/usr/local/include/glib-2.0/glib/gstrfuncs.h:
+
+/usr/local/include/glib-2.0/glib/gstringchunk.h:
+
+/usr/local/include/glib-2.0/glib/gtestutils.h:
+
+/usr/local/include/glib-2.0/glib/gthreadpool.h:
+
+/usr/local/include/glib-2.0/glib/gtimer.h:
+
+/usr/local/include/glib-2.0/glib/gtrashstack.h:
+
+/usr/local/include/glib-2.0/glib/gtree.h:
+
+/usr/local/include/glib-2.0/glib/gurifuncs.h:
+
+/usr/local/include/glib-2.0/glib/gvarianttype.h:
+
+/usr/local/include/glib-2.0/glib/gvariant.h:
+
+/usr/local/include/glib-2.0/glib/gversion.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gallocator.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gcache.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gcompletion.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gmain.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/grel.h:
+
+/usr/local/include/glib-2.0/glib/deprecated/gthread.h:
+
+/usr/include/pthread.h:
+
+/usr/include/sched.h:
+
+/usr/local/include/glib-2.0/glib/glib-autocleanups.h:
+
+/usr/local/include/fuse/fuse_opt.h:
+
+/usr/local/include/neon/ne_props.h:
+
+/usr/local/include/neon/ne_request.h:
+
+/usr/local/include/neon/ne_utils.h:
+
+/usr/local/include/neon/ne_defs.h:
+
+/usr/local/include/neon/ne_string.h:
+
+/usr/local/include/neon/ne_alloc.h:
+
+/usr/local/include/neon/ne_session.h:
+
+/usr/local/include/neon/ne_ssl.h:
+
+/usr/local/include/neon/ne_uri.h:
+
+/usr/local/include/neon/ne_socket.h:
+
+/usr/local/include/neon/ne_207.h:
+
+/usr/local/include/neon/ne_xml.h:
+
+/usr/local/include/neon/ne_dates.h:
+
+/usr/local/include/neon/ne_redirect.h:
+
+wdfs-main.h:
+
+config.h:
+
+/usr/local/include/fuse/fuse.h:
+
+/usr/local/include/fuse/fuse_common.h:
+
+/usr/include/stdint.h:
+
+/usr/include/machine/_stdint.h:
+
+/usr/include/x86/_stdint.h:
+
+/usr/local/include/fuse/fuse_common_compat.h:
+
+/usr/include/utime.h:
+
+/usr/include/sys/stat.h:
+
+/usr/include/sys/time.h:
+
+/usr/include/sys/statvfs.h:
+
+/usr/include/sys/uio.h:
+
+/usr/include/sys/_iovec.h:
+
+/usr/local/include/fuse/fuse_compat.h:
+
+/usr/local/include/neon/ne_basic.h:
+
+webdav.h:
+
+cache.h:
+
+svn.h:
diff --git a/src/.deps/webdav.Po b/src/.deps/webdav.Po
new file mode 100644
index 0000000..4734e67
--- /dev/null
+++ b/src/.deps/webdav.Po
@@ -0,0 +1,160 @@
+webdav.o: webdav.c /usr/include/stdio.h /usr/include/sys/cdefs.h \
+ /usr/include/sys/_null.h /usr/include/sys/_types.h \
+ /usr/include/machine/_types.h /usr/include/x86/_types.h \
+ /usr/include/string.h /usr/include/strings.h \
+ /usr/include/xlocale/_strings.h /usr/include/xlocale/_string.h \
+ /usr/include/stdlib.h /usr/include/unistd.h /usr/include/sys/types.h \
+ /usr/include/machine/endian.h /usr/include/x86/endian.h \
+ /usr/include/sys/_pthreadtypes.h /usr/include/sys/_stdint.h \
+ /usr/include/sys/select.h /usr/include/sys/_sigset.h \
+ /usr/include/sys/_timeval.h /usr/include/sys/timespec.h \
+ /usr/include/sys/_timespec.h /usr/include/sys/unistd.h \
+ /usr/include/assert.h /usr/include/termios.h \
+ /usr/include/sys/_termios.h /usr/include/sys/ttycom.h \
+ /usr/include/sys/ioccom.h /usr/include/sys/ttydefaults.h \
+ /usr/local/include/neon/ne_basic.h \
+ /usr/local/include/neon/ne_request.h \
+ /usr/local/include/neon/ne_utils.h /usr/include/stdarg.h \
+ /usr/include/x86/stdarg.h /usr/local/include/neon/ne_defs.h \
+ /usr/local/include/neon/ne_string.h /usr/local/include/neon/ne_alloc.h \
+ /usr/local/include/neon/ne_session.h /usr/local/include/neon/ne_ssl.h \
+ /usr/local/include/neon/ne_uri.h /usr/local/include/neon/ne_socket.h \
+ /usr/local/include/neon/ne_auth.h /usr/local/include/neon/ne_locks.h \
+ /usr/local/include/neon/ne_redirect.h wdfs-main.h config.h \
+ /usr/local/include/fuse/fuse.h /usr/local/include/fuse/fuse_common.h \
+ /usr/local/include/fuse/fuse_opt.h /usr/include/stdint.h \
+ /usr/include/machine/_stdint.h /usr/include/x86/_stdint.h \
+ /usr/local/include/fuse/fuse_common_compat.h /usr/include/fcntl.h \
+ /usr/include/time.h /usr/include/xlocale/_time.h /usr/include/utime.h \
+ /usr/include/sys/stat.h /usr/include/sys/time.h \
+ /usr/include/sys/statvfs.h /usr/include/sys/uio.h \
+ /usr/include/sys/_iovec.h /usr/local/include/fuse/fuse_compat.h \
+ webdav.h
+
+/usr/include/stdio.h:
+
+/usr/include/sys/cdefs.h:
+
+/usr/include/sys/_null.h:
+
+/usr/include/sys/_types.h:
+
+/usr/include/machine/_types.h:
+
+/usr/include/x86/_types.h:
+
+/usr/include/string.h:
+
+/usr/include/strings.h:
+
+/usr/include/xlocale/_strings.h:
+
+/usr/include/xlocale/_string.h:
+
+/usr/include/stdlib.h:
+
+/usr/include/unistd.h:
+
+/usr/include/sys/types.h:
+
+/usr/include/machine/endian.h:
+
+/usr/include/x86/endian.h:
+
+/usr/include/sys/_pthreadtypes.h:
+
+/usr/include/sys/_stdint.h:
+
+/usr/include/sys/select.h:
+
+/usr/include/sys/_sigset.h:
+
+/usr/include/sys/_timeval.h:
+
+/usr/include/sys/timespec.h:
+
+/usr/include/sys/_timespec.h:
+
+/usr/include/sys/unistd.h:
+
+/usr/include/assert.h:
+
+/usr/include/termios.h:
+
+/usr/include/sys/_termios.h:
+
+/usr/include/sys/ttycom.h:
+
+/usr/include/sys/ioccom.h:
+
+/usr/include/sys/ttydefaults.h:
+
+/usr/local/include/neon/ne_basic.h:
+
+/usr/local/include/neon/ne_request.h:
+
+/usr/local/include/neon/ne_utils.h:
+
+/usr/include/stdarg.h:
+
+/usr/include/x86/stdarg.h:
+
+/usr/local/include/neon/ne_defs.h:
+
+/usr/local/include/neon/ne_string.h:
+
+/usr/local/include/neon/ne_alloc.h:
+
+/usr/local/include/neon/ne_session.h:
+
+/usr/local/include/neon/ne_ssl.h:
+
+/usr/local/include/neon/ne_uri.h:
+
+/usr/local/include/neon/ne_socket.h:
+
+/usr/local/include/neon/ne_auth.h:
+
+/usr/local/include/neon/ne_locks.h:
+
+/usr/local/include/neon/ne_redirect.h:
+
+wdfs-main.h:
+
+config.h:
+
+/usr/local/include/fuse/fuse.h:
+
+/usr/local/include/fuse/fuse_common.h:
+
+/usr/local/include/fuse/fuse_opt.h:
+
+/usr/include/stdint.h:
+
+/usr/include/machine/_stdint.h:
+
+/usr/include/x86/_stdint.h:
+
+/usr/local/include/fuse/fuse_common_compat.h:
+
+/usr/include/fcntl.h:
+
+/usr/include/time.h:
+
+/usr/include/xlocale/_time.h:
+
+/usr/include/utime.h:
+
+/usr/include/sys/stat.h:
+
+/usr/include/sys/time.h:
+
+/usr/include/sys/statvfs.h:
+
+/usr/include/sys/uio.h:
+
+/usr/include/sys/_iovec.h:
+
+/usr/local/include/fuse/fuse_compat.h:
+
+webdav.h:
diff --git a/src/Makefile b/src/Makefile
new file mode 100644
index 0000000..d59bdd0
--- /dev/null
+++ b/src/Makefile
@@ -0,0 +1,427 @@
+# Makefile.in generated by automake 1.9.6 from Makefile.am.
+# src/Makefile. Generated from Makefile.in by configure.
+
+# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
+# 2003, 2004, 2005 Free Software Foundation, Inc.
+# This Makefile.in is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+
+
+srcdir = .
+top_srcdir = ..
+
+pkgdatadir = $(datadir)/wdfs
+pkglibdir = $(libdir)/wdfs
+pkgincludedir = $(includedir)/wdfs
+top_builddir = ..
+am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
+INSTALL = /usr/bin/install -c
+install_sh_DATA = $(install_sh) -c -m 644
+install_sh_PROGRAM = $(install_sh) -c
+install_sh_SCRIPT = $(install_sh) -c
+INSTALL_HEADER = $(INSTALL_DATA)
+transform = $(program_transform_name)
+NORMAL_INSTALL = :
+PRE_INSTALL = :
+POST_INSTALL = :
+NORMAL_UNINSTALL = :
+PRE_UNINSTALL = :
+POST_UNINSTALL = :
+bin_PROGRAMS = wdfs$(EXEEXT)
+subdir = src
+DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \
+ $(srcdir)/config.h.in
+ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
+am__aclocal_m4_deps = $(top_srcdir)/configure.ac
+am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
+ $(ACLOCAL_M4)
+mkinstalldirs = $(install_sh) -d
+CONFIG_HEADER = config.h
+CONFIG_CLEAN_FILES =
+am__installdirs = "$(DESTDIR)$(bindir)"
+binPROGRAMS_INSTALL = $(INSTALL_PROGRAM)
+PROGRAMS = $(bin_PROGRAMS)
+am_wdfs_OBJECTS = cache.$(OBJEXT) svn.$(OBJEXT) wdfs-main.$(OBJEXT) \
+ webdav.$(OBJEXT)
+wdfs_OBJECTS = $(am_wdfs_OBJECTS)
+wdfs_LDADD = $(LDADD)
+DEFAULT_INCLUDES = -I. -I$(srcdir) -I.
+depcomp = $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe = depfiles
+COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
+ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+CCLD = $(CC)
+LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
+SOURCES = $(wdfs_SOURCES)
+DIST_SOURCES = $(wdfs_SOURCES)
+ETAGS = etags
+CTAGS = ctags
+DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+ACLOCAL = ${SHELL} /xj/waitman/wdfs/missing --run aclocal-1.9
+AMDEP_FALSE = #
+AMDEP_TRUE =
+AMTAR = ${SHELL} /xj/waitman/wdfs/missing --run tar
+AUTOCONF = ${SHELL} /xj/waitman/wdfs/missing --run autoconf
+AUTOHEADER = ${SHELL} /xj/waitman/wdfs/missing --run autoheader
+AUTOMAKE = ${SHELL} /xj/waitman/wdfs/missing --run automake-1.9
+AWK = nawk
+CC = cc
+CCDEPMODE = depmode=gcc3
+CFLAGS = -g -O2 -I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include -Wall -D_GNU_SOURCE -D_REENTRANT
+CPP = cc -E
+CPPFLAGS =
+CYGPATH_W = echo
+DEFS = -DHAVE_CONFIG_H
+DEPDIR = .deps
+ECHO_C =
+ECHO_N = -n
+ECHO_T =
+EGREP = /usr/bin/grep -E
+EXEEXT =
+GREP = /usr/bin/grep
+INSTALL_DATA = ${INSTALL} -m 644
+INSTALL_PROGRAM = ${INSTALL}
+INSTALL_SCRIPT = ${INSTALL}
+INSTALL_STRIP_PROGRAM = ${SHELL} $(install_sh) -c -s
+LDFLAGS =
+LIBOBJS =
+LIBS = -L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl
+LTLIBOBJS =
+MAKEINFO = ${SHELL} /xj/waitman/wdfs/missing --run makeinfo
+OBJEXT = o
+PACKAGE = wdfs
+PACKAGE_BUGREPORT = [email protected]
+PACKAGE_NAME = wdfs
+PACKAGE_STRING = wdfs 1.4.2
+PACKAGE_TARNAME = wdfs
+PACKAGE_VERSION = 1.4.2
+PATH_SEPARATOR = :
+PKG_CONFIG = /usr/local/bin/pkg-config
+SET_MAKE =
+SHELL = /bin/sh
+STRIP =
+VERSION = 1.4.2
+WDFS_CFLAGS = -I/usr/local/include/fuse -D_FILE_OFFSET_BITS=64 -I/usr/local/include/neon -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include
+WDFS_LIBS = -L/usr/local/lib -lfuse -pthread -lneon -lglib-2.0 -lintl
+ac_ct_CC =
+am__fastdepCC_FALSE = #
+am__fastdepCC_TRUE =
+am__include = include
+am__leading_dot = .
+am__quote =
+am__tar = ${AMTAR} chof - "$$tardir"
+am__untar = ${AMTAR} xf -
+bindir = ${exec_prefix}/bin
+build_alias =
+datadir = ${datarootdir}
+datarootdir = ${prefix}/share
+docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
+dvidir = ${docdir}
+exec_prefix = ${prefix}
+host_alias =
+htmldir = ${docdir}
+includedir = ${prefix}/include
+infodir = ${datarootdir}/info
+install_sh = /xj/waitman/wdfs/install-sh
+libdir = ${exec_prefix}/lib
+libexecdir = ${exec_prefix}/libexec
+localedir = ${datarootdir}/locale
+localstatedir = ${prefix}/var
+mandir = ${datarootdir}/man
+mkdir_p = $(install_sh) -d
+oldincludedir = /usr/include
+pdfdir = ${docdir}
+prefix = /usr/local
+program_transform_name = s,x,x,
+psdir = ${docdir}
+sbindir = ${exec_prefix}/sbin
+sharedstatedir = ${prefix}/com
+sysconfdir = ${prefix}/etc
+target_alias =
+wdfs_SOURCES = cache.c cache.h svn.c svn.h wdfs-main.c wdfs-main.h webdav.c webdav.h
+all: config.h
+ $(MAKE) $(AM_MAKEFLAGS) all-am
+
+.SUFFIXES:
+.SUFFIXES: .c .o .obj
+$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
+ @for dep in $?; do \
+ case '$(am__configure_deps)' in \
+ *$$dep*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
+ && exit 0; \
+ exit 1;; \
+ esac; \
+ done; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \
+ cd $(top_srcdir) && \
+ $(AUTOMAKE) --gnu src/Makefile
+.PRECIOUS: Makefile
+Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
+ @case '$?' in \
+ *config.status*) \
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
+ *) \
+ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
+ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
+ esac;
+
+$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+$(top_srcdir)/configure: $(am__configure_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(ACLOCAL_M4): $(am__aclocal_m4_deps)
+ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+
+config.h: stamp-h1
+ @if test ! -f $@; then \
+ rm -f stamp-h1; \
+ $(MAKE) stamp-h1; \
+ else :; fi
+
+stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status
+ @rm -f stamp-h1
+ cd $(top_builddir) && $(SHELL) ./config.status src/config.h
+$(srcdir)/config.h.in: $(am__configure_deps)
+ cd $(top_srcdir) && $(AUTOHEADER)
+ rm -f stamp-h1
+ touch $@
+
+distclean-hdr:
+ -rm -f config.h stamp-h1
+install-binPROGRAMS: $(bin_PROGRAMS)
+ @$(NORMAL_INSTALL)
+ test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)"
+ @list='$(bin_PROGRAMS)'; for p in $$list; do \
+ p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \
+ if test -f $$p \
+ ; then \
+ f=`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
+ echo " $(INSTALL_PROGRAM_ENV) $(binPROGRAMS_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
+ $(INSTALL_PROGRAM_ENV) $(binPROGRAMS_INSTALL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
+ else :; fi; \
+ done
+
+uninstall-binPROGRAMS:
+ @$(NORMAL_UNINSTALL)
+ @list='$(bin_PROGRAMS)'; for p in $$list; do \
+ f=`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \
+ echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
+ rm -f "$(DESTDIR)$(bindir)/$$f"; \
+ done
+
+clean-binPROGRAMS:
+ -test -z "$(bin_PROGRAMS)" || rm -f $(bin_PROGRAMS)
+wdfs$(EXEEXT): $(wdfs_OBJECTS) $(wdfs_DEPENDENCIES)
+ @rm -f wdfs$(EXEEXT)
+ $(LINK) $(wdfs_LDFLAGS) $(wdfs_OBJECTS) $(wdfs_LDADD) $(LIBS)
+
+mostlyclean-compile:
+ -rm -f *.$(OBJEXT)
+
+distclean-compile:
+ -rm -f *.tab.c
+
+include ./$(DEPDIR)/cache.Po
+include ./$(DEPDIR)/svn.Po
+include ./$(DEPDIR)/wdfs-main.Po
+include ./$(DEPDIR)/webdav.Po
+
+.c.o:
+ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
+ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+# source='$<' object='$@' libtool=no \
+# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
+# $(COMPILE) -c $<
+
+.c.obj:
+ if $(COMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
+ then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+# source='$<' object='$@' libtool=no \
+# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \
+# $(COMPILE) -c `$(CYGPATH_W) '$<'`
+uninstall-info-am:
+
+ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
+ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ mkid -fID $$unique
+tags: TAGS
+
+TAGS: $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+ test -n "$$unique" || unique=$$empty_fix; \
+ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+ $$tags $$unique; \
+ fi
+ctags: CTAGS
+CTAGS: $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \
+ $(TAGS_FILES) $(LISP)
+ tags=; \
+ here=`pwd`; \
+ list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \
+ unique=`for i in $$list; do \
+ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
+ done | \
+ $(AWK) ' { files[$$0] = 1; } \
+ END { for (i in files) print i; }'`; \
+ test -z "$(CTAGS_ARGS)$$tags$$unique" \
+ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
+ $$tags $$unique
+
+GTAGS:
+ here=`$(am__cd) $(top_builddir) && pwd` \
+ && cd $(top_srcdir) \
+ && gtags -i $(GTAGS_ARGS) $$here
+
+distclean-tags:
+ -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
+
+distdir: $(DISTFILES)
+ @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+ list='$(DISTFILES)'; for file in $$list; do \
+ case $$file in \
+ $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+ $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+ esac; \
+ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+ dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+ if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+ dir="/$$dir"; \
+ $(mkdir_p) "$(distdir)$$dir"; \
+ else \
+ dir=''; \
+ fi; \
+ if test -d $$d/$$file; then \
+ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+ fi; \
+ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+ else \
+ test -f $(distdir)/$$file \
+ || cp -p $$d/$$file $(distdir)/$$file \
+ || exit 1; \
+ fi; \
+ done
+check-am: all-am
+check: check-am
+all-am: Makefile $(PROGRAMS) config.h
+installdirs:
+ for dir in "$(DESTDIR)$(bindir)"; do \
+ test -z "$$dir" || $(mkdir_p) "$$dir"; \
+ done
+install: install-am
+install-exec: install-exec-am
+install-data: install-data-am
+uninstall: uninstall-am
+
+install-am: all-am
+ @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
+
+installcheck: installcheck-am
+install-strip:
+ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
+ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
+ `test -z '$(STRIP)' || \
+ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
+mostlyclean-generic:
+
+clean-generic:
+
+distclean-generic:
+ -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+
+maintainer-clean-generic:
+ @echo "This command is intended for maintainers to use"
+ @echo "it deletes files that may require special tools to rebuild."
+clean: clean-am
+
+clean-am: clean-binPROGRAMS clean-generic mostlyclean-am
+
+distclean: distclean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+distclean-am: clean-am distclean-compile distclean-generic \
+ distclean-hdr distclean-tags
+
+dvi: dvi-am
+
+dvi-am:
+
+html: html-am
+
+info: info-am
+
+info-am:
+
+install-data-am:
+
+install-exec-am: install-binPROGRAMS
+
+install-info: install-info-am
+
+install-man:
+
+installcheck-am:
+
+maintainer-clean: maintainer-clean-am
+ -rm -rf ./$(DEPDIR)
+ -rm -f Makefile
+maintainer-clean-am: distclean-am maintainer-clean-generic
+
+mostlyclean: mostlyclean-am
+
+mostlyclean-am: mostlyclean-compile mostlyclean-generic
+
+pdf: pdf-am
+
+pdf-am:
+
+ps: ps-am
+
+ps-am:
+
+uninstall-am: uninstall-binPROGRAMS uninstall-info-am
+
+.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \
+ clean-generic ctags distclean distclean-compile \
+ distclean-generic distclean-hdr distclean-tags distdir dvi \
+ dvi-am html html-am info info-am install install-am \
+ install-binPROGRAMS install-data install-data-am install-exec \
+ install-exec-am install-info install-info-am install-man \
+ install-strip installcheck installcheck-am installdirs \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-compile mostlyclean-generic pdf pdf-am ps ps-am \
+ tags uninstall uninstall-am uninstall-binPROGRAMS \
+ uninstall-info-am
+
+
+# this flag is set via "#define FUSE_USE_VERSION XY" in wdfs-main.c
+# wdfs_CPPFLAGS = -DFUSE_USE_VERSION=
+
+# eof
+# Tell versions [3.59,3.63) of GNU make to not export all variables.
+# Otherwise a system limit (for SysV at least) may be exceeded.
+.NOEXPORT:
diff --git a/src/config.h b/src/config.h
new file mode 100644
index 0000000..bf10206
--- /dev/null
+++ b/src/config.h
@@ -0,0 +1,59 @@
+/* src/config.h. Generated from config.h.in by configure. */
+/* src/config.h.in. Generated from configure.ac by autoheader. */
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the <pthread.h> header file. */
+#define HAVE_PTHREAD_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strndup' function. */
+#define HAVE_STRNDUP 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Name of package */
+#define PACKAGE "wdfs"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "[email protected]"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "wdfs"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "wdfs 1.4.2"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "wdfs"
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "1.4.2"
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Version number of package */
+#define VERSION "1.4.2"
diff --git a/src/stamp-h1 b/src/stamp-h1
new file mode 100644
index 0000000..57ea58e
--- /dev/null
+++ b/src/stamp-h1
@@ -0,0 +1 @@
+timestamp for src/config.h
diff --git a/src/wdfs-main.c b/src/wdfs-main.c
index 9bd5244..98917b3 100644
--- a/src/wdfs-main.c
+++ b/src/wdfs-main.c
@@ -1,1401 +1,1436 @@
/*
* this file is part of wdfs --> http://noedler.de/projekte/wdfs/
*
* wdfs is a webdav filesystem with special features for accessing subversion
* repositories. it is based on fuse v2.5+ and neon v0.24.7+.
*
* copyright (c) 2005 - 2007 jens m. noedler, [email protected]
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* This program is released under the GPL with the additional exemption
* that compiling, linking and/or using OpenSSL is allowed.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <assert.h>
#include <unistd.h>
#include <glib.h>
#include <fuse_opt.h>
#include <ne_props.h>
#include <ne_dates.h>
#include <ne_redirect.h>
#include "wdfs-main.h"
#include "webdav.h"
#include "cache.h"
#include "svn.h"
/* there are four locking modes available. the simple locking mode locks a file
* on open()ing it and unlocks it on close()ing the file. the advanced mode
* prevents data curruption by locking the file on open() and holds the lock
* until the file was writen and closed or the lock timed out. the eternity
* mode holds the lock until wdfs is unmounted or the lock times out. the last
* mode is to do no locking at all which is the default behaviour. */
#define NO_LOCK 0
#define SIMPLE_LOCK 1
#define ADVANCED_LOCK 2
#define ETERNITY_LOCK 3
static void print_help();
static int call_fuse_main(struct fuse_args *args);
+static int wdfs_mknod(const char *localpath, mode_t mode, dev_t rdev);
+static int wdfs_open(const char *localpath, struct fuse_file_info *fi);
+
/* define package name and version if config.h is not available. */
#ifndef HAVE_CONFIG_H
#define PACKAGE_NAME "wdfs"
#define PACKAGE_VERSION "unknown"
#endif
/* product string according RFC 2616, that is included in every request. */
const char *project_name = PACKAGE_NAME"/"PACKAGE_VERSION;
/* homepage of this filesystem */
const char *project_uri = "http://noedler.de/projekte/wdfs/";
/* init settings with default values */
struct wdfs_conf wdfs = {
.debug = false,
.accept_certificate = false,
.username = NULL,
.password = NULL,
.redirect = true,
.svn_mode = false,
.locking_mode = NO_LOCK,
.locking_timeout = 300,
.webdav_resource = NULL,
};
enum {
KEY_HELP,
KEY_VERSION,
KEY_VERSION_FULL,
KEY_DEBUG,
KEY_LOCKING_MODE,
KEY_NOOP,
};
#define WDFS_OPT(t, p, v) { t, offsetof(struct wdfs_conf, p), v }
static struct fuse_opt wdfs_opts[] = {
FUSE_OPT_KEY("-h", KEY_HELP),
FUSE_OPT_KEY("--help", KEY_HELP),
FUSE_OPT_KEY("-v", KEY_VERSION),
FUSE_OPT_KEY("--version", KEY_VERSION),
FUSE_OPT_KEY("-vv", KEY_VERSION_FULL),
FUSE_OPT_KEY("--all-versions", KEY_VERSION_FULL),
FUSE_OPT_KEY("-D", KEY_DEBUG),
FUSE_OPT_KEY("wdfs_debug", KEY_DEBUG),
FUSE_OPT_KEY("-m %u", KEY_LOCKING_MODE),
FUSE_OPT_KEY("-a", KEY_NOOP),
WDFS_OPT("-D", debug, true),
WDFS_OPT("wdfs_debug", debug, true),
WDFS_OPT("-ac", accept_certificate, true),
WDFS_OPT("accept_sslcert", accept_certificate, true),
WDFS_OPT("-u %s", username, 0),
WDFS_OPT("username=%s", username, 0),
WDFS_OPT("-p %s", password, 0),
WDFS_OPT("password=%s", password, 0),
WDFS_OPT("no_redirect", redirect, false),
WDFS_OPT("-S", svn_mode, true),
WDFS_OPT("svn_mode", svn_mode, true),
WDFS_OPT("-l", locking_mode, SIMPLE_LOCK),
WDFS_OPT("locking", locking_mode, SIMPLE_LOCK),
WDFS_OPT("locking=0", locking_mode, NO_LOCK),
WDFS_OPT("locking=none", locking_mode, NO_LOCK),
WDFS_OPT("locking=1", locking_mode, SIMPLE_LOCK),
WDFS_OPT("locking=simple", locking_mode, SIMPLE_LOCK),
WDFS_OPT("locking=2", locking_mode, ADVANCED_LOCK),
WDFS_OPT("locking=advanced", locking_mode, ADVANCED_LOCK),
WDFS_OPT("locking=3", locking_mode, ETERNITY_LOCK),
WDFS_OPT("locking=eternity", locking_mode, ETERNITY_LOCK),
WDFS_OPT("-t %u", locking_timeout, 300),
WDFS_OPT("locking_timeout=%u", locking_timeout, 300),
FUSE_OPT_END
};
static int wdfs_opt_proc(
void *data, const char *option, int key, struct fuse_args *option_list)
{
switch (key) {
case KEY_HELP:
print_help();
fuse_opt_add_arg(option_list, "-ho");
call_fuse_main(option_list);
exit(1);
case KEY_VERSION:
fprintf(stderr, "%s version: %s\n", PACKAGE_NAME, PACKAGE_VERSION);
exit(0);
case KEY_VERSION_FULL:
fprintf(stderr, "%s version: %s\n", PACKAGE_NAME, PACKAGE_VERSION);
fprintf(stderr, "%s homepage: %s\n", PACKAGE_NAME, project_uri);
fprintf(stderr, "neon version: 0.%d\n", NEON_VERSION);
fuse_opt_add_arg(option_list, "--version");
call_fuse_main(option_list);
exit(0);
case KEY_DEBUG:
return fuse_opt_add_arg(option_list, "-f");
case KEY_LOCKING_MODE:
if (option[3] != '\0' || option[2] < '0' || option[2] > '3') {
fprintf(stderr, "%s: unknown locking mode '%s'\n",
wdfs.program_name, option + 2);
exit(1);
} else {
wdfs.locking_mode = option[2] - '0';
}
return 0;
case KEY_NOOP:
return 0;
case FUSE_OPT_KEY_NONOPT:
if (wdfs.webdav_resource == NULL &&
strncmp(option, "http", 4) == 0) {
wdfs.webdav_resource = strdup(option);
return 0;
}
return 1;
case FUSE_OPT_KEY_OPT:
return 1;
default:
fprintf(stderr, "%s: unknown option '%s'\n",
wdfs.program_name, option);
exit(1);
}
}
/* webdav server base directory. if you are connected to "http://server/dir/"
* remotepath_basedir is set to "/dir" (starting slash, no ending slash).
* if connected to the root directory (http://server/) it will be set to "". */
char *remotepath_basedir;
/* infos about an open file. used by open(), read(), write() and release() */
struct open_file {
unsigned long fh; /* this file's filehandle */
bool_t modified; /* set true if the filehandle's content is modified */
};
/* webdav properties used to get file attributes */
static const ne_propname properties_fileattr[] = {
{ "DAV:", "resourcetype" },
{ "DAV:", "getcontentlength" },
{ "DAV:", "getlastmodified" },
{ "DAV:", "creationdate" },
{ NULL } /* MUST be NULL terminated! */
};
/* +++ exported method +++ */
/* free()s each char passed that is not NULL and sets it to NULL after freeing */
void free_chars(char **arg, ...)
{
va_list ap;
va_start(ap, arg);
while (arg) {
if (*arg != NULL)
free(*arg);
*arg = NULL;
/* get the next parameter */
arg = va_arg(ap, char **);
}
va_end(ap);
}
/* removes all trailing slashes from the path.
* returns the new malloc()d path or NULL on error. */
char* remove_ending_slashes(const char *path)
{
char *new_path = strdup(path);
int pos = strlen(path) - 1;
while(pos >= 0 && new_path[pos] == '/')
new_path[pos--] = '\0';
return new_path;
}
/* unifies the given path by removing the ending slash and escaping or
* unescaping the path. returns the new malloc()d string or NULL on error. */
char* unify_path(const char *path_in, int mode)
{
assert(path_in);
char *path_tmp, *path_out = NULL;
path_tmp = strdup(path_in);
if (path_tmp == NULL)
return NULL;
/* some servers send the complete URI not only the path.
* hence remove the server part and use the path only.
* example1: before: "https://server.com/path/to/hell/"
* after: "/path/to/hell/"
* example2: before: "http://server.com"
* after: "" */
if (g_str_has_prefix(path_tmp, "http")) {
char *tmp0 = strdup(path_in);
FREE(path_tmp);
/* jump to the 1st '/' of http[s]:// */
char *tmp1 = strchr(tmp0, '/');
/* jump behind '//' and get the next '/'. voila: the path! */
char *tmp2 = strchr(tmp1 + 2, '/');
if (tmp2 == NULL)
path_tmp = strdup("");
else
path_tmp = strdup(tmp2);
FREE(tmp0);
}
if (mode & LEAVESLASH) {
mode &= ~LEAVESLASH;
} else {
path_tmp = remove_ending_slashes(path_tmp);
}
if (path_tmp == NULL)
return NULL;
switch (mode) {
case ESCAPE:
path_out = ne_path_escape(path_tmp);
break;
case UNESCAPE:
path_out = ne_path_unescape(path_tmp);
break;
default:
fprintf(stderr, "## fatal error: unknown mode in %s()\n", __func__);
exit(1);
}
FREE(path_tmp);
if (path_out == NULL)
return NULL;
return path_out;
}
/* mac os x lacks support for strndup() because it's a gnu extension.
* be gentle to the apples and define the required method. */
#ifndef HAVE_STRNDUP
char* strndup(const char *str, size_t len1)
{
size_t len2 = strlen(str);
if (len1 < len2)
len2 = len1;
char *result = (char *)malloc(len2 + 1);
if (result == NULL)
return NULL;
result[len2] = '\0';
return (char *)memcpy(result, str, len2);
}
#endif
/* +++ helper methods +++ */
/* this method prints some debug output and sets the http user agent string to
* a more informative value. */
static void print_debug_infos(const char *method, const char *parameter)
{
assert(method);
fprintf(stderr, ">> %s(%s)\n", method, parameter);
char *useragent =
ne_concat(project_name, " ", method, "(", parameter, ")", NULL);
ne_set_useragent(session, useragent);
FREE(useragent);
}
/* returns the malloc()ed escaped remotepath on success or NULL on error */
static char* get_remotepath(const char *localpath)
{
assert(localpath);
char *remotepath = ne_concat(remotepath_basedir, localpath, NULL);
if (remotepath == NULL)
return NULL;
char *remotepath2 = unify_path(remotepath, ESCAPE | LEAVESLASH);
FREE(remotepath);
if (remotepath2 == NULL)
return NULL;
return remotepath2;
}
/* returns a filehandle for read and write on success or -1 on error */
static int get_filehandle()
{
char dummyfile[] = "/tmp/wdfs-tmp-XXXXXX";
/* mkstemp() replaces XXXXXX by unique random chars and
* returns a filehandle for reading and writing */
int fh = mkstemp(dummyfile);
if (fh == -1)
fprintf(stderr, "## mkstemp(%s) error\n", dummyfile);
if (unlink(dummyfile))
fprintf(stderr, "## unlink() error\n");
return fh;
}
/* evaluates the propfind result set and sets the file's attributes (stat) */
static void set_stat(struct stat* stat, const ne_prop_result_set *results)
{
if (wdfs.debug == true)
print_debug_infos(__func__, "");
const char *resourcetype, *contentlength, *lastmodified, *creationdate;
assert(stat && results);
memset(stat, 0, sizeof(struct stat));
/* get the values from the propfind result set */
resourcetype = ne_propset_value(results, &properties_fileattr[0]);
contentlength = ne_propset_value(results, &properties_fileattr[1]);
lastmodified = ne_propset_value(results, &properties_fileattr[2]);
creationdate = ne_propset_value(results, &properties_fileattr[3]);
/* webdav collection == directory entry */
if (resourcetype != NULL && !strstr("<collection", resourcetype)) {
/* "DT_DIR << 12" equals "S_IFDIR" */
stat->st_mode = S_IFDIR | 0777;
stat->st_size = 4096;
} else {
stat->st_mode = S_IFREG | 0666;
if (contentlength != NULL)
stat->st_size = atoll(contentlength);
else
stat->st_size = 0;
}
stat->st_nlink = 1;
stat->st_atime = time(NULL);
if (lastmodified != NULL)
stat->st_mtime = ne_rfc1123_parse(lastmodified);
else
stat->st_mtime = 0;
if (creationdate != NULL)
stat->st_ctime = ne_iso8601_parse(creationdate);
else
stat->st_ctime = 0;
/* calculate number of 512 byte blocks */
stat->st_blocks = (stat->st_size + 511) / 512;
/* no need to set a restrict mode, because fuse filesystems can
* only be accessed by the user that mounted the filesystem. */
stat->st_mode &= ~umask(0);
stat->st_uid = getuid();
stat->st_gid = getgid();
}
/* this method is invoked, if a redirect needs to be done. therefore the current
* remotepath is freed and set to the redirect target. returns -1 and prints an
* error if the current host and new host differ. returns 0 on success and -1
* on error. side effect: remotepath is freed on error. */
static int handle_redirect(char **remotepath)
{
if (wdfs.debug == true)
print_debug_infos(__func__, *remotepath);
/* free the old value of remotepath, because it's no longer needed */
FREE(*remotepath);
/* get the current_uri and new_uri structs */
ne_uri current_uri;
ne_fill_server_uri(session, ¤t_uri);
const ne_uri *new_uri = ne_redirect_location(session);
if (strcasecmp(current_uri.host, new_uri->host)) {
fprintf(stderr,
"## error: wdfs does not support redirecting to another host!\n");
free_chars(¤t_uri.host, ¤t_uri.scheme, NULL);
return -1;
}
/* can't use ne_uri_free() here, because only host and scheme are mallocd */
free_chars(¤t_uri.host, ¤t_uri.scheme, NULL);
/* set the new remotepath to the redirect target path */
*remotepath = ne_strdup(new_uri->path);
return 0;
}
/* +++ fuse callback methods +++ */
/* this method is called by ne_simple_propfind() from wdfs_getattr() for a
* specific file. it sets the file's attributes and and them to the cache. */
static void wdfs_getattr_propfind_callback(
#if NEON_VERSION >= 26
void *userdata, const ne_uri* href_uri, const ne_prop_result_set *results)
#else
void *userdata, const char *remotepath, const ne_prop_result_set *results)
#endif
{
#if NEON_VERSION >= 26
char *remotepath = ne_uri_unparse(href_uri);
#endif
if (wdfs.debug == true)
print_debug_infos(__func__, remotepath);
struct stat *stat = (struct stat*)userdata;
memset(stat, 0, sizeof(struct stat));
assert(stat && remotepath);
set_stat(stat, results);
cache_add_item(stat, remotepath);
#if NEON_VERSION >= 26
FREE(remotepath);
#endif
}
/* this method returns the file attributes (stat) for a requested file either
* from the cache or directly from the webdav server by performing a propfind
* request. */
static int wdfs_getattr(const char *localpath, struct stat *stat)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath && stat);
char *remotepath;
/* for details about the svn_mode, please have a look at svn.c */
/* get the stat for the svn_basedir, if localpath equals svn_basedir. */
if (wdfs.svn_mode == true && !strcmp(localpath, svn_basedir)) {
*stat = svn_get_static_dir_stat();
return 0;
}
/* if svn_mode is enabled and string localpath starts with svn_basedir... */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir)) {
/* ...get stat for the level 1 directories... */
if (svn_get_level1_stat(stat, localpath) == 0) {
return 0;
/* ...or get remotepath and go on. */
} else {
remotepath = svn_get_remotepath(localpath);
}
/* normal mode; no svn mode */
} else {
remotepath = get_remotepath(localpath);
}
if (remotepath == NULL)
return -ENOMEM;
+
/* stat not found in the cache? perform a propfind to get stat! */
if (cache_get_item(stat, remotepath)) {
int ret = ne_simple_propfind(
session, remotepath, NE_DEPTH_ZERO, properties_fileattr,
wdfs_getattr_propfind_callback, stat);
/* handle the redirect and retry the propfind with the new target */
if (ret == NE_REDIRECT && wdfs.redirect == true) {
if (handle_redirect(&remotepath))
return -ENOENT;
ret = ne_simple_propfind(
session, remotepath, NE_DEPTH_ZERO, properties_fileattr,
wdfs_getattr_propfind_callback, stat);
}
+
if (ret != NE_OK) {
fprintf(stderr, "## PROPFIND error in %s(): %s\n",
__func__, ne_get_error(session));
+
FREE(remotepath);
return -ENOENT;
}
}
FREE(remotepath);
return 0;
}
/* this method is called by ne_simple_propfind() from wdfs_readdir() for each
* member (file) of the requested collection. this method extracts the file's
* attributes from the webdav response, adds it to the cache and calls the fuse
* filler method to add the file to the requested directory. */
static void wdfs_readdir_propfind_callback(
#if NEON_VERSION >= 26
void *userdata, const ne_uri* href_uri, const ne_prop_result_set *results)
#else
void *userdata, const char *remotepath0, const ne_prop_result_set *results)
#endif
{
#if NEON_VERSION >= 26
char *remotepath = ne_uri_unparse(href_uri);
#else
char *remotepath = strdup(remotepath0);
#endif
if (wdfs.debug == true)
print_debug_infos(__func__, remotepath);
struct dir_item *item_data = (struct dir_item*)userdata;
assert(item_data);
char *remotepath1 = unify_path(remotepath, UNESCAPE);
char *remotepath2 = unify_path(item_data->remotepath, UNESCAPE);
if (remotepath1 == NULL || remotepath2 == NULL) {
free_chars(&remotepath, &remotepath1, &remotepath2, NULL);
fprintf(stderr, "## fatal error: unify_path() returned NULL\n");
return;
}
/* don't add this directory to itself */
if (!strcmp(remotepath2, remotepath1)) {
free_chars(&remotepath, &remotepath1, &remotepath2, NULL);
return;
}
/* extract filename from the path. it's the string behind the last '/'. */
char *filename = strrchr(remotepath1, '/');
filename++;
/* set this file's attributes. the "ne_prop_result_set *results" contains
* the file attributes of all files of this collection (directory). this
* performs better then single requests for each file in getattr(). */
struct stat stat;
set_stat(&stat, results);
/* add this file's attributes to the cache */
cache_add_item(&stat, remotepath1);
/* add directory entry */
if (item_data->filler(item_data->buf, filename, &stat, 0))
fprintf(stderr, "## filler() error in %s()!\n", __func__);
free_chars(&remotepath, &remotepath1, &remotepath2, NULL);
}
/* this method adds the files to the requested directory using the webdav method
* propfind. the server responds with status code 207 that contains metadata of
* all files of the requested collection. for each file the method
* wdfs_readdir_propfind_callback() is called. */
static int wdfs_readdir(
const char *localpath, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath && filler);
struct dir_item item_data;
item_data.buf = buf;
item_data.filler = filler;
/* for details about the svn_mode, please have a look at svn.c */
/* if svn_mode is enabled, add svn_basedir to root */
if (wdfs.svn_mode == true && !strcmp(localpath, "/")) {
filler(buf, svn_basedir + 1, NULL, 0);
}
/* if svn_mode is enabled, add level 1 directories to svn_basedir */
if (wdfs.svn_mode == true && !strcmp(localpath, svn_basedir)) {
svn_add_level1_directories(&item_data);
return 0;
}
/* if svn_mode is enabled and string localpath starts with svn_basedir... */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir)) {
/* ... add level 2 directories and return... */
if (svn_add_level2_directories(&item_data, localpath) == 0) {
return 0;
/* ...or get remote path and go on */
} else {
item_data.remotepath = svn_get_remotepath(localpath);
}
/* normal mode; no svn mode */
} else {
item_data.remotepath = get_remotepath(localpath);
}
if (item_data.remotepath == NULL)
return -ENOMEM;
int ret = ne_simple_propfind(
session, item_data.remotepath, NE_DEPTH_ONE,
properties_fileattr, wdfs_readdir_propfind_callback, &item_data);
/* handle the redirect and retry the propfind with the redirect target */
if (ret == NE_REDIRECT && wdfs.redirect == true) {
if (handle_redirect(&item_data.remotepath))
return -ENOENT;
ret = ne_simple_propfind(
session, item_data.remotepath, NE_DEPTH_ONE,
properties_fileattr, wdfs_readdir_propfind_callback, &item_data);
}
if (ret != NE_OK) {
fprintf(stderr, "## PROPFIND error in %s(): %s\n",
__func__, ne_get_error(session));
FREE(item_data.remotepath);
return -ENOENT;
}
struct stat st;
memset(&st, 0, sizeof(st));
st.st_mode = S_IFDIR | 0777;
filler(buf, ".", &st, 0);
filler(buf, "..", &st, 0);
FREE(item_data.remotepath);
return 0;
}
/* author jens, 13.08.2005 11:22:20, location: unknown, refactored in goettingen
* get the file from the server already at open() and write the data to a new
* filehandle. also create a "struct open_file" to store the filehandle. */
static int wdfs_open(const char *localpath, struct fuse_file_info *fi)
{
if (wdfs.debug == true) {
print_debug_infos(__func__, localpath);
fprintf(stderr,
">> %s() by PID %d\n", __func__, fuse_get_context()->pid);
}
assert(localpath && &fi);
struct open_file *file = g_new0(struct open_file, 1);
file->modified = false;
file->fh = get_filehandle();
if (file->fh == -1)
return -EIO;
char *remotepath;
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
remotepath = svn_get_remotepath(localpath);
else
remotepath = get_remotepath(localpath);
if (remotepath == NULL) {
FREE(file);
return -ENOMEM;
}
/* try to lock, if locking is enabled and file is not below svn_basedir. */
if (wdfs.locking_mode != NO_LOCK &&
!g_str_has_prefix(localpath, svn_basedir)) {
if (lockfile(remotepath, wdfs.locking_timeout)) {
/* locking the file is not possible, because the file is locked by
* somebody else. read-only access is allowed. */
if ((fi->flags & O_ACCMODE) == O_RDONLY) {
fprintf(stderr,
"## error: file %s is already locked. "
"allowing read-only (O_RDONLY) access!\n", remotepath);
} else {
FREE(file);
FREE(remotepath);
return -EACCES;
}
}
}
/* GET the data to the filehandle even if the file is opened O_WRONLY,
* because the opening application could use pwrite() or use O_APPEND
* and than the data needs to be present. */
if (ne_get(session, remotepath, file->fh)) {
fprintf(stderr, "## GET error: %s\n", ne_get_error(session));
FREE(remotepath);
return -ENOENT;
}
FREE(remotepath);
/* save our "struct open_file" to the fuse filehandle
* this looks like a dirty hack too me, but it's the fuse way... */
fi->fh = (unsigned long)file;
return 0;
}
/* reads data from the filehandle with pread() to fulfill read requests */
static int wdfs_read(
const char *localpath, char *buf, size_t size,
off_t offset, struct fuse_file_info *fi)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath && buf && &fi);
struct open_file *file = (struct open_file*)(uintptr_t)fi->fh;
int ret = pread(file->fh, buf, size, offset);
if (ret < 0) {
fprintf(stderr, "## pread() error: %d\n", ret);
return -EIO;
}
return ret;
}
/* writes data to the filehandle with pwrite() to fulfill write requests */
static int wdfs_write(
const char *localpath, const char *buf, size_t size,
off_t offset, struct fuse_file_info *fi)
{
+
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath && buf && &fi);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
return -EROFS;
struct open_file *file = (struct open_file*)(uintptr_t)fi->fh;
int ret = pwrite(file->fh, buf, size, offset);
if (ret < 0) {
fprintf(stderr, "## pwrite() error: %d\n", ret);
return -EIO;
}
/* set this flag, to indicate that data has been modified and needs to be
* put to the webdav server. */
file->modified = true;
return ret;
}
/* author jens, 13.08.2005 11:28:40, location: unknown, refactored in goettingen
* wdfs_release is called by fuse, when the last reference to the filehandle is
* removed. this happens if the file is closed. after closing the file it's
* time to put it to the server, but only if it was modified. */
static int wdfs_release(const char *localpath, struct fuse_file_info *fi)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
struct open_file *file = (struct open_file*)(uintptr_t)fi->fh;
char *remotepath = get_remotepath(localpath);
if (remotepath == NULL)
return -ENOMEM;
/* put the file only to the server, if it was modified. */
if (file->modified == true) {
if (ne_put(session, remotepath, file->fh)) {
fprintf(stderr, "## PUT error: %s\n", ne_get_error(session));
FREE(remotepath);
return -EIO;
}
if (wdfs.debug == true)
fprintf(stderr, ">> wdfs_release(): PUT the file to the server.\n");
/* attributes for this file are no longer up to date.
* so remove it from cache. */
cache_delete_item(remotepath);
/* unlock if locking is enabled and mode is ADVANCED_LOCK, because data
* has been read and writen and so now it's time to remove the lock. */
if (wdfs.locking_mode == ADVANCED_LOCK) {
if (unlockfile(remotepath)) {
FREE(remotepath);
return -EACCES;
}
}
}
/* if locking is enabled and mode is SIMPLE_LOCK, simple unlock on close() */
if (wdfs.locking_mode == SIMPLE_LOCK) {
if (unlockfile(remotepath)) {
FREE(remotepath);
return -EACCES;
}
}
/* close filehandle and free memory */
close(file->fh);
FREE(file);
FREE(remotepath);
return 0;
}
/* author jens, 13.08.2005 11:32:20, location: unknown, refactored in goettingen
* wdfs_truncate is called by fuse, when a file is opened with the O_TRUNC flag
* or truncate() is called. according to 'man truncate' if the file previously
* was larger than this size, the extra data is lost. if the file previously
* was shorter, it is extended, and the extended part is filled with zero bytes.
*/
static int wdfs_truncate(const char *localpath, off_t size)
{
if (wdfs.debug == true) {
print_debug_infos(__func__, localpath);
fprintf(stderr, ">> truncate() at offset %li\n", (long int)size);
}
assert(localpath);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
return -EROFS;
/* the truncate procedure:
* 1. get the complete file and write into fh_in
* 2. read size bytes from fh_in to buffer
* 3. write size bytes from buffer to fh_out
* 4. read from fh_out and put file to the server
*/
char *remotepath = get_remotepath(localpath);
if (remotepath == NULL)
return -ENOMEM;
int ret;
int fh_in = get_filehandle();
int fh_out = get_filehandle();
if (fh_in == -1 || fh_out == -1)
return -EIO;
char buffer[size];
memset(buffer, 0, size);
/* if truncate(0) is called, there is no need to get the data, because it
* would not be used. */
if (size != 0) {
if (ne_get(session, remotepath, fh_in)) {
fprintf(stderr, "## GET error: %s\n", ne_get_error(session));
close(fh_in);
close(fh_out);
FREE(remotepath);
return -ENOENT;
}
ret = pread(fh_in, buffer, size, 0);
if (ret < 0) {
fprintf(stderr, "## pread() error: %d\n", ret);
close(fh_in);
close(fh_out);
FREE(remotepath);
return -EIO;
}
}
ret = pwrite(fh_out, buffer, size, 0);
if (ret < 0) {
fprintf(stderr, "## pwrite() error: %d\n", ret);
close(fh_in);
close(fh_out);
FREE(remotepath);
return -EIO;
}
if (ne_put(session, remotepath, fh_out)) {
fprintf(stderr, "## PUT error: %s\n", ne_get_error(session));
close(fh_in);
close(fh_out);
FREE(remotepath);
return -EIO;
}
/* stat for this file is no longer up to date. remove it from the cache. */
cache_delete_item(remotepath);
close(fh_in);
close(fh_out);
FREE(remotepath);
return 0;
}
/* author jens, 12.03.2006 19:44:23, location: goettingen in the winter
* ftruncate is called on already opened files, truncate on not yet opened
* files. ftruncate is supported since wdfs 1.2.0 and needs at least
* fuse 2.5.0 and linux kernel 2.6.15. */
static int wdfs_ftruncate(
const char *localpath, off_t size, struct fuse_file_info *fi)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath && &fi);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
return -EROFS;
char *remotepath = get_remotepath(localpath);
if (remotepath == NULL)
return -ENOMEM;
struct open_file *file = (struct open_file*)(uintptr_t)fi->fh;
int ret = ftruncate(file->fh, size);
if (ret < 0) {
fprintf(stderr, "## ftruncate() error: %d\n", ret);
FREE(remotepath);
return -EIO;
}
/* set this flag, to indicate that data has been modified and needs to be
* put to the webdav server. */
file->modified = true;
/* update the cache item of the ftruncate()d file */
struct stat stat;
if (cache_get_item(&stat, remotepath) < 0) {
fprintf(stderr,
"## cache_get_item() error: item '%s' not found!\n", remotepath);
FREE(remotepath);
return -EIO;
}
/* set the new size after the ftruncate() call */
stat.st_size = size;
/* calculate number of 512 byte blocks */
stat.st_blocks = (stat.st_size + 511) / 512;
/* update the cache */
cache_add_item(&stat, remotepath);
FREE(remotepath);
return 0;
}
+/* author waitman, 08.11.2015 implement create for fuse */
+static int wdfs_create(const char *localpath, mode_t mode, struct fuse_file_info *fi)
+{
+
+ int ret;
+ dev_t rdev;
+ rdev = (dev_t)0;
+
+ ret = wdfs_mknod(localpath,mode,rdev);
+ if (ret!=0)
+ {
+ return ret;
+ }
+ ret = wdfs_open(localpath, fi);
+ return ret;
+
+}
+
+
/* author jens, 28.07.2005 18:15:12, location: noedlers garden in trubenhausen
* this method creates a empty file using the webdav method put. */
static int wdfs_mknod(const char *localpath, mode_t mode, dev_t rdev)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath);
+
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
return -EROFS;
+
+
char *remotepath = get_remotepath(localpath);
if (remotepath == NULL)
return -ENOMEM;
+
+
int fh = get_filehandle();
if (fh == -1) {
FREE(remotepath);
return -EIO;
}
+
+
if (ne_put(session, remotepath, fh)) {
fprintf(stderr, "## PUT error: %s\n", ne_get_error(session));
close(fh);
FREE(remotepath);
return -EIO;
}
+
close(fh);
FREE(remotepath);
return 0;
}
/* author jens, 03.08.2005 12:03:40, location: goettingen
* this method creates a directory / collection using the webdav method mkcol. */
static int wdfs_mkdir(const char *localpath, mode_t mode)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
return -EROFS;
char *remotepath = get_remotepath(localpath);
if (remotepath == NULL)
return -ENOMEM;
if (ne_mkcol(session, remotepath)) {
fprintf(stderr, "MKCOL error: %s\n", ne_get_error(session));
FREE(remotepath);
return -ENOENT;
}
FREE(remotepath);
return 0;
}
/* author jens, 30.07.2005 13:08:11, location: heli at heinemanns
* this methods removes a file or directory using the webdav method delete. */
static int wdfs_unlink(const char *localpath)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
assert(localpath);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true && g_str_has_prefix(localpath, svn_basedir))
return -EROFS;
char *remotepath = get_remotepath(localpath);
if (remotepath == NULL)
return -ENOMEM;
/* unlock the file, to be able to unlink it */
if (wdfs.locking_mode != NO_LOCK) {
if (unlockfile(remotepath)) {
FREE(remotepath);
return -EACCES;
}
}
int ret = ne_delete(session, remotepath);
if (ret == NE_REDIRECT && wdfs.redirect == true) {
if (handle_redirect(&remotepath))
return -ENOENT;
ret = ne_delete(session, remotepath);
}
/* file successfully deleted! remove it also from the cache. */
if (ret == 0) {
cache_delete_item(remotepath);
/* return more specific error message in case of permission problems */
} else if (!strcmp(ne_get_error(session), "403 Forbidden")) {
ret = -EPERM;
} else {
fprintf(stderr, "## DELETE error: %s\n", ne_get_error(session));
ret = -EIO;
}
FREE(remotepath);
return ret;
}
/* author jens, 31.07.2005 19:13:39, location: heli at heinemanns
* this methods renames a file. it uses the webdav method move to do that. */
static int wdfs_rename(const char *localpath_src, const char *localpath_dest)
{
if (wdfs.debug == true) {
print_debug_infos(__func__, localpath_src);
print_debug_infos(__func__, localpath_dest);
}
assert(localpath_src && localpath_dest);
/* data below svn_basedir is read-only */
if (wdfs.svn_mode == true &&
(g_str_has_prefix(localpath_src, svn_basedir) ||
g_str_has_prefix(localpath_dest, svn_basedir)))
return -EROFS;
char *remotepath_src = get_remotepath(localpath_src);
char *remotepath_dest = get_remotepath(localpath_dest);
if (remotepath_src == NULL || remotepath_dest == NULL )
return -ENOMEM;
/* unlock the source file, before renaming */
if (wdfs.locking_mode != NO_LOCK) {
if (unlockfile(remotepath_src)) {
FREE(remotepath_src);
return -EACCES;
}
}
int ret = ne_move(session, 1, remotepath_src, remotepath_dest);
if (ret == NE_REDIRECT && wdfs.redirect == true) {
if (handle_redirect(&remotepath_src))
return -ENOENT;
ret = ne_move(session, 1, remotepath_src, remotepath_dest);
}
if (ret == 0) {
/* rename was successful and the source file no longer exists.
* hence, remove it from the cache. */
cache_delete_item(remotepath_src);
} else {
fprintf(stderr, "## MOVE error: %s\n", ne_get_error(session));
ret = -EIO;
}
free_chars(&remotepath_src, &remotepath_dest, NULL);
return ret;
}
/* this is just a dummy implementation to avoid errors, when running chmod. */
int wdfs_chmod(const char *localpath, mode_t mode)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
fprintf(stderr, "## error: chmod() is not (yet) implemented.\n");
return 0;
}
/* this is just a dummy implementation to avoid errors, when setting attributes.
* a usefull implementation is not possible, because the webdav standard only
* defines a "getlastmodified" property that is read-only and just updated when
* the file's content or properties change. */
static int wdfs_setattr(const char *localpath, struct utimbuf *buf)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
return 0;
}
/* this is a dummy implementation that pretends to have 1000 GB free space :D */
static int wdfs_statfs(const char *localpath, struct statvfs *buf)
{
if (wdfs.debug == true)
print_debug_infos(__func__, localpath);
/* taken from sshfs v1.7, thanks miklos! */
buf->f_bsize = 512;
buf->f_blocks = buf->f_bfree = buf->f_bavail =
1000ULL * 1024 * 1024 * 1024 / buf->f_bsize;
buf->f_files = buf->f_ffree = 1000000000;
return 0;
}
/* just say hello when fuse takes over control. */
#if FUSE_VERSION >= 26
static void* wdfs_init(struct fuse_conn_info *conn)
#else
static void* wdfs_init()
#endif
{
if (wdfs.debug == true)
fprintf(stderr, ">> %s()\n", __func__);
return NULL;
}
/* author jens, 04.08.2005 17:41:12, location: goettingen
* this method is called, when the filesystems is unmounted. time to clean up! */
static void wdfs_destroy()
{
if (wdfs.debug == true)
fprintf(stderr, ">> freeing globaly used memory\n");
/* free globaly used memory */
cache_destroy();
unlock_all_files();
ne_session_destroy(session);
FREE(remotepath_basedir);
svn_free_repository_root();
}
static struct fuse_operations wdfs_operations = {
+ .create = wdfs_create,
.getattr = wdfs_getattr,
.readdir = wdfs_readdir,
.open = wdfs_open,
.read = wdfs_read,
.write = wdfs_write,
.release = wdfs_release,
.truncate = wdfs_truncate,
.ftruncate = wdfs_ftruncate,
.mknod = wdfs_mknod,
.mkdir = wdfs_mkdir,
/* webdav treats file and directory deletions equal, both use wdfs_unlink */
.unlink = wdfs_unlink,
.rmdir = wdfs_unlink,
.rename = wdfs_rename,
.chmod = wdfs_chmod,
/* utime should be better named setattr
* see: http://sourceforge.net/mailarchive/message.php?msg_id=11344401 */
.utime = wdfs_setattr,
.statfs = wdfs_statfs,
.init = wdfs_init,
.destroy = wdfs_destroy,
};
/* author jens, 26.08.2005 12:26:59, location: lystrup near aarhus
* this method prints help and usage information, call fuse to print its
* help information. */
static void print_help()
{
fprintf(stderr,
"usage: %s http[s]://server[:port][/directory/] mountpoint [options]\n\n"
"wdfs options:\n"
" -v, --version show version of wdfs\n"
" -vv, --all-versions show versions of wdfs, neon and fuse\n"
" -h, --help show this help page\n"
" -D, -o wdfs_debug enable wdfs debug output\n"
" -o accept_sslcert accept ssl certificate, don't prompt the user\n"
" -o username=arg replace arg with username of the webdav resource\n"
" -o password=arg replace arg with password of the webdav resource\n"
" username/password can also be entered interactively\n"
" -o no_redirect disable http redirect support\n"
" -o svn_mode enable subversion mode to access all revisions\n"
" -o locking same as -o locking=simple\n"
" -o locking=mode select a file locking mode:\n"
" 0 or none: disable file locking (default)\n"
" 1 or simple: from open until close\n"
" 2 or advanced: from open until write + close\n"
" 3 or eternity: from open until umount or timeout\n"
" -o locking_timeout=sec timeout for a lock in seconds, -1 means infinite\n"
" default is 300 seconds (5 minutes)\n\n"
"wdfs backwards compatibility options: (used until wdfs 1.3.1)\n"
" -a uri address of the webdav resource to mount\n"
" -ac same as -o accept_sslcert\n"
" -u arg same as -o username=arg\n"
" -p arg same as -o password=arg\n"
" -S same as -o svn_mode\n"
" -l same as -o locking=simple\n"
" -m locking_mode same as -o locking=mode (only numerical modes)\n"
" -t seconds same as -o locking_timeout=sec\n\n",
wdfs.program_name);
}
/* just a simple wrapper for fuse_main(), because the interface changed... */
static int call_fuse_main(struct fuse_args *args)
{
#if FUSE_VERSION >= 26
return fuse_main(args->argc, args->argv, &wdfs_operations, NULL);
#else
return fuse_main(args->argc, args->argv, &wdfs_operations);
#endif
}
/* the main method does the option parsing using fuse_opt_parse(), establishes
* the connection to the webdav resource and finally calls main_fuse(). */
int main(int argc, char *argv[])
{
int status_program_exec = 1;
struct fuse_args options = FUSE_ARGS_INIT(argc, argv);
wdfs.program_name = argv[0];
if (fuse_opt_parse(&options, &wdfs, wdfs_opts, wdfs_opt_proc) == -1)
exit(1);
if (!wdfs.webdav_resource) {
fprintf(stderr, "%s: missing webdav uri\n", wdfs.program_name);
exit(1);
}
if (wdfs.locking_timeout < -1 || wdfs.locking_timeout == 0) {
fprintf(stderr, "## error: timeout must be bigger than 0 or -1!\n");
exit(1);
}
if (wdfs.debug == true) {
fprintf(stderr,
"wdfs settings:\n program_name: %s\n webdav_resource: %s\n"
" accept_certificate: %s\n username: %s\n password: %s\n"
" redirect: %s\n svn_mode: %s\n locking_mode: %i\n"
" locking_timeout: %i\n",
wdfs.program_name,
wdfs.webdav_resource ? wdfs.webdav_resource : "NULL",
wdfs.accept_certificate == true ? "true" : "false",
wdfs.username ? wdfs.username : "NULL",
wdfs.password ? "****" : "NULL",
wdfs.redirect == true ? "true" : "false",
wdfs.svn_mode == true ? "true" : "false",
wdfs.locking_mode, wdfs.locking_timeout);
}
/* set a nice name for /proc/mounts */
char *fsname = ne_concat("-ofsname=wdfs (", wdfs.webdav_resource, ")", NULL);
fuse_opt_add_arg(&options, fsname);
FREE(fsname);
/* ensure that wdfs is called in single thread mode */
fuse_opt_add_arg(&options, "-s");
/* wdfs must not use the fuse caching of names (entries) and attributes! */
fuse_opt_add_arg(&options, "-oentry_timeout=0");
fuse_opt_add_arg(&options, "-oattr_timeout=0");
/* reset parameters to avoid storing sensitive data in the process table */
int arg_number = 1;
for (; arg_number < argc; arg_number++)
memset(argv[arg_number], 0, strlen(argv[arg_number]));
/* set up webdav connection, exit on error */
if (setup_webdav_session(wdfs.webdav_resource, wdfs.username, wdfs.password)) {
status_program_exec = 1;
goto cleanup;
}
if (wdfs.svn_mode == true) {
if(svn_set_repository_root()) {
fprintf(stderr,
"## error: could not set subversion repository root.\n");
ne_session_destroy(session);
status_program_exec = 1;
goto cleanup;
}
}
cache_initialize();
/* finally call fuse */
status_program_exec = call_fuse_main(&options);
/* clean up and quit wdfs */
cleanup:
free_chars(&wdfs.webdav_resource, &wdfs.username, &wdfs.password, NULL);
fuse_opt_free_args(&options);
return status_program_exec;
}
|
codyps/wdfs
|
3a6a8137be2fcc61e06c17cb6a6fdc1cf21829e7
|
fix a remote '500' error due to the lack of a useragent
|
diff --git a/src/webdav.c b/src/webdav.c
index ce4bd35..e54b828 100644
--- a/src/webdav.c
+++ b/src/webdav.c
@@ -1,428 +1,432 @@
/*
* this file is part of wdfs --> http://noedler.de/projekte/wdfs/
*
* wdfs is a webdav filesystem with special features for accessing subversion
* repositories. it is based on fuse v2.5+ and neon v0.24.7+.
*
* copyright (c) 2005 - 2007 jens m. noedler, [email protected]
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* This program is released under the GPL with the additional exemption
* that compiling, linking and/or using OpenSSL is allowed.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <termios.h>
#include <ne_basic.h>
#include <ne_auth.h>
#include <ne_locks.h>
#include <ne_socket.h>
#include <ne_redirect.h>
#include "wdfs-main.h"
#include "webdav.h"
/* used to authorize at the webdav server */
struct ne_auth_data {
const char *username;
const char *password;
};
ne_session *session;
ne_lock_store *store = NULL;
struct ne_auth_data auth_data;
/* reads from the terminal without displaying the typed chars. used to type
* the password savely. */
static int fgets_hidden(char *lineptr, size_t n, FILE *stream)
{
struct termios settings_old, settings_new;
int ret = 0;
if (isatty(fileno(stream))) {
/* turn echoing off and fail if we can't */
if (tcgetattr(fileno(stream), &settings_old) == 0) {
settings_new = settings_old;
settings_new.c_lflag &= ~ECHO;
if (tcsetattr(fileno(stream), TCSAFLUSH, &settings_new) == 0)
ret = 1;
}
}
else
ret = 1;
/* read the password */
if (ret == 1 && fgets(lineptr, n, stream) == NULL)
ret = 0;
if (isatty(fileno(stream)))
/* restore terminal */
(void) tcsetattr(fileno(stream), TCSAFLUSH, &settings_old);
return ret;
}
/* this method is envoked, if the server requires authentication */
static int ne_set_server_auth_callback(
void *userdata, const char *realm,
int attempt, char *username, char *password)
{
const size_t length = 100;
char buffer[length];
/* ask the user for the username and password if needed */
if (auth_data.username == NULL) {
printf("username: ");
if (fgets(buffer, length, stdin)) {
int len = strlen(buffer);
if (buffer[len - 1] == '\n')
buffer[len - 1] = '\0';
auth_data.username = strdup(buffer);
}
}
if (auth_data.password == NULL) {
printf("password: ");
if (fgets_hidden(buffer, length, stdin)) {
int len = strlen(buffer);
if (buffer[len - 1] == '\n')
buffer[len - 1] = '\0';
auth_data.password = strdup(buffer);
}
printf("\n");
}
assert(auth_data.username && auth_data.password);
strncpy(username, auth_data.username, NE_ABUFSIZ);
strncpy(password, auth_data.password, NE_ABUFSIZ);
return attempt;
}
/* this is called from ne_ssl_set_verify() if there is something wrong with the
* ssl certificate. */
static int verify_ssl_certificate(
void *userdata, int failures, const ne_ssl_certificate *certificate)
{
ne_uri *uri = (ne_uri*)userdata;
char from[NE_SSL_VDATELEN], to[NE_SSL_VDATELEN];
const char *ident;
ident = ne_ssl_cert_identity(certificate);
if (ident) {
fprintf(stderr,
"WARNING: untrusted server certificate for '%s':\n", ident);
}
if (failures & NE_SSL_IDMISMATCH) {
fprintf(stderr,
" certificate was issued to hostname '%s' rather than '%s'\n",
ne_ssl_cert_identity(certificate), uri->host);
fprintf(stderr, " this connection could have been intercepted!\n");
}
ne_ssl_cert_validity(certificate, from, to);
printf(" certificate is valid from %s to %s\n", from, to);
if (failures & NE_SSL_EXPIRED)
fprintf(stderr, " >> certificate expired! <<\n");
char *issued_to = ne_ssl_readable_dname(ne_ssl_cert_subject(certificate));
char *issued_by = ne_ssl_readable_dname(ne_ssl_cert_issuer(certificate));
printf(" issued to: %s\n", issued_to);
printf(" issued by: %s\n", issued_by);
free_chars(&issued_to, &issued_by, NULL);
/* don't prompt the user if the parameter "-ac" was passed to wdfs */
if (wdfs.accept_certificate == true)
return 0;
/* prompt the user wether he/she wants to accept this certificate */
int answer;
while (1) {
printf(" do you wish to accept this certificate? (y/n) ");
answer = getchar();
/* delete the input buffer (if the char is not a newline) */
if (answer != '\n')
while (getchar() != '\n');
/* stop asking if the answer was 'y' or 'n' */
if (answer == 'y' || answer == 'n')
break;
}
if (answer == 'y') {
return 0;
} else {
printf(" certificate rejected.\n");
return -1;
}
}
/* sets up a webdav connection. if the servers needs authentication, the passed
* parameters username and password are used. if they were not passed they can
* be entered interactively. this method returns 0 on success or -1 on error. */
int setup_webdav_session(
const char *uri_string, const char *username, const char *password)
{
assert(uri_string);
auth_data.username = username;
auth_data.password = password;
/* parse the uri_string and return a uri struct */
ne_uri uri;
if (ne_uri_parse(uri_string, &uri)) {
fprintf(stderr,
"## ne_uri_parse() error: invalid URI '%s'.\n", uri_string);
ne_uri_free(&uri);
return -1;
}
assert(uri.scheme && uri.host && uri.path);
/* if no port was defined use the default port */
uri.port = uri.port ? uri.port : ne_uri_defaultport(uri.scheme);
+ ne_debug_init(stderr,0);
+
/* needed for ssl connections. it's not documented. nice to know... ;-) */
ne_sock_init();
/* create a session object, that allows to access the server */
session = ne_session_create(uri.scheme, uri.host, uri.port);
/* init ssl if needed */
if (!strcasecmp(uri.scheme, "https")) {
#if NEON_VERSION >= 25
if (ne_has_support(NE_FEATURE_SSL)) {
#else
if (ne_supports_ssl()) {
#endif
ne_ssl_trust_default_ca(session);
ne_ssl_set_verify(session, verify_ssl_certificate, &uri);
} else {
fprintf(stderr, "## error: neon ssl support is not enabled.\n");
ne_session_destroy(session);
ne_uri_free(&uri);
return -1;
}
}
/* enable this for on-demand authentication */
ne_set_server_auth(session, ne_set_server_auth_callback, NULL);
/* enable redirect support */
ne_redirect_register(session);
/* escape the path for the case that it contains special chars */
char *path = unify_path(uri.path, ESCAPE | LEAVESLASH);
if (path == NULL) {
printf("## error: unify_path() returned NULL\n");
ne_session_destroy(session);
ne_uri_free(&uri);
return -1;
}
+ ne_set_useragent(session,"wdfs");
+
/* try to access the server */
ne_server_capabilities capabilities;
int ret = ne_options(session, path, &capabilities);
if (ret != NE_OK) {
fprintf(stderr,
"## error: could not mount remote server '%s'. ", uri_string);
fprintf(stderr, "reason: %s", ne_get_error(session));
/* if we got a redirect, print the new destination uri and exit */
if (ret == NE_REDIRECT) {
const ne_uri *new_uri = ne_redirect_location(session);
char *new_uri_string = ne_uri_unparse(new_uri);
fprintf(stderr, " to '%s'", new_uri_string);
FREE(new_uri_string);
}
fprintf(stderr, ".\n");
ne_session_destroy(session);
ne_uri_free(&uri);
FREE(path);
return -1;
}
FREE(path);
/* is this a webdav server that fulfills webdav class 1? */
if (capabilities.dav_class1 != 1) {
fprintf(stderr,
"## error: '%s' is not a webdav enabled server.\n", uri_string);
ne_session_destroy(session);
ne_uri_free(&uri);
return -1;
}
/* set a useragent string, to identify wdfs in the server log files */
ne_set_useragent(session, project_name);
/* save the remotepath, because each fuse callback method need it to
* access the files at the webdav server */
remotepath_basedir = remove_ending_slashes(uri.path);
if (remotepath_basedir == NULL) {
ne_session_destroy(session);
ne_uri_free(&uri);
return -1;
}
ne_uri_free(&uri);
return 0;
}
/* +++++++ locking methods +++++++ */
/* returns the lock for this file from the lockstore on success
* or NULL if the lock is not found in the lockstore. */
static struct ne_lock* get_lock_by_path(const char *remotepath)
{
assert(remotepath);
/* unless the lockstore is initialized, no lock can be found */
if (store == NULL)
return NULL;
/* generate a ne_uri object to find the lock by its uri */
ne_uri uri;
uri.path = (char *)remotepath;
ne_fill_server_uri(session, &uri);
/* find the lock for this uri in the lockstore */
struct ne_lock *lock = NULL;
lock = ne_lockstore_findbyuri(store, &uri);
/* ne_fill_server_uri() malloc()d these fields, time to free them */
free_chars(&uri.scheme, &uri.host, NULL);
return lock;
}
/* tries to lock the file and returns 0 on success and 1 on error */
int lockfile(const char *remotepath, const int timeout)
{
assert(remotepath && timeout);
/* initialize the lockstore, if needed (e.g. first locking a file). */
if (store == NULL) {
store = ne_lockstore_create();
if (store == NULL)
return 1;
ne_lockstore_register(store, session);
}
/* check, if we already hold a lock for this file */
struct ne_lock *lock = get_lock_by_path(remotepath);
/* we already hold a lock for this file, simply return 0 */
if (lock != NULL) {
if (wdfs.debug == true)
fprintf(stderr, "++ file '%s' is already locked.\n", remotepath);
return 0;
}
/* otherwise lock the file exclusivly */
lock = ne_lock_create();
enum ne_lock_scope scope = ne_lockscope_exclusive;
lock->scope = scope;
lock->owner = ne_concat("wdfs, user: ", getenv("USER"), NULL);
lock->timeout = timeout;
lock->depth = NE_DEPTH_ZERO;
ne_fill_server_uri(session, &lock->uri);
lock->uri.path = ne_strdup(remotepath);
if (ne_lock(session, lock)) {
fprintf(stderr, "## ne_lock() error:\n");
fprintf(stderr, "## could _not_ lock file '%s'.\n", lock->uri.path);
ne_lock_destroy(lock);
return 1;
} else {
ne_lockstore_add(store, lock);
if (wdfs.debug == true)
fprintf(stderr, "++ locked file '%s'.\n", remotepath);
}
return 0;
}
/* tries to unlock the file and returns 0 on success and 1 on error */
int unlockfile(const char *remotepath)
{
assert(remotepath);
struct ne_lock *lock = get_lock_by_path(remotepath);
/* if the lock was not found, the file is already unlocked */
if (lock == NULL)
return 0;
/* if the lock was found, unlock the file */
if (ne_unlock(session, lock)) {
fprintf(stderr, "## ne_unlock() error:\n");
fprintf(stderr, "## could _not_ unlock file '%s'.\n", lock->uri.path);
ne_lock_destroy(lock);
return 1;
} else {
/* on success remove the lock from the store and destroy the lock */
ne_lockstore_remove(store, lock);
ne_lock_destroy(lock);
if (wdfs.debug == true)
fprintf(stderr, "++ unlocked file '%s'.\n", remotepath);
}
return 0;
}
/* this method unlocks all files of the lockstore and destroys the lockstore */
void unlock_all_files()
{
/* only unlock all files, if the lockstore is initialized */
if (store != NULL) {
/* get each lock from the lockstore and try to unlock the file */
struct ne_lock *this_lock = NULL;
this_lock = ne_lockstore_first(store);
while (this_lock != NULL) {
if (ne_unlock(session, this_lock)) {
fprintf(stderr,
"## ne_unlock() error:\n"
"## could _not_ unlock file '%s'.\n", this_lock->uri.path);
} else {
if (wdfs.debug == true)
fprintf(stderr,
"++ unlocked file '%s'.\n", this_lock->uri.path);
}
/* get the next lock from the lockstore */
this_lock = ne_lockstore_next(store);
}
/* finally destroy the lockstore */
if (wdfs.debug == true)
fprintf(stderr, "++ destroying lockstore.\n");
ne_lockstore_destroy(store);
}
}
|
Spacerat/BlitzIRC
|
59142f15f828cdc235d9827aeaee0f164277aa2e
|
Indicate if build is threaded. Send input in threaded mode.
|
diff --git a/SpaceBot/spacebot.bmx b/SpaceBot/spacebot.bmx
index dc72bd4..865546a 100644
--- a/SpaceBot/spacebot.bmx
+++ b/SpaceBot/spacebot.bmx
@@ -1,32 +1,36 @@
SuperStrict
Framework brl.blitz
Import "irc.bmx"
Import "Modules/debug.bmx"
Import "Modules/ping.bmx"
Global SBConfig:IRCClientConfig = New IRCClientConfig
Global SBClient:IRCClient = New IRCClient
+?Threaded
+Print "THREADING ENABLED"
+?
+
SBConfig.SetServer("irc.ajaxlife.net")
SBConfig.SetNick("SpaceBot")
SBConfig.SetName("SpaceBot")
SBConfig.SetIdent("spacebot")
SBClient.Connect(SBConfig)
-SBClient.Send("JOIN #spacebot")
+
?threaded
SBClient.BeginThread()
Global terminate:Int = False
While Not terminate
- If Input() = "" terminate = 1
+ SBClient.Send(TInput(">"))
EndWhile
?Not threaded
IRCClientThread(SBClient)
?
|
Spacerat/BlitzIRC
|
7d0c63702b8659f1c32dadf517c74ea428d6157d
|
Ping actually works now.
|
diff --git a/SpaceBot/Modules/ping.bmx b/SpaceBot/Modules/ping.bmx
index 7c6ff73..ddfe1ee 100644
--- a/SpaceBot/Modules/ping.bmx
+++ b/SpaceBot/Modules/ping.bmx
@@ -1,15 +1,16 @@
SuperStrict
Import "../irc.bmx"
AddHook(IRCClient.INHOOK, IRCPingPong, Null)
Function IRCPingPong:Object(id:Int, data:Object, context:Object)
Local event:IRCEvent = IRCEvent(data)
If Not event Return Null
If event.GetCommand() = "PING"
- event.GetClient().Send("PONG :"+event._hostmask)
+ event.GetClient().Send("PONG :" + event.GetMessage())
End If
+ Return data
End Function
|
Spacerat/BlitzIRC
|
bee822a9e41b3cc6cc1f42d0c5e81d38e7cdc792
|
Client remembers its nick and config object.
|
diff --git a/SpaceBot/irc.bmx b/SpaceBot/irc.bmx
index 77bb32f..3feb504 100644
--- a/SpaceBot/irc.bmx
+++ b/SpaceBot/irc.bmx
@@ -1,291 +1,310 @@
SuperStrict
Import brl.threads
Import brl.socketstream
Import brl.textstream
Import brl.hook
Import brl.linkedlist
Rem
bbdoc: IRC Event object
about: This object is passed to IRC hook functions in the same way TEvent is used by BRL.
EndRem
Type IRCEvent
Field _client:IRCClient
Field _data:String
Field _hookid:Int
Field _hostmask:String
Field _user:String
Field _host:String
Field _command:String
Field _params:String[]
Field _message:String
Rem
bbdoc: Create an IRC Event object
about: id is the hook id. data is the message as a string.
returns: The new IRCEvent
EndRem
Function Create:IRCEvent(id:Int, client:IRCClient, data:String)
If Not client Throw "IRC Event must have a valid client"
Local n:IRCEvent = New IRCEvent
n._hookid = id
n._client = client
n.SetData(data)
Return n
EndFunction
Rem
bbdoc: Sets the data associated with this message
about: Also parses the data and splits its different parts.
EndRem
Method SetData(data:String)
Local parts:String[]
Local cindex:Int = 0
Local params:TList = New TList
_data = data
parts = _data.Split(" ")
If _data[0] = Asc(":")
cindex = 1
parts = _data[1..].Split(" ")
_hostmask = parts[0].Split("!")[0]
If parts[0].Split("!").Dimensions()[0] > 1
_user = parts[0].Split("!")[1].Split("@")[0]
_host = parts[0].Split("!")[1].Split("@")[1]
EndIf
End If
_command = parts[cindex]
If _data.Find(" :") > 0 Then
_message = _data.Split(" :")[1]
parts = _data.Split(" :")[0].Split(" ")
EndIf
Local paramcount:Int = 0
For Local i:Int = cindex + 1 To parts.Dimensions()[0] - 1
If parts[i][0] = Asc(":") Exit
paramcount:+1
Next
_params = New String[paramcount]
For Local i:Int = cindex + 1 To parts.Dimensions()[0] - 1
_params[i - cindex - 1] = parts[i]
Next
EndMethod
'#Region Get/Set methods
Rem
bbdoc: Get the full message string
EndRem
Method GetData:String()
Return _data
End Method
Rem
bbdoc: Get the IRC client object
EndRem
Method GetClient:IRCClient()
Return _client
End Method
Rem
bbdoc: Get the command string
EndRem
Method GetCommand:String()
Return _command
End Method
Rem
bbdoc: Get an array of parameters
EndRem
Method GetParams:String[] ()
Return _params
End Method
Rem
bbdoc: Get the servername/nickname
EndRem
Method GetNickname:String()
Return _hostmask
End Method
Rem
bbdoc: Get the host address
EndRem
Method GetHost:String()
Return _host
End Method
Rem
bbdoc: Get the message/trailing parameter
EndRem
Method GetMessage:String()
Return _message
EndMethod
Rem
bbdoc: Get the user/ident
EndRem
Method GetUser:String()
Return _user
End Method
'#End Region
End Type
Rem
bbdoc: IRC Configuration struct
about: Stores information about a network and connection info for it.
EndRem
Type IRCClientConfig
Field _Network:String
Field _Port:Int = 6667
Field _Nick:String
Field _Name:String
Field _Ident:String
'#Region Get/Set methods
Rem
bbdoc: Set the server and port
EndRem
Method SetServer(network:String, port:Int = 6667)
_Network = network
_Port = port
End Method
Rem
bbdoc: Set the nick
EndRem
Method SetNick(nick:String)
_Nick = nick
End Method
Rem
bbdoc: Set the real name
EndRem
Method SetName(name:String)
_Name = name
End Method
Rem
bbdoc: Set the ident
EndRem
Method SetIdent(ident:String)
_Ident = ident
End Method
'#End Region
End Type
Rem
bbdoc: The main IRC client type
EndRem
Type IRCClient
Global OUTHOOK:Int = AllocHookId()
Global INHOOK:Int = AllocHookId()
Field _socket:TSocket
Field _stream:TSocketStream
Field _utf8:TTextStream
Field _running:Int = False
+
+ Field _config:IRCClientConfig
+ Field _nick:String
Rem
bbdoc: Connect to a server
EndRem
Method Connect:Int(config:IRCClientConfig)
'Attempt a TCP connection
_socket = TSocket.CreateTCP()
_socket.Connect(HostIp(config._Network), config._Port)
_stream = CreateSocketStream(_socket)
_utf8 = TTextStream.Create(_stream, TTextStream.UTF8)
Send("NICK " + config._Nick)
Send("USER " + config._Nick + " " + config._Ident + " 8* :" + config._Name)
_running = True
+
+ _config = config
+ _nick = _config._Nick
+
EndMethod
Rem
bbdoc: Start the thread
EndRem
?threaded
Method BeginThread:TThread()
Return TThread.Create(IRCClientThread, Self)
End Method
?Not threaded
Method BeginThread:Object()
Return Null
End Method
?
Rem
bbdoc: Send a string to the server
EndRem
Method Send(line:String, utf8:Int = True)
RunIRCHookThread(IRCEvent.Create(OUTHOOK, Self, line))
If utf8
_utf8.WriteLine(line)
Else
_stream.WriteLine(line)
EndIf
End Method
Rem
bbdoc: Execute a client cycle.
EndRem
Method Run()
While Not _stream.Eof()
Local line:String = _stream.ReadLine()
RunIRCHookThread(IRCEvent.Create(INHOOK, Self, line))
Wend
End Method
'#Region Get/Set/Is methods
Method IsRunning:Int()
Return _running
End Method
+
+ Method GetConfig:IRCClientConfig()
+ Return _config
+ End Method
+
+ Method GetNick:String()
+ Return _nick
+ End Method
+
+ Method GetIdent:String()
+ Return _config._Ident
+ End Method
'#End Region
EndType
Rem
bbdoc: Run an IRC Event in a new thread.
returns: The new thread in threaded mode, otherwise returns the IRC hook data.
EndRem
?threaded
Function RunIRCHookThread:TThread(event:IRCEvent)
?Not threaded
Function RunIRCHookThread:Object(event:IRCEvent)
?
?threaded
Return TThread.Create(IRCHookThread, event)
?Not threaded
Return IRCHookThread(event)
?
EndFunction
Function IRCClientThread:Object(data:Object)
Local client:IRCClient = IRCClient(data)
If Not client Return Null
While client.IsRunning()
client.Run()
Wend
End Function
Function IRCHookThread:Object(data:Object)
Local event:IRCEvent = IRCEvent(data)
If (event)
Return RunHooks(event._hookid, event)
End If
End Function
|
Spacerat/BlitzIRC
|
58558cda0ebb80718550359d961e8b1ad6e777a4
|
Added origin to pong.
|
diff --git a/SpaceBot/Modules/ping.bmx b/SpaceBot/Modules/ping.bmx
index fc6f911..7c6ff73 100644
--- a/SpaceBot/Modules/ping.bmx
+++ b/SpaceBot/Modules/ping.bmx
@@ -1,15 +1,15 @@
SuperStrict
Import "../irc.bmx"
AddHook(IRCClient.INHOOK, IRCPingPong, Null)
Function IRCPingPong:Object(id:Int, data:Object, context:Object)
Local event:IRCEvent = IRCEvent(data)
If Not event Return Null
If event.GetCommand() = "PING"
- event.GetClient().Send("PONG")
+ event.GetClient().Send("PONG :"+event._hostmask)
End If
End Function
|
Spacerat/BlitzIRC
|
bd3ac7e94e46e55a8c9871d52468fadd90cf29ab
|
Another USER string correction.
|
diff --git a/SpaceBot/irc.bmx b/SpaceBot/irc.bmx
index d844284..77bb32f 100644
--- a/SpaceBot/irc.bmx
+++ b/SpaceBot/irc.bmx
@@ -1,291 +1,291 @@
SuperStrict
Import brl.threads
Import brl.socketstream
Import brl.textstream
Import brl.hook
Import brl.linkedlist
Rem
bbdoc: IRC Event object
about: This object is passed to IRC hook functions in the same way TEvent is used by BRL.
EndRem
Type IRCEvent
Field _client:IRCClient
Field _data:String
Field _hookid:Int
Field _hostmask:String
Field _user:String
Field _host:String
Field _command:String
Field _params:String[]
Field _message:String
Rem
bbdoc: Create an IRC Event object
about: id is the hook id. data is the message as a string.
returns: The new IRCEvent
EndRem
Function Create:IRCEvent(id:Int, client:IRCClient, data:String)
If Not client Throw "IRC Event must have a valid client"
Local n:IRCEvent = New IRCEvent
n._hookid = id
n._client = client
n.SetData(data)
Return n
EndFunction
Rem
bbdoc: Sets the data associated with this message
about: Also parses the data and splits its different parts.
EndRem
Method SetData(data:String)
Local parts:String[]
Local cindex:Int = 0
Local params:TList = New TList
_data = data
parts = _data.Split(" ")
If _data[0] = Asc(":")
cindex = 1
parts = _data[1..].Split(" ")
_hostmask = parts[0].Split("!")[0]
If parts[0].Split("!").Dimensions()[0] > 1
_user = parts[0].Split("!")[1].Split("@")[0]
_host = parts[0].Split("!")[1].Split("@")[1]
EndIf
End If
_command = parts[cindex]
If _data.Find(" :") > 0 Then
_message = _data.Split(" :")[1]
parts = _data.Split(" :")[0].Split(" ")
EndIf
Local paramcount:Int = 0
For Local i:Int = cindex + 1 To parts.Dimensions()[0] - 1
If parts[i][0] = Asc(":") Exit
paramcount:+1
Next
_params = New String[paramcount]
For Local i:Int = cindex + 1 To parts.Dimensions()[0] - 1
_params[i - cindex - 1] = parts[i]
Next
EndMethod
'#Region Get/Set methods
Rem
bbdoc: Get the full message string
EndRem
Method GetData:String()
Return _data
End Method
Rem
bbdoc: Get the IRC client object
EndRem
Method GetClient:IRCClient()
Return _client
End Method
Rem
bbdoc: Get the command string
EndRem
Method GetCommand:String()
Return _command
End Method
Rem
bbdoc: Get an array of parameters
EndRem
Method GetParams:String[] ()
Return _params
End Method
Rem
bbdoc: Get the servername/nickname
EndRem
Method GetNickname:String()
Return _hostmask
End Method
Rem
bbdoc: Get the host address
EndRem
Method GetHost:String()
Return _host
End Method
Rem
bbdoc: Get the message/trailing parameter
EndRem
Method GetMessage:String()
Return _message
EndMethod
Rem
bbdoc: Get the user/ident
EndRem
Method GetUser:String()
Return _user
End Method
'#End Region
End Type
Rem
bbdoc: IRC Configuration struct
about: Stores information about a network and connection info for it.
EndRem
Type IRCClientConfig
Field _Network:String
Field _Port:Int = 6667
Field _Nick:String
Field _Name:String
Field _Ident:String
'#Region Get/Set methods
Rem
bbdoc: Set the server and port
EndRem
Method SetServer(network:String, port:Int = 6667)
_Network = network
_Port = port
End Method
Rem
bbdoc: Set the nick
EndRem
Method SetNick(nick:String)
_Nick = nick
End Method
Rem
bbdoc: Set the real name
EndRem
Method SetName(name:String)
_Name = name
End Method
Rem
bbdoc: Set the ident
EndRem
Method SetIdent(ident:String)
_Ident = ident
End Method
'#End Region
End Type
Rem
bbdoc: The main IRC client type
EndRem
Type IRCClient
Global OUTHOOK:Int = AllocHookId()
Global INHOOK:Int = AllocHookId()
Field _socket:TSocket
Field _stream:TSocketStream
Field _utf8:TTextStream
Field _running:Int = False
Rem
bbdoc: Connect to a server
EndRem
Method Connect:Int(config:IRCClientConfig)
'Attempt a TCP connection
_socket = TSocket.CreateTCP()
_socket.Connect(HostIp(config._Network), config._Port)
_stream = CreateSocketStream(_socket)
_utf8 = TTextStream.Create(_stream, TTextStream.UTF8)
Send("NICK " + config._Nick)
- Send("USER " + config._Nick + " 8* :" + config._Name)
+ Send("USER " + config._Nick + " " + config._Ident + " 8* :" + config._Name)
_running = True
EndMethod
Rem
bbdoc: Start the thread
EndRem
?threaded
Method BeginThread:TThread()
Return TThread.Create(IRCClientThread, Self)
End Method
?Not threaded
Method BeginThread:Object()
Return Null
End Method
?
Rem
bbdoc: Send a string to the server
EndRem
Method Send(line:String, utf8:Int = True)
RunIRCHookThread(IRCEvent.Create(OUTHOOK, Self, line))
If utf8
_utf8.WriteLine(line)
Else
_stream.WriteLine(line)
EndIf
End Method
Rem
bbdoc: Execute a client cycle.
EndRem
Method Run()
While Not _stream.Eof()
Local line:String = _stream.ReadLine()
RunIRCHookThread(IRCEvent.Create(INHOOK, Self, line))
Wend
End Method
'#Region Get/Set/Is methods
Method IsRunning:Int()
Return _running
End Method
'#End Region
EndType
Rem
bbdoc: Run an IRC Event in a new thread.
returns: The new thread in threaded mode, otherwise returns the IRC hook data.
EndRem
?threaded
Function RunIRCHookThread:TThread(event:IRCEvent)
?Not threaded
Function RunIRCHookThread:Object(event:IRCEvent)
?
?threaded
Return TThread.Create(IRCHookThread, event)
?Not threaded
Return IRCHookThread(event)
?
EndFunction
Function IRCClientThread:Object(data:Object)
Local client:IRCClient = IRCClient(data)
If Not client Return Null
While client.IsRunning()
client.Run()
Wend
End Function
Function IRCHookThread:Object(data:Object)
Local event:IRCEvent = IRCEvent(data)
If (event)
Return RunHooks(event._hookid, event)
End If
End Function
|
Spacerat/BlitzIRC
|
31cee5210509a6c70acb76d31b7c21a3684a3dda
|
Comitted PING/PONG module.
|
diff --git a/SpaceBot/Modules/ping.bmx b/SpaceBot/Modules/ping.bmx
new file mode 100644
index 0000000..fc6f911
--- /dev/null
+++ b/SpaceBot/Modules/ping.bmx
@@ -0,0 +1,15 @@
+SuperStrict
+
+Import "../irc.bmx"
+
+AddHook(IRCClient.INHOOK, IRCPingPong, Null)
+
+Function IRCPingPong:Object(id:Int, data:Object, context:Object)
+ Local event:IRCEvent = IRCEvent(data)
+ If Not event Return Null
+
+ If event.GetCommand() = "PING"
+ event.GetClient().Send("PONG")
+ End If
+
+End Function
diff --git a/SpaceBot/spacebot.bmx b/SpaceBot/spacebot.bmx
index c00e534..dc72bd4 100644
--- a/SpaceBot/spacebot.bmx
+++ b/SpaceBot/spacebot.bmx
@@ -1,31 +1,32 @@
SuperStrict
Framework brl.blitz
Import "irc.bmx"
Import "Modules/debug.bmx"
+Import "Modules/ping.bmx"
Global SBConfig:IRCClientConfig = New IRCClientConfig
Global SBClient:IRCClient = New IRCClient
SBConfig.SetServer("irc.ajaxlife.net")
SBConfig.SetNick("SpaceBot")
SBConfig.SetName("SpaceBot")
SBConfig.SetIdent("spacebot")
SBClient.Connect(SBConfig)
SBClient.Send("JOIN #spacebot")
?threaded
SBClient.BeginThread()
Global terminate:Int = False
While Not terminate
If Input() = "" terminate = 1
EndWhile
?Not threaded
IRCClientThread(SBClient)
?
|
Spacerat/BlitzIRC
|
98e79f0f258a910a84759c06c87f61af030f7a2a
|
Fixed USER string.
|
diff --git a/SpaceBot/irc.bmx b/SpaceBot/irc.bmx
index bd6a530..d844284 100644
--- a/SpaceBot/irc.bmx
+++ b/SpaceBot/irc.bmx
@@ -1,291 +1,291 @@
SuperStrict
Import brl.threads
Import brl.socketstream
Import brl.textstream
Import brl.hook
Import brl.linkedlist
Rem
bbdoc: IRC Event object
about: This object is passed to IRC hook functions in the same way TEvent is used by BRL.
EndRem
Type IRCEvent
Field _client:IRCClient
Field _data:String
Field _hookid:Int
Field _hostmask:String
Field _user:String
Field _host:String
Field _command:String
Field _params:String[]
Field _message:String
Rem
bbdoc: Create an IRC Event object
about: id is the hook id. data is the message as a string.
returns: The new IRCEvent
EndRem
Function Create:IRCEvent(id:Int, client:IRCClient, data:String)
If Not client Throw "IRC Event must have a valid client"
Local n:IRCEvent = New IRCEvent
n._hookid = id
n._client = client
n.SetData(data)
Return n
EndFunction
Rem
bbdoc: Sets the data associated with this message
about: Also parses the data and splits its different parts.
EndRem
Method SetData(data:String)
Local parts:String[]
Local cindex:Int = 0
Local params:TList = New TList
_data = data
parts = _data.Split(" ")
If _data[0] = Asc(":")
cindex = 1
parts = _data[1..].Split(" ")
_hostmask = parts[0].Split("!")[0]
If parts[0].Split("!").Dimensions()[0] > 1
_user = parts[0].Split("!")[1].Split("@")[0]
_host = parts[0].Split("!")[1].Split("@")[1]
EndIf
End If
_command = parts[cindex]
If _data.Find(" :") > 0 Then
_message = _data.Split(" :")[1]
parts = _data.Split(" :")[0].Split(" ")
EndIf
Local paramcount:Int = 0
For Local i:Int = cindex + 1 To parts.Dimensions()[0] - 1
If parts[i][0] = Asc(":") Exit
paramcount:+1
Next
_params = New String[paramcount]
For Local i:Int = cindex + 1 To parts.Dimensions()[0] - 1
_params[i - cindex - 1] = parts[i]
Next
EndMethod
'#Region Get/Set methods
Rem
bbdoc: Get the full message string
EndRem
Method GetData:String()
Return _data
End Method
Rem
bbdoc: Get the IRC client object
EndRem
Method GetClient:IRCClient()
Return _client
End Method
Rem
bbdoc: Get the command string
EndRem
Method GetCommand:String()
Return _command
End Method
Rem
bbdoc: Get an array of parameters
EndRem
Method GetParams:String[] ()
Return _params
End Method
Rem
bbdoc: Get the servername/nickname
EndRem
Method GetNickname:String()
Return _hostmask
End Method
Rem
bbdoc: Get the host address
EndRem
Method GetHost:String()
Return _host
End Method
Rem
bbdoc: Get the message/trailing parameter
EndRem
Method GetMessage:String()
Return _message
EndMethod
Rem
bbdoc: Get the user/ident
EndRem
Method GetUser:String()
Return _user
End Method
'#End Region
End Type
Rem
bbdoc: IRC Configuration struct
about: Stores information about a network and connection info for it.
EndRem
Type IRCClientConfig
Field _Network:String
Field _Port:Int = 6667
Field _Nick:String
Field _Name:String
Field _Ident:String
'#Region Get/Set methods
Rem
bbdoc: Set the server and port
EndRem
Method SetServer(network:String, port:Int = 6667)
_Network = network
_Port = port
End Method
Rem
bbdoc: Set the nick
EndRem
Method SetNick(nick:String)
_Nick = nick
End Method
Rem
bbdoc: Set the real name
EndRem
Method SetName(name:String)
_Name = name
End Method
Rem
bbdoc: Set the ident
EndRem
Method SetIdent(ident:String)
_Ident = ident
End Method
'#End Region
End Type
Rem
bbdoc: The main IRC client type
EndRem
Type IRCClient
Global OUTHOOK:Int = AllocHookId()
Global INHOOK:Int = AllocHookId()
Field _socket:TSocket
Field _stream:TSocketStream
Field _utf8:TTextStream
Field _running:Int = False
Rem
bbdoc: Connect to a server
EndRem
Method Connect:Int(config:IRCClientConfig)
'Attempt a TCP connection
_socket = TSocket.CreateTCP()
_socket.Connect(HostIp(config._Network), config._Port)
_stream = CreateSocketStream(_socket)
_utf8 = TTextStream.Create(_stream, TTextStream.UTF8)
Send("NICK " + config._Nick)
- Send("USER " + config._Nick + " 8 * :" + config._Name)
+ Send("USER " + config._Nick + " 8* :" + config._Name)
_running = True
EndMethod
Rem
bbdoc: Start the thread
EndRem
?threaded
Method BeginThread:TThread()
Return TThread.Create(IRCClientThread, Self)
End Method
?Not threaded
Method BeginThread:Object()
Return Null
End Method
?
Rem
bbdoc: Send a string to the server
EndRem
Method Send(line:String, utf8:Int = True)
RunIRCHookThread(IRCEvent.Create(OUTHOOK, Self, line))
If utf8
_utf8.WriteLine(line)
Else
_stream.WriteLine(line)
EndIf
End Method
Rem
bbdoc: Execute a client cycle.
EndRem
Method Run()
While Not _stream.Eof()
Local line:String = _stream.ReadLine()
RunIRCHookThread(IRCEvent.Create(INHOOK, Self, line))
Wend
End Method
'#Region Get/Set/Is methods
Method IsRunning:Int()
Return _running
End Method
'#End Region
EndType
Rem
bbdoc: Run an IRC Event in a new thread.
returns: The new thread in threaded mode, otherwise returns the IRC hook data.
EndRem
?threaded
Function RunIRCHookThread:TThread(event:IRCEvent)
?Not threaded
Function RunIRCHookThread:Object(event:IRCEvent)
?
?threaded
Return TThread.Create(IRCHookThread, event)
?Not threaded
Return IRCHookThread(event)
?
EndFunction
Function IRCClientThread:Object(data:Object)
Local client:IRCClient = IRCClient(data)
If Not client Return Null
While client.IsRunning()
client.Run()
Wend
End Function
Function IRCHookThread:Object(data:Object)
Local event:IRCEvent = IRCEvent(data)
If (event)
Return RunHooks(event._hookid, event)
End If
End Function
|
Spacerat/BlitzIRC
|
6aec4979875fe1a8632e0d569eb118df7d69bda5
|
Parse() is now SetData(data:String)
|
diff --git a/SpaceBot/irc.bmx b/SpaceBot/irc.bmx
index fe8d176..bd6a530 100644
--- a/SpaceBot/irc.bmx
+++ b/SpaceBot/irc.bmx
@@ -1,288 +1,291 @@
SuperStrict
Import brl.threads
Import brl.socketstream
Import brl.textstream
Import brl.hook
Import brl.linkedlist
Rem
bbdoc: IRC Event object
about: This object is passed to IRC hook functions in the same way TEvent is used by BRL.
EndRem
Type IRCEvent
Field _client:IRCClient
Field _data:String
Field _hookid:Int
Field _hostmask:String
Field _user:String
Field _host:String
Field _command:String
Field _params:String[]
Field _message:String
Rem
bbdoc: Create an IRC Event object
about: id is the hook id. data is the message as a string.
returns: The new IRCEvent
EndRem
Function Create:IRCEvent(id:Int, client:IRCClient, data:String)
If Not client Throw "IRC Event must have a valid client"
Local n:IRCEvent = New IRCEvent
n._hookid = id
n._client = client
- n._data = data.Trim()
- n.Parse()
+ n.SetData(data)
Return n
EndFunction
- Method Parse()
+ Rem
+ bbdoc: Sets the data associated with this message
+ about: Also parses the data and splits its different parts.
+ EndRem
+ Method SetData(data:String)
Local parts:String[]
Local cindex:Int = 0
Local params:TList = New TList
+ _data = data
parts = _data.Split(" ")
- ' DebugStop
+
If _data[0] = Asc(":")
cindex = 1
parts = _data[1..].Split(" ")
_hostmask = parts[0].Split("!")[0]
If parts[0].Split("!").Dimensions()[0] > 1
_user = parts[0].Split("!")[1].Split("@")[0]
_host = parts[0].Split("!")[1].Split("@")[1]
EndIf
End If
_command = parts[cindex]
If _data.Find(" :") > 0 Then
- 'Local pstring:String
_message = _data.Split(" :")[1]
parts = _data.Split(" :")[0].Split(" ")
EndIf
Local paramcount:Int = 0
For Local i:Int = cindex + 1 To parts.Dimensions()[0] - 1
If parts[i][0] = Asc(":") Exit
paramcount:+1
Next
_params = New String[paramcount]
For Local i:Int = cindex + 1 To parts.Dimensions()[0] - 1
_params[i - cindex - 1] = parts[i]
Next
EndMethod
'#Region Get/Set methods
Rem
bbdoc: Get the full message string
EndRem
Method GetData:String()
Return _data
End Method
Rem
bbdoc: Get the IRC client object
EndRem
Method GetClient:IRCClient()
Return _client
End Method
Rem
bbdoc: Get the command string
EndRem
Method GetCommand:String()
Return _command
End Method
Rem
bbdoc: Get an array of parameters
EndRem
Method GetParams:String[] ()
Return _params
End Method
Rem
bbdoc: Get the servername/nickname
EndRem
Method GetNickname:String()
Return _hostmask
End Method
Rem
bbdoc: Get the host address
EndRem
Method GetHost:String()
Return _host
End Method
Rem
bbdoc: Get the message/trailing parameter
EndRem
Method GetMessage:String()
Return _message
EndMethod
Rem
bbdoc: Get the user/ident
EndRem
Method GetUser:String()
Return _user
End Method
'#End Region
End Type
Rem
bbdoc: IRC Configuration struct
about: Stores information about a network and connection info for it.
EndRem
Type IRCClientConfig
Field _Network:String
Field _Port:Int = 6667
Field _Nick:String
Field _Name:String
Field _Ident:String
'#Region Get/Set methods
Rem
bbdoc: Set the server and port
EndRem
Method SetServer(network:String, port:Int = 6667)
_Network = network
_Port = port
End Method
Rem
bbdoc: Set the nick
EndRem
Method SetNick(nick:String)
_Nick = nick
End Method
Rem
bbdoc: Set the real name
EndRem
Method SetName(name:String)
_Name = name
End Method
Rem
bbdoc: Set the ident
EndRem
Method SetIdent(ident:String)
_Ident = ident
End Method
'#End Region
End Type
Rem
bbdoc: The main IRC client type
EndRem
Type IRCClient
Global OUTHOOK:Int = AllocHookId()
Global INHOOK:Int = AllocHookId()
Field _socket:TSocket
Field _stream:TSocketStream
Field _utf8:TTextStream
Field _running:Int = False
Rem
bbdoc: Connect to a server
EndRem
Method Connect:Int(config:IRCClientConfig)
'Attempt a TCP connection
_socket = TSocket.CreateTCP()
_socket.Connect(HostIp(config._Network), config._Port)
_stream = CreateSocketStream(_socket)
_utf8 = TTextStream.Create(_stream, TTextStream.UTF8)
Send("NICK " + config._Nick)
Send("USER " + config._Nick + " 8 * :" + config._Name)
_running = True
EndMethod
Rem
bbdoc: Start the thread
EndRem
?threaded
Method BeginThread:TThread()
Return TThread.Create(IRCClientThread, Self)
End Method
?Not threaded
Method BeginThread:Object()
Return Null
End Method
?
Rem
bbdoc: Send a string to the server
EndRem
Method Send(line:String, utf8:Int = True)
RunIRCHookThread(IRCEvent.Create(OUTHOOK, Self, line))
If utf8
_utf8.WriteLine(line)
Else
_stream.WriteLine(line)
EndIf
End Method
Rem
bbdoc: Execute a client cycle.
EndRem
Method Run()
While Not _stream.Eof()
Local line:String = _stream.ReadLine()
RunIRCHookThread(IRCEvent.Create(INHOOK, Self, line))
Wend
End Method
'#Region Get/Set/Is methods
Method IsRunning:Int()
Return _running
End Method
'#End Region
EndType
Rem
bbdoc: Run an IRC Event in a new thread.
returns: The new thread in threaded mode, otherwise returns the IRC hook data.
EndRem
?threaded
Function RunIRCHookThread:TThread(event:IRCEvent)
?Not threaded
Function RunIRCHookThread:Object(event:IRCEvent)
?
?threaded
Return TThread.Create(IRCHookThread, event)
?Not threaded
Return IRCHookThread(event)
?
EndFunction
Function IRCClientThread:Object(data:Object)
Local client:IRCClient = IRCClient(data)
If Not client Return Null
While client.IsRunning()
client.Run()
Wend
End Function
Function IRCHookThread:Object(data:Object)
Local event:IRCEvent = IRCEvent(data)
If (event)
Return RunHooks(event._hookid, event)
End If
End Function
|
Spacerat/BlitzIRC
|
e7c3d3757c027f937c2b5f9855f1732868008e9f
|
Added more get methods to IRCEvent.
|
diff --git a/SpaceBot/irc.bmx b/SpaceBot/irc.bmx
index b01d8f7..fe8d176 100644
--- a/SpaceBot/irc.bmx
+++ b/SpaceBot/irc.bmx
@@ -1,240 +1,288 @@
SuperStrict
Import brl.threads
Import brl.socketstream
Import brl.textstream
Import brl.hook
Import brl.linkedlist
-Import joe.threadedio
Rem
bbdoc: IRC Event object
about: This object is passed to IRC hook functions in the same way TEvent is used by BRL.
EndRem
Type IRCEvent
Field _client:IRCClient
Field _data:String
Field _hookid:Int
Field _hostmask:String
Field _user:String
Field _host:String
Field _command:String
Field _params:String[]
Field _message:String
Rem
bbdoc: Create an IRC Event object
about: id is the hook id. data is the message as a string.
returns: The new IRCEvent
EndRem
Function Create:IRCEvent(id:Int, client:IRCClient, data:String)
If Not client Throw "IRC Event must have a valid client"
Local n:IRCEvent = New IRCEvent
n._hookid = id
n._client = client
n._data = data.Trim()
n.Parse()
Return n
EndFunction
Method Parse()
Local parts:String[]
Local cindex:Int = 0
Local params:TList = New TList
parts = _data.Split(" ")
' DebugStop
If _data[0] = Asc(":")
cindex = 1
parts = _data[1..].Split(" ")
_hostmask = parts[0].Split("!")[0]
If parts[0].Split("!").Dimensions()[0] > 1
_user = parts[0].Split("!")[1].Split("@")[0]
_host = parts[0].Split("!")[1].Split("@")[1]
EndIf
End If
_command = parts[cindex]
If _data.Find(" :") > 0 Then
'Local pstring:String
_message = _data.Split(" :")[1]
parts = _data.Split(" :")[0].Split(" ")
EndIf
Local paramcount:Int = 0
For Local i:Int = cindex + 1 To parts.Dimensions()[0] - 1
If parts[i][0] = Asc(":") Exit
paramcount:+1
Next
_params = New String[paramcount]
For Local i:Int = cindex + 1 To parts.Dimensions()[0] - 1
_params[i - cindex - 1] = parts[i]
Next
EndMethod
'#Region Get/Set methods
Rem
- bbdoc: Get the message data
+ bbdoc: Get the full message string
EndRem
Method GetData:String()
Return _data
End Method
+
+ Rem
+ bbdoc: Get the IRC client object
+ EndRem
+ Method GetClient:IRCClient()
+ Return _client
+ End Method
+
+ Rem
+ bbdoc: Get the command string
+ EndRem
+ Method GetCommand:String()
+ Return _command
+ End Method
+
+ Rem
+ bbdoc: Get an array of parameters
+ EndRem
+ Method GetParams:String[] ()
+ Return _params
+ End Method
+
+ Rem
+ bbdoc: Get the servername/nickname
+ EndRem
+ Method GetNickname:String()
+ Return _hostmask
+ End Method
+
+ Rem
+ bbdoc: Get the host address
+ EndRem
+ Method GetHost:String()
+ Return _host
+ End Method
+
+ Rem
+ bbdoc: Get the message/trailing parameter
+ EndRem
+ Method GetMessage:String()
+ Return _message
+ EndMethod
+
+ Rem
+ bbdoc: Get the user/ident
+ EndRem
+ Method GetUser:String()
+ Return _user
+ End Method
'#End Region
End Type
Rem
bbdoc: IRC Configuration struct
about: Stores information about a network and connection info for it.
EndRem
Type IRCClientConfig
Field _Network:String
Field _Port:Int = 6667
Field _Nick:String
Field _Name:String
Field _Ident:String
'#Region Get/Set methods
Rem
bbdoc: Set the server and port
EndRem
Method SetServer(network:String, port:Int = 6667)
_Network = network
_Port = port
End Method
Rem
bbdoc: Set the nick
EndRem
Method SetNick(nick:String)
_Nick = nick
End Method
Rem
bbdoc: Set the real name
EndRem
Method SetName(name:String)
_Name = name
End Method
Rem
bbdoc: Set the ident
EndRem
Method SetIdent(ident:String)
_Ident = ident
End Method
'#End Region
End Type
Rem
bbdoc: The main IRC client type
EndRem
Type IRCClient
Global OUTHOOK:Int = AllocHookId()
Global INHOOK:Int = AllocHookId()
Field _socket:TSocket
Field _stream:TSocketStream
Field _utf8:TTextStream
Field _running:Int = False
Rem
bbdoc: Connect to a server
EndRem
Method Connect:Int(config:IRCClientConfig)
'Attempt a TCP connection
_socket = TSocket.CreateTCP()
_socket.Connect(HostIp(config._Network), config._Port)
_stream = CreateSocketStream(_socket)
_utf8 = TTextStream.Create(_stream, TTextStream.UTF8)
Send("NICK " + config._Nick)
Send("USER " + config._Nick + " 8 * :" + config._Name)
_running = True
EndMethod
Rem
bbdoc: Start the thread
EndRem
?threaded
Method BeginThread:TThread()
Return TThread.Create(IRCClientThread, Self)
End Method
?Not threaded
Method BeginThread:Object()
Return Null
End Method
?
Rem
bbdoc: Send a string to the server
EndRem
Method Send(line:String, utf8:Int = True)
RunIRCHookThread(IRCEvent.Create(OUTHOOK, Self, line))
If utf8
_utf8.WriteLine(line)
Else
_stream.WriteLine(line)
EndIf
End Method
Rem
bbdoc: Execute a client cycle.
EndRem
Method Run()
While Not _stream.Eof()
Local line:String = _stream.ReadLine()
RunIRCHookThread(IRCEvent.Create(INHOOK, Self, line))
Wend
End Method
'#Region Get/Set/Is methods
Method IsRunning:Int()
Return _running
End Method
'#End Region
EndType
Rem
bbdoc: Run an IRC Event in a new thread.
-returns: The new thread
+returns: The new thread in threaded mode, otherwise returns the IRC hook data.
EndRem
?threaded
Function RunIRCHookThread:TThread(event:IRCEvent)
?Not threaded
Function RunIRCHookThread:Object(event:IRCEvent)
?
?threaded
Return TThread.Create(IRCHookThread, event)
?Not threaded
Return IRCHookThread(event)
?
EndFunction
Function IRCClientThread:Object(data:Object)
Local client:IRCClient = IRCClient(data)
If Not client Return Null
While client.IsRunning()
client.Run()
Wend
End Function
Function IRCHookThread:Object(data:Object)
Local event:IRCEvent = IRCEvent(data)
If (event)
Return RunHooks(event._hookid, event)
End If
End Function
|
Spacerat/BlitzIRC
|
99f6f3d29b1ac4b15a90cfb46a94b760b76d02c9
|
Added SuperStrict
|
diff --git a/SpaceBot/Modules/debug.bmx b/SpaceBot/Modules/debug.bmx
index 20bf4fb..1e9348c 100644
--- a/SpaceBot/Modules/debug.bmx
+++ b/SpaceBot/Modules/debug.bmx
@@ -1,21 +1,22 @@
+SuperStrict
+
Import joe.threadedio
Import "../irc.bmx"
-
AddHook(IRCClient.OUTHOOK, PrintIRCOutput, Null)
AddHook(IRCClient.INHOOK, PrintIRCInput, Null)
Function PrintIRCOutput:Object(id:Int, data:Object, context:Object)
Local event:IRCEvent = IRCEvent(data)
If Not event Return Null
TPrint("OUTPUT: " + event.GetData())
Return data
End Function
Function PrintIRCInput:Object(id:Int, data:Object, context:Object)
Local event:IRCEvent = IRCEvent(data)
If Not event Return Null
TPrint("INPUT: " + event.GetData())
Return data
End Function
|
Spacerat/BlitzIRC
|
75f2d01e5ae6957063968f1d05d8cef3ef0625d5
|
Added non-thread support; finished the message parser.
|
diff --git a/SpaceBot/irc.bmx b/SpaceBot/irc.bmx
index 7221468..b01d8f7 100644
--- a/SpaceBot/irc.bmx
+++ b/SpaceBot/irc.bmx
@@ -1,208 +1,240 @@
SuperStrict
Import brl.threads
Import brl.socketstream
Import brl.textstream
Import brl.hook
+Import brl.linkedlist
+Import joe.threadedio
Rem
bbdoc: IRC Event object
about: This object is passed to IRC hook functions in the same way TEvent is used by BRL.
EndRem
Type IRCEvent
Field _client:IRCClient
Field _data:String
Field _hookid:Int
Field _hostmask:String
Field _user:String
Field _host:String
Field _command:String
- Field _middle:String
+ Field _params:String[]
Field _message:String
Rem
bbdoc: Create an IRC Event object
about: id is the hook id. data is the message as a string.
returns: The new IRCEvent
EndRem
Function Create:IRCEvent(id:Int, client:IRCClient, data:String)
If Not client Throw "IRC Event must have a valid client"
Local n:IRCEvent = New IRCEvent
n._hookid = id
n._client = client
- n._data = data
+ n._data = data.Trim()
n.Parse()
Return n
EndFunction
Method Parse()
Local parts:String[]
- If _data[0] = ":"
- parts = _data.Split(" ")
- _hostmask = parts[0].Split(":")[0]
- _user = parts[0].Split(":")[1].Split("@")[0]
- _host = parts[0].Split(":")[1].Split("@")[1]
+ Local cindex:Int = 0
+ Local params:TList = New TList
+ parts = _data.Split(" ")
+ ' DebugStop
+ If _data[0] = Asc(":")
+ cindex = 1
+ parts = _data[1..].Split(" ")
+ _hostmask = parts[0].Split("!")[0]
+ If parts[0].Split("!").Dimensions()[0] > 1
+ _user = parts[0].Split("!")[1].Split("@")[0]
+ _host = parts[0].Split("!")[1].Split("@")[1]
+ EndIf
End If
- parts = _data.Split(" :")
+ _command = parts[cindex]
+ If _data.Find(" :") > 0 Then
+ 'Local pstring:String
+ _message = _data.Split(" :")[1]
+ parts = _data.Split(" :")[0].Split(" ")
+ EndIf
+
+
+ Local paramcount:Int = 0
+ For Local i:Int = cindex + 1 To parts.Dimensions()[0] - 1
+ If parts[i][0] = Asc(":") Exit
+ paramcount:+1
+ Next
+ _params = New String[paramcount]
+
+ For Local i:Int = cindex + 1 To parts.Dimensions()[0] - 1
+ _params[i - cindex - 1] = parts[i]
+ Next
EndMethod
'#Region Get/Set methods
Rem
bbdoc: Get the message data
EndRem
Method GetData:String()
Return _data
End Method
'#End Region
End Type
Rem
bbdoc: IRC Configuration struct
about: Stores information about a network and connection info for it.
EndRem
Type IRCClientConfig
Field _Network:String
Field _Port:Int = 6667
Field _Nick:String
Field _Name:String
Field _Ident:String
'#Region Get/Set methods
Rem
bbdoc: Set the server and port
EndRem
Method SetServer(network:String, port:Int = 6667)
_Network = network
_Port = port
End Method
Rem
bbdoc: Set the nick
EndRem
Method SetNick(nick:String)
_Nick = nick
End Method
Rem
bbdoc: Set the real name
EndRem
Method SetName(name:String)
_Name = name
End Method
Rem
bbdoc: Set the ident
EndRem
Method SetIdent(ident:String)
_Ident = ident
End Method
'#End Region
End Type
Rem
bbdoc: The main IRC client type
EndRem
Type IRCClient
Global OUTHOOK:Int = AllocHookId()
Global INHOOK:Int = AllocHookId()
Field _socket:TSocket
Field _stream:TSocketStream
Field _utf8:TTextStream
Field _running:Int = False
Rem
bbdoc: Connect to a server
EndRem
Method Connect:Int(config:IRCClientConfig)
'Attempt a TCP connection
_socket = TSocket.CreateTCP()
_socket.Connect(HostIp(config._Network), config._Port)
_stream = CreateSocketStream(_socket)
_utf8 = TTextStream.Create(_stream, TTextStream.UTF8)
Send("NICK " + config._Nick)
Send("USER " + config._Nick + " 8 * :" + config._Name)
_running = True
EndMethod
Rem
bbdoc: Start the thread
EndRem
- Method BeginThread:TThread()
- ?threaded
+ ?threaded
+ Method BeginThread:TThread()
Return TThread.Create(IRCClientThread, Self)
- ?
- Throw "ERROR: Cannot create an IRC Client thread in non-threaded mode!"
End Method
-
+ ?Not threaded
+ Method BeginThread:Object()
+ Return Null
+ End Method
+ ?
Rem
bbdoc: Send a string to the server
EndRem
Method Send(line:String, utf8:Int = True)
RunIRCHookThread(IRCEvent.Create(OUTHOOK, Self, line))
If utf8
_utf8.WriteLine(line)
Else
_stream.WriteLine(line)
EndIf
End Method
Rem
bbdoc: Execute a client cycle.
EndRem
Method Run()
While Not _stream.Eof()
Local line:String = _stream.ReadLine()
RunIRCHookThread(IRCEvent.Create(INHOOK, Self, line))
Wend
End Method
'#Region Get/Set/Is methods
Method IsRunning:Int()
Return _running
End Method
'#End Region
EndType
Rem
bbdoc: Run an IRC Event in a new thread.
returns: The new thread
EndRem
+?threaded
Function RunIRCHookThread:TThread(event:IRCEvent)
+?Not threaded
+Function RunIRCHookThread:Object(event:IRCEvent)
+?
?threaded
Return TThread.Create(IRCHookThread, event)
?Not threaded
- IRCHookThread(event)
+ Return IRCHookThread(event)
?
EndFunction
Function IRCClientThread:Object(data:Object)
Local client:IRCClient = IRCClient(data)
If Not client Return Null
While client.IsRunning()
client.Run()
Wend
End Function
Function IRCHookThread:Object(data:Object)
Local event:IRCEvent = IRCEvent(data)
If (event)
Return RunHooks(event._hookid, event)
End If
End Function
|
Spacerat/BlitzIRC
|
62dc477872fc66f7f5b31dcd4efa7f72f013c06d
|
Added code to support threaded and non-threaded mode.
|
diff --git a/SpaceBot/spacebot.bmx b/SpaceBot/spacebot.bmx
index 79a664c..c00e534 100644
--- a/SpaceBot/spacebot.bmx
+++ b/SpaceBot/spacebot.bmx
@@ -1,25 +1,31 @@
SuperStrict
Framework brl.blitz
Import "irc.bmx"
Import "Modules/debug.bmx"
Global SBConfig:IRCClientConfig = New IRCClientConfig
Global SBClient:IRCClient = New IRCClient
SBConfig.SetServer("irc.ajaxlife.net")
SBConfig.SetNick("SpaceBot")
SBConfig.SetName("SpaceBot")
SBConfig.SetIdent("spacebot")
SBClient.Connect(SBConfig)
-SBClient.BeginThread()
SBClient.Send("JOIN #spacebot")
-Global terminate:Int = False
-While Not terminate
- If Input() = "" terminate = 1
-EndWhile
+?threaded
+ SBClient.BeginThread()
+
+ Global terminate:Int = False
+
+ While Not terminate
+ If Input() = "" terminate = 1
+ EndWhile
+?Not threaded
+ IRCClientThread(SBClient)
+?
|
Spacerat/BlitzIRC
|
687af91dc3c4572ebc6a30d526400bbd910b4c25
|
Added the begginings of a decent IRC message parcer.
|
diff --git a/SpaceBot/irc.bmx b/SpaceBot/irc.bmx
index afa5a43..7221468 100644
--- a/SpaceBot/irc.bmx
+++ b/SpaceBot/irc.bmx
@@ -1,185 +1,208 @@
SuperStrict
Import brl.threads
Import brl.socketstream
Import brl.textstream
Import brl.hook
Rem
bbdoc: IRC Event object
about: This object is passed to IRC hook functions in the same way TEvent is used by BRL.
EndRem
Type IRCEvent
- Field _hookid:Int
Field _client:IRCClient
Field _data:String
+ Field _hookid:Int
+
+ Field _hostmask:String
+ Field _user:String
+ Field _host:String
+ Field _command:String
+ Field _middle:String
+ Field _message:String
Rem
bbdoc: Create an IRC Event object
about: id is the hook id. data is the message as a string.
returns: The new IRCEvent
EndRem
Function Create:IRCEvent(id:Int, client:IRCClient, data:String)
If Not client Throw "IRC Event must have a valid client"
Local n:IRCEvent = New IRCEvent
n._hookid = id
n._client = client
n._data = data
+ n.Parse()
+
Return n
EndFunction
+ Method Parse()
+ Local parts:String[]
+ If _data[0] = ":"
+ parts = _data.Split(" ")
+ _hostmask = parts[0].Split(":")[0]
+ _user = parts[0].Split(":")[1].Split("@")[0]
+ _host = parts[0].Split(":")[1].Split("@")[1]
+ End If
+
+ parts = _data.Split(" :")
+
+
+ EndMethod
+
'#Region Get/Set methods
Rem
bbdoc: Get the message data
EndRem
Method GetData:String()
Return _data
End Method
'#End Region
End Type
Rem
bbdoc: IRC Configuration struct
about: Stores information about a network and connection info for it.
EndRem
Type IRCClientConfig
Field _Network:String
Field _Port:Int = 6667
Field _Nick:String
Field _Name:String
Field _Ident:String
'#Region Get/Set methods
Rem
bbdoc: Set the server and port
EndRem
Method SetServer(network:String, port:Int = 6667)
_Network = network
_Port = port
End Method
Rem
bbdoc: Set the nick
EndRem
Method SetNick(nick:String)
_Nick = nick
End Method
Rem
bbdoc: Set the real name
EndRem
Method SetName(name:String)
_Name = name
End Method
Rem
bbdoc: Set the ident
EndRem
Method SetIdent(ident:String)
_Ident = ident
End Method
'#End Region
End Type
Rem
bbdoc: The main IRC client type
EndRem
Type IRCClient
Global OUTHOOK:Int = AllocHookId()
Global INHOOK:Int = AllocHookId()
Field _socket:TSocket
Field _stream:TSocketStream
Field _utf8:TTextStream
Field _running:Int = False
Rem
bbdoc: Connect to a server
EndRem
Method Connect:Int(config:IRCClientConfig)
'Attempt a TCP connection
_socket = TSocket.CreateTCP()
_socket.Connect(HostIp(config._Network), config._Port)
_stream = CreateSocketStream(_socket)
_utf8 = TTextStream.Create(_stream, TTextStream.UTF8)
Send("NICK " + config._Nick)
Send("USER " + config._Nick + " 8 * :" + config._Name)
_running = True
EndMethod
Rem
bbdoc: Start the thread
EndRem
Method BeginThread:TThread()
?threaded
Return TThread.Create(IRCClientThread, Self)
?
Throw "ERROR: Cannot create an IRC Client thread in non-threaded mode!"
End Method
Rem
bbdoc: Send a string to the server
EndRem
Method Send(line:String, utf8:Int = True)
RunIRCHookThread(IRCEvent.Create(OUTHOOK, Self, line))
If utf8
_utf8.WriteLine(line)
Else
_stream.WriteLine(line)
EndIf
End Method
Rem
bbdoc: Execute a client cycle.
EndRem
Method Run()
While Not _stream.Eof()
Local line:String = _stream.ReadLine()
RunIRCHookThread(IRCEvent.Create(INHOOK, Self, line))
Wend
End Method
'#Region Get/Set/Is methods
Method IsRunning:Int()
Return _running
End Method
'#End Region
EndType
Rem
bbdoc: Run an IRC Event in a new thread.
returns: The new thread
EndRem
Function RunIRCHookThread:TThread(event:IRCEvent)
?threaded
Return TThread.Create(IRCHookThread, event)
?Not threaded
IRCHookThread(event)
?
EndFunction
Function IRCClientThread:Object(data:Object)
Local client:IRCClient = IRCClient(data)
If Not client Return Null
While client.IsRunning()
client.Run()
Wend
End Function
Function IRCHookThread:Object(data:Object)
Local event:IRCEvent = IRCEvent(data)
If (event)
Return RunHooks(event._hookid, event)
End If
End Function
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.